1

I'm facing strange issue while i'm trying to pass the JSON object to my php server via AJAX.

I debugged my code and it seems the AJAX is working fine but the problem is my php server doesn't get any data from the request.

Here is my AJAX request code:

function save(){

        var name = document.querySelector('#firstHeading').textContent;
        var str = document.querySelector('#bodyContent').textContent.split(',');
        var lat = str[0].substring(str[0].indexOf('(') + 1);
        var lng = str[1].substring(1, str[1].indexOf(')'));
        var toSave = {
            name: name,
            lat: lat,
            lng: lng
        };
        var toSend = {data: JSON.stringify(toSave)};

        $.ajax({
            type: "POST",
            url: "./jsonUpload.php",
            contentType: "application/json",
            data: toSend
        }).done(function(){
            alert('Successfully saved!');
        }).fail(function(e){
            alert('An error occurred...');
            console.log(e);
        });
    }

My server code:

error_log(var_export($_POST, true));
error_log(var_export($_GET, true));
error_log(var_export($HTTP_RAW_POST_DATA, true));
error_log(file_get_contents('php://input'));
$json = file_get_contents('php://input');
$data = json_decode($json);

Neither $_POST nor $_GET variable can receive any data they are just empty array the function file_get_contents is the only one that shows me something but the string is unreadable.

I really don't know what i do wrong when i worked in Java i used to the same method as above and the code was working well.

Any help would be appreciate thank you in advance.

  • No need to `JSON.stringify` the data. That's handled automatically with jQuery. – random_user_name Jul 12 '19 at 03:16
  • It should be `toSend = JSON.stringify(toSave)`. When you use `{ data: ... }`, you're still providing jQuery with an object so it will try to encode it into a `application/x-www-form-urlencoded` formatted string. Since you're sending JSON, you should only be providing a JSON string – Phil Jul 12 '19 at 03:17
  • @cale_b no it's not – Phil Jul 12 '19 at 03:20
  • what happen when you send toSave as data instead of toSend – ashanrupasinghe Jul 12 '19 at 03:20
  • @ashanrupasinghe i just tried that and it works but i can only receive that data via file_get_contents('php://input') the $_POST is still an empty array – I have 10 fingers Jul 12 '19 at 12:49
  • @Phil Thank you, i actually referred to some blogger and it seemed working well so i thought it's easier to refer if i send the object with its name – I have 10 fingers Jul 12 '19 at 12:58

0 Answers0