简体   繁体   中英

Unable to send JSON via AJAX

I made a function which counts how much time I spent on some page and where I came from. I collect all the data and save it into a JSON but when I try to send that JSON via ajax on the success it alerts me with an empty alert box, which means that nothing is being sent. I tried to add async to false because I use the onbeforeunload function but that doesn't work. I tried numberless combinations with AJAX setting but nothing is working.

HTML / JS

(function(){
var time,timeSite,endTime,seconds,testObject,retrievedObject,text;
window.onload=function(){
    time= new Date();       
}
window.onbeforeunload=function(){
    endTime = new Date();
    timeSite= time.getTime()-endTime.getTime();
    seconds =Math.abs(timeSite/1000);
    window.localStorage['seconds']=seconds;
    text = 'Visitor accessed site directly.';
    if(document.referrer == ''){
        var link = text;
    } else{
        var link = document.referrer;
    } 
     var url = window.location.href;
     var main = {
        'From': link,
        'Current was' : url,
        'Time Spent': seconds
     }
     $.ajax({
           type: "POST",
           data: {'data': main},
           url: "http://localhost:8080/projectFour/test.php", //i use this page only to check if i receive data
           contentType:'application/json',
           success:  function(data) {
                alert(data);
           }, 
           error: function(xhr, ajaxOptions, thrownError) {
        if (xhr.status == 200) {

            alert(ajaxOptions);
        }
        else {
            alert(xhr.status);
            alert(thrownError);
        }
    }
       });
}
})();

Test.php

<?php 
  if(isset($_POST['main'])) { 
    $obj = json_decode($_POST['main']); 
    //some php operation 
    echo $obj; 
   } 
?>

Your test.php is looking for a POST variable called main , but you're sending one called data .

You can change the data part of the ajax call from:

data: {'data': main}

to

data: {'main': main}

and that should cause it to post the variable with main as the variable name.

Secondly, when you return the data, it would be better to return it as JSON again, otherwise it might mangle the result a bit.

Replace

echo $obj;

with

echo json_encode($obj);

And in the ajax replace

alert(data);

with

alert(JSON.stringify(data));

That will give you a view of the returned data structure as a string.

You should also consider returning something from PHP when the if statement is false, whether that be an error code, or some other response. Sending no response in this case isn't very helpful to the client side, and has hindered your debugging.

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