Vadimster
Vadimster

Reputation: 119

Ajax + PHP: null instead of an array

Ajax call is made in the background

var signupValidate = function(elementID){
  var value = $('#' + elementID).val();
  if (value !== ''){
    $('#'+elementID+'-status').css("background-image", "url(img/signup/spinner.gif)");
    var data = {elementID: value};
    var json = JSON.stringify(data);
    $.ajax({
      url: 'php/validator_signup.php',
      dataType: 'json',
      type: 'post',
      data: json,
      success: function(data){
        var parsedResponse = JSON.parse(data);
        console.log(parsedResponse);
        /*
                if(data.response === 1){
                    $('#'+elementID+'-status').css("background-image", "url(img/signup/no.png)");
                }else if(data.response === 0){
                    $('#'+elementID+'-status').css("background-image", "url(img/signup/yes.png)");              }
            */
      }

    });
  }
}

validator_signup.php received the call. So far in test mode PHP will receive the string, parse it and encode again to return to JS:

$post = $_POST['data'];
$data = json_decode($post, true); //decode as associative array
$details = $data[0];
echo json_encode($details);

JS then needs to print this in console.

I get this:

null

instead of the value which I expect back.

Result is same whether I parse returned data or not.

If I understand it correctly, the problem is on PHP side?

Upvotes: 0

Views: 1192

Answers (5)

Mohamed Belal
Mohamed Belal

Reputation: 622

JSON data is sent to the server as a raw http input it is not associated with query name like $_POST['data'] or anything like that which means you must access the input string not a data post value to do so you need to use

$rawInput = json_decode(file_get_contents('php://input'), true);
$elementValue = $rawInput['elementId'];

thats it

Upvotes: 0

user3030546
user3030546

Reputation: 43

$_POST = json_decode(file_get_contents('php://input'), true); 
$data = $_POST['data'];

Upvotes: -3

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

Here, since you are checking whether data is being post, if you see in Network, no data is being posted. To fix it, change this part:

var data = {elementID: value};

To this:

var data = {data: {elementID: value}};

Consider removing conversion of Data

PHP automatically handles the $_POST as an array! So you don't need to use the reconversion. Please eliminate this part:

var json = JSON.stringify(data);  // Remove this.

And in the server side:

$data = json_decode($post, true);   // Remove this
$data = $_POST['data'];             // Change this

Update

OP said data[elementID]:gh is sent to the PHP file.

If this is the case, then if the data needs to be "gh" in JSON, then:

$res = $_POST["elementID"];
die(json_encode(array("response" => $res)));

This will send:

{
  "response": "gh"
}

And in the client side, you don't need anything other than this:

$.post('php/validator_signup.php', function (data) {
    var parsedResponse = JSON.parse(data);
    console.log(data);
});

Upvotes: 1

Steve
Steve

Reputation: 20469

There does not appear to be any value in converting to json when your data is so simple, you can just use a regular js object that jquery will convert to form data.

Also, as both the key and value you send are unknown, i would suggest sending the data in a different structure so its easy to retrieve:

var signupValidate = function(elementID){
  var value = $('#' + elementID).val();
  if (value !== ''){
    $('#'+elementID+'-status').css("background-image", "url(img/signup/spinner.gif)");

    $.ajax({
      url: 'php/validator_signup.php',
      type: 'post',
      //      ▼key   ▼value     ▼key  ▼value
      data: { id:    elementID, val:  value},
      success: function(response){
        console.log(response.message);
      }

    });
  }
}

In php you can access the data via $_POST, and as you know the keys, its simple:

<?php

$id = $_POST['id'];
$val = $_POST['val'];

//set correct header, jquery will parse the json for you
header('Content-Type: application/json');
echo json_encode([
    'message'=>'Request received with the id of: ' . $id . 'and the value of: ' . $val,
]);
die();

Upvotes: 2

Derek Pollard
Derek Pollard

Reputation: 7165

Change:

data: json,

To:

data: { data: json},

This is because you aren't giving the sent data a POST parameter to then be used server side to retrieve it.

Then, you can simply fetch the code server-side like this:

$data = json_decode($_POST['data']);

Hope this helps!

Upvotes: 1

Related Questions