最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using JQuery to get JSON response from PHP - Stack Overflow

programmeradmin3浏览0评论

I have accumulated and chopped up about 5 or 6 different tutorials of this now, and I still can't find out what's wrong!

Using JQuery Mobile (phonegap) to send and receive data to a PHP server. I cannot seem to get the JQuery script to pick up a response. PHP on server:

<?php

// Set up associative array
$data = array('success'=> true,'message'=>'Success message: worked!');

// JSON encode and send back to the server
echo json_encode($data);

?>

JQuery Function (Which is being called):

<script type="text/javascript">
$(function () {
    $('#inp').keyup(function () {
        var postData = $('#inp').val();
        $.ajax({
            type: "POST",
            dataType: "json",
            data: postData,
            beforeSend: function (x) {
                if (x && x.overrideMimeType) {
                    x.overrideMimeType("application/json;charset=UTF-8");
                }
            },
            url: 'removedmyurlfromhere',
            success: function (data) {
                // 'data' is a JSON object which we can access directly.
                // Evaluate the data.success member and do something appropriate...
                if (data.success == true) {
                    alert('result');
                    $('.results').html(data.message);
                } else {
                    $('.results').html(data.message);
                }
            }
        });
    });
});
</script>

Sorry for the formatting, it all went pair shaped copying it across. Removed my url.

I know that the function is firing, because if I remove the alert('here'); and put it above the ajax call it displays.

Anybody know why the success function isn't calling? nothing shows in the div with class results on any browser.

Thanks!

I have accumulated and chopped up about 5 or 6 different tutorials of this now, and I still can't find out what's wrong!

Using JQuery Mobile (phonegap) to send and receive data to a PHP server. I cannot seem to get the JQuery script to pick up a response. PHP on server:

<?php

// Set up associative array
$data = array('success'=> true,'message'=>'Success message: worked!');

// JSON encode and send back to the server
echo json_encode($data);

?>

JQuery Function (Which is being called):

<script type="text/javascript">
$(function () {
    $('#inp').keyup(function () {
        var postData = $('#inp').val();
        $.ajax({
            type: "POST",
            dataType: "json",
            data: postData,
            beforeSend: function (x) {
                if (x && x.overrideMimeType) {
                    x.overrideMimeType("application/json;charset=UTF-8");
                }
            },
            url: 'removedmyurlfromhere',
            success: function (data) {
                // 'data' is a JSON object which we can access directly.
                // Evaluate the data.success member and do something appropriate...
                if (data.success == true) {
                    alert('result');
                    $('.results').html(data.message);
                } else {
                    $('.results').html(data.message);
                }
            }
        });
    });
});
</script>

Sorry for the formatting, it all went pair shaped copying it across. Removed my url.

I know that the function is firing, because if I remove the alert('here'); and put it above the ajax call it displays.

Anybody know why the success function isn't calling? nothing shows in the div with class results on any browser.

Thanks!

Share Improve this question edited Oct 15, 2013 at 19:03 user2625787 asked Oct 15, 2013 at 18:57 WelshJohnWelshJohn 391 gold badge1 silver badge6 bronze badges 7
  • 1 What response do you get in the browser when making the ajax call? Are you actually getting a 200 response? Is this a cross-domain request? – Mike Brant Commented Oct 15, 2013 at 19:00
  • It was just an array with the associations like: {"success":true,"message":"Success message: hooray!"} Adding the header suggested by tak3er I get a .json file Files are stored locally, apart from the php file which is stored on a server externally on a webpage. – WelshJohn Commented Oct 15, 2013 at 19:11
  • i suspect it is a cross-domain request – Kevin B Commented Oct 15, 2013 at 19:13
  • I have tried using jsonp and adding a callback parameter. This didn't work either – WelshJohn Commented Oct 15, 2013 at 19:23
  • @WelshJohn So you are saying that in looking at response info for the AJAX call using the browser's developer tool (or Firebug or similar), you are getting a 200 response with the JSON body that you expect? – Mike Brant Commented Oct 15, 2013 at 19:23
 |  Show 2 more ments

5 Answers 5

Reset to default 1

Hey i had the same problem

Firstly i used $.getJSON blah blah.... but didn't worked for some reason...

But the normal ajax call worked.. MY Page returns a json output as you.. try removing the "datatype"

I Used code copied from JQUERY site which is below i pasted

$.ajax({
  type: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" }
})
  .done(function( msg ) {
    alert( "Data Saved: " + msg );
  });

Below is the code how i used and worked with json output i got...

$.ajax({
          type: "GET",
          url: "json.php",
          data: { searchword: q, projid:prid }
        })
          .done(function( jsonResult ) {
            var str='';
        for(var i=0; i<jsonResult.length;i++)
          {
              //do something here.. with jsonResult."yournameof "
            alert(jsonResult[i].id+jsonResult[i].boqitem);
          }
});

Keep same domain origins in mind here, use jsonp with a callback has always been helpful for me, that does mean adding a $_GET['callback'] to your php script and wrap the json_encode with '('.json_encode($Array).')' for proper formatting.

http://api.jquery./jQuery.getJSON/

The last demo on that page is the best example I have found.

Looks like cross domain request.

Try it by changing :

dataType : "json"

to

dataType : "jsonp"

I know it is very late. But it can simply be handled like

var postData = {'inp': $('#inp').val()};
$.ajax({
    type: "POST",
    data: postData,
    url: 'removedmyurlfromhere', // your url
    success: function (response) {
        // use exception handling for non json response
        try {
            response = $.parseJSON(response);
            console.log(response); // or whatever you want do with that
        } catch(e) {}
    },
    error: function( jqXHR, textStatus, errorThrown ) {},
    plete: function(  jqXHR, textStatus ) {}
});

In PHP, add the JSON content-type header:

header('Content-Type: application/json');

also, try listening for plete as well to see if you do get any response back:

$.ajax({

 // ....
 plete: function (xhr, status) {
   $('.results').append('Complete fired with status: ' + status + '<br />');
   $('.results').append('XHR: ' + (xhr ? xhr.responseText : '(undefined)'));
 }
 // ...

});
发布评论

评论列表(0)

  1. 暂无评论