0

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?

5
  • What's the value of $data[0]? Commented Jun 16, 2016 at 15:17
  • A bigger question is why are you using JSON.stringify to pass data? Depending on what you are doing, there is no reason to use JSON.stringify nor JSON.parse. Commented Jun 16, 2016 at 15:19
  • What will be stored in value? Commented Jun 16, 2016 at 15:23
  • 1
    Please clarify if elementID is suposed to be sent to php, because currently you are (attempting) to send a key value pair, with the key being the literal string elementID. Commented Jun 16, 2016 at 16:01
  • @Stave Javascript function takes the argument (string). Function is called through the attribute of an HTML element like this: onblur="signupValidate('signupUsername')". I might bing it via jquery later on, so far attributes are good. Commented Jun 16, 2016 at 16:03

5 Answers 5

2

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();
Sign up to request clarification or add additional context in comments.

8 Comments

I think this what the OP wants. Though, no need to die().
@Steve I favour this approach more for some reason, this is in line with how I see this happening. My first mistake was that I missed the right way to create the data variable in the client, it should of course be var data = {id: elementID, val: value}; Now in Network I see the data passed as it should be to the php: id:signupUsername val:test. I still do not stringify it, should I? I will post server code in next comment.
@Steve PHP: I create a template array which I intent to update and return to Javascript: $json = array("response" => 1);. I intend to take the id value and return it in the response by doing this: $id = $_POST['id']; $json[0] = $id; echo json_encode($json);. Javascript console gives me this, however: Object {0: "signupUsername", response: 1}. I am not quite following what is happening, as I expect to a) rewrite response value in the php array to the id value and return that value.
@Steve I can see in Network, that response passed back to JS is {"response":"signupUsername"}. If I JSON.parse the response from PHP and output to console log, I get the following VM380:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1
@Vadimster i have left the office and am typing from my phone so i cant really help at the moment, ill check back tomorrow and if you are still stuck will try and provide some more information
|
1

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!

4 Comments

Yup... This is the same thing I said as well. :) Looks like this can be an alternate of what I gave. :D
well this one could work too :D even though not full JSON solution
if you are going to use this solution then change the dataType in the ajax call too because this is not a full JSON solution the data which being sent to the script isn't fully JSON
@MohamedBelal - this is data being sent to the server, the dataType attribute is used for the data that is returned from the server.
1

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

11 Comments

This solves half of the problem, the php will still fail (there is no element in the array with a key of 0).
And considering the number of upvotes, it would probably be helpfull if you addresses the needless json conversion in the js. Simply send form data, that php can handle directly
@Steve Definitely... Will do that.
The more i look at the OPs question, the more bugs i see. Unless the OP comes back and engages with us, its not really possible to guess what they are trying to do unfortunatly
I adjusted client and server code as advised, still null is returned :(
|
0

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

Comments

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

1 Comment

So what do you mean? Can't you explain?

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.