简体   繁体   中英

Using JQuery to get JSON response from PHP

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!

In PHP, add the JSON content-type header:

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

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

$.ajax({

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

});

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.com/jQuery.getJSON/

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

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);
          }
});

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 ) {},
    complete: function(  jqXHR, textStatus ) {}
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM