1

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!

WelshJohn
  • 39
  • 1
  • 1
  • 6
  • 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 Oct 15 '13 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 Oct 15 '13 at 19:11
  • i suspect it is a cross-domain request – Kevin B Oct 15 '13 at 19:13
  • I have tried using jsonp and adding a callback parameter. This didn't work either – WelshJohn Oct 15 '13 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 Oct 15 '13 at 19:23
  • HTTP/1.1 200 OK Date: Tue, 15 Oct 2013 19:26:56 GMT Server: Apache Connection: close Transfer-Encoding: chunked Content-Type: text/html. Its sending the request ok, but doesn't seem like a response. – WelshJohn Oct 15 '13 at 19:35
  • Are you sure that your json is valid? Pass it through http://jsonlint.com or similar. – Moob Oct 15 '13 at 22:35

5 Answers5

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);
          }
});
ivar ajet
  • 196
  • 2
  • 9
0

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.

E-comm
  • 96
  • 1
  • 6
0

Looks like cross domain request.

Try it by changing :

dataType : "json"

to

dataType : "jsonp"
byJeevan
  • 3,728
  • 3
  • 37
  • 60
0

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 ) {}
});
kazimt9
  • 563
  • 5
  • 11
-1

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)'));
 }
 // ...

});
Stefan
  • 3,962
  • 4
  • 34
  • 39
  • Added the above header and no change. No alert and no results in div. Accessing the page directly now leads to a open or save .json file. – WelshJohn Oct 15 '13 at 19:09
  • While adding the header is a good idea, it isn't required if you supplied the dataType in the ajax options. – Kevin B Oct 15 '13 at 19:11
  • the file opens because you're browser does not understand the json mime type. Did you see my edited response with calling complete: to see if you get a response at all? – Stefan Oct 15 '13 at 19:11
  • The complete functions fires and produces Complete Fired! in the corresponding div. – WelshJohn Oct 15 '13 at 19:15
  • ok cool. that means that your code is working but something is wrong with the response. You have 2 options: you get some reply different from 200 OK or your JSON is invalid. It would be very useful if you have Google chrome or Firefox with firebug. Open the devtools/firebug, go to the network tab and click on the request you make to see the response. I also updated the js code to include printing the status and the response – Stefan Oct 15 '13 at 19:22
  • Getting a 200 OK through firebug – WelshJohn Oct 15 '13 at 19:27
  • and if you check the response tab on that reply? do you see anything or no text at all? – Stefan Oct 15 '13 at 19:28
  • HTTP/1.1 200 OK Date: Tue, 15 Oct 2013 19:26:56 GMT Server: Apache Connection: close Transfer-Encoding: chunked Content-Type: text/html – WelshJohn Oct 15 '13 at 19:30
  • hmm.. you get nothing back and Content-Type: text/html ... you sure you're pointing to the correct php script? if so try replacing the php code from `echo json_encode($data)` to `echo '{"success":true, "message":"whatever..."}';` – Stefan Oct 15 '13 at 19:34
  • Definitely pointing to the correct script. I stripped the php down to just the text echo and still the same. 200 OK but no response sadly – WelshJohn Oct 15 '13 at 19:41
  • HTTP/1.1 200 OK Date: Tue, 15 Oct 2013 19:46:28 GMT Server: Apache Connection close Transfer-Encoding: chunked Content-Type: application/json. Now getting the correct content type on the 200 ok – WelshJohn Oct 15 '13 at 19:47
  • hmm... I really don't have an idea then, it should work, esp if you go to the php file directly and open the json file it saves and you see that the contents is there. Last thing you should do is disable browser cache (http://stackoverflow.com/questions/404617/disabling-the-browser-cache-in-php-or-using-javascript) but if that also does not help you I'm baffled sry :) ... for simplicity as well btw, you might want to use jquery's getJson() method: http://api.jquery.com/jQuery.getJSON/ – Stefan Oct 15 '13 at 19:57
  • Thanks for all your help tak3r. Will try browser cache and the other getJSon method (I believe I started trying with that) – WelshJohn Oct 15 '13 at 19:59