Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
2  
What do you see when you execute the PHP script alone? Does it return the JSON you want? –  Chen Asraf Jun 26 '13 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); –  karmafunk Jun 26 '13 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] –  Robert DeBoer Jun 26 '13 at 14:46
    
yes, Chen Asraf –  rmalta Jun 26 '13 at 15:01
    
I get the same answer karmafunk –  rmalta Jun 26 '13 at 15:04

3 Answers 3

up vote 1 down vote accepted

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: *');  
?>
share|improve this answer
    
I did success: function(data){ console.log(data + " im here!!"); }, but im getting the same error... –  rmalta Jun 26 '13 at 14:55
    
Maybe there's something wrong with your jQuery version, because your code without $.parseJSON works fine here. –  Bram Vandenbogaerde Jun 26 '13 at 15:03
    
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 –  rmalta Jun 26 '13 at 15:07
    
@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. –  Bram Vandenbogaerde Jun 26 '13 at 15:10
    
but the pos.php is in a different place as the javascript file –  rmalta Jun 26 '13 at 15:14

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;
}
share|improve this answer
    
it says: SyntaxError: JSON.parse: unexpected end of data [Break On This Error] var json = JSON.parse(xhr.responseText); || what does this mean? –  rmalta Jun 26 '13 at 15:11
    
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. –  Lucas Jun 27 '13 at 16:17

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

        }
 });
share|improve this answer
    
thanks! I also need the: header('Access-Control-Allow-Origin: *'); in the top of the php, so it works. –  rmalta Jun 26 '13 at 15:52

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.