jquery - how to send json object in ajax to a php page -


i trying send json object php page demo.php using ajax request

<script type="text/javascript" charset="utf-8"> $(document).ready(function ()  {     var data =      {'name':'sam','id':'1345'};     var test = {}     test["data"] = json.stringify(data);     $("#btnsend").click(function()      {            $.ajax({             type:"post",             url:"/demo.php",             datatype:'json',             data:test,             success: function(data)                  {                console.log('success');                          }             error: function()             {                 console.log('failure');              }         });      });  }); </script> 

this tried in jquery,but not rendered on php page.in php tried following:

<html>        <?php         $json = json_decode(stripslashes($_post['data']), true);        echo var_dump($json);         ?>         <body>        hello world !!!        </body>        </html> 

but printing failure in console. please me this.

edit: initial answer wrong, reason error function, have specified:

datatype:'json', 

so jquery expects output of php script valid json. not, returning text / html why success function never reached.

the way have setup php script (outputting html), should remove:

datatype:'json', 

and success function.

by way, nothing rendered on page until (show...) data variable in success function:

success: function(data) {     console.log('success');     $('#some_element').html(data);    // put output in #some_element } 

and in php script should send / echo out want display in html element, no html or body tags.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -