-1

I am developing a web app with html5, javascript with a php server, my problem is in a ajax call in the javascript:

$.ajax({ 
      type: "POST",
      url: "http://localhost/pos.php",
      data: "lat="+lat+"&lon="+lon+"&nome=helena",
      dataType: "JSON",
      success: function(data){ 

      data = $.parseJSON(data);
        console.log(data + " im here!!");
      },

      error: function(jqXHR, textStatus, errorThrown ){
         console.log("POST: ", jqXHR, textStatus, errorThrown);
      }
    });

And from the side of the php I run a script, and in the end I do:

$arr = array ( 'a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5 );
echo json_encode($arr);

The php returns the array, but from the side of the javascript, I can't access it in the success function, in the console it says:

POST:  [url=""]Object { readyState=0,  status=0,  statusText="error"}[/url] error (an empty string)

What am I doing wrong? I have tried to do it in lots of ways I saw in the internet, but I can't get it to work, can someone help me?

6
  • 2
    What do you see when you execute the PHP script alone? Does it return the JSON you want? Commented Jun 26, 2013 at 14:39
  • Try sending your data like this: data: { lat: lat, lon: lon, nome : 'helena' } and your PHP: $arr['result'] = array ( 'a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5 ); echo json_encode($arr); Commented Jun 26, 2013 at 14:45
  • To access json data returned from a ajax/post call in jquery, you will need to access the data like an object, so data.[name of what you returned] Commented Jun 26, 2013 at 14:46
  • I get the same answer karmafunk Commented Jun 26, 2013 at 15:04
  • What browser are you testing this? Also, can you try changing the name of the success: function(data){ to success: function(res){ (and use res in this function). I don't expect much but I see data in the top part (data: "lat="+lat+"&lon="+lon+"&nome=helena") and data in the response so just trying :) Commented Jun 26, 2013 at 15:26

3 Answers 3

1

I've tested it and everthing is working fine.

You just need to remove $.parseJSON(data); from your JavaScript. Then it would work because jQuery automatically does that for you if you set the data type to JSON.

EDIT:

If the PHP script is on a different domain you can add the following PHP header to your script:

<?php
    header('Access-Control-Allow-Origin: *');  
?>
Sign up to request clarification or add additional context in comments.

9 Comments

I did success: function(data){ console.log(data + " im here!!"); }, but im getting the same error...
Maybe there's something wrong with your jQuery version, because your code without $.parseJSON works fine here.
Im loading jquery-1.9.1.js and jquery.mobile-1.3.0.js. It might be something else, or im going crazy, because im doing everything like in the examples, and this is not a complex thing
@user2524560 maybe you can try "/pos.php" instead of "localhost/pos.php", the browser maybe blocks your request because it is "cross-domain" or something.
but the pos.php is in a different place as the javascript file
|
0

Try this instead of your ajax call:

var xhr = getXMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
       var json = JSON.parse(xhr.responseText);
       //Do whatever you want...
    }
};

xhr.open("POST", "pos.php", true);
xhr.send("lat="+lat+"&lon="+lon+"&nome=helena");

function getXMLHttpRequest() {
    var xhr = null;

    if (window.XMLHttpRequest || window.ActiveXObject) {
        if (window.ActiveXObject) {
            try {
                xhr = new ActiveXObject("Msxml2.XMLHTTP");
            } catch(e) {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
        } else {
            xhr = new XMLHttpRequest(); 
        }
    } else {
        alert("XMLHTTPRequest object not supported...");
        return null;
    }

    return xhr;
}

2 Comments

it says: SyntaxError: JSON.parse: unexpected end of data [Break On This Error] var json = JSON.parse(xhr.responseText); || what does this mean?
Try to do a "alert(xhr.responseText)" to see its content right before the instruction that causes the issue. The json string returned by the php file may be wrong.
0

No need to use normal ajax. I found some problems in your code.See the corrected code below

Php file

  <?php
  header('Access-Control-Allow-Origin: *');
  $arr = array ( 'a'=>'1','b'=>'2','c'=>'3','d'=>'4','e'=>'5');
  echo json_encode($arr);
  ?>

Javascript file

 $.ajax({
 url : "http://localhost/pos.php",
 type : "POST",
 dataType : "JSON",
 data : {"lat":lat , "lon" : lon , "nome" : helena },
 error : function () { //statements }
 success : function(data)
        {
          alert(data.a);

        }
 });

1 Comment

thanks! I also need the: header('Access-Control-Allow-Origin: *'); in the top of the php, so it works.

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.