0

I am trying to send a json object to a php page demo.php using an 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 is what I tried in jQuery,but it is not rendered on my php page.In php I tried the following:

<html>
       <?php

       $json = json_decode(stripslashes($_POST['data']), true);
       echo var_dump($json);

       ?>

       <body>
       Hello World !!!
       </body>
       </html>

But it is printing a failure in console. Please help me with this.

1
  • 1
    Remove all the HTML from it, it tries to parse an invalid JSON, just encode and echo it (no vardump etc, be sure no notices are generated)! Commented Jun 27, 2014 at 13:43

1 Answer 1

3

Edit: My initial answer was wrong, the reason you get to the error function, is that you have specified:

dataType:'json',

So jQuery expects the output of your php script to be valid json. It is not, you are returning text / html so that is why your success function is never reached.

The way you have setup your php script (outputting html), you probably should just remove:

dataType:'json',

and then you will get to your success function.

By the way, nothing is rendered on your page until you do something (show...) the data variable in your success function:

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

And in your php script you should only send back / echo out what you want to display in your html element, so no html or body tags.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.