Jason Krs Jason Krs - 5 months ago 19
Javascript Question

Retrieve PHP Data from AJAX

The code below triggers the error callback function. Can you help me ?
Actually the thing I'm trying do is get the data in the form in php and then send back these data in Ajax for further treatments

HTML

<body>
<div>
<form id="user">
NOM : <input type="text" name="name"/>
</form>
<button id="tst" onclick="SHOW();">CLICK</button>
</div>


Javascript

function AFFICHER(){

$.ajax({
type: 'POST',
url: 'http://localhost:8012/myscript.php',
data: $('#user').serialize(),
dataType: "json",
crossDomain: true,
success: function(result) {
console.log(result);
},
error: function(xhr, textStatus, errorThrown) {
console.log('ajax loading error...');
return false;
}
});


}


My PHP

<?php
$decoded = json_decode($_POST['data'],true);
foreach ($decoded as $value) {
echo json_encode($value["name"]);
}

?>


The error is

enter image description here

Answer

$('#user').serialize() will leave you with a string such as name=<input-value> (name being the input name from your form input name="name"). The larger your form gets, the more values that will be stored in the data string, Eg. name=marcus&phone=555-555-5555&location=interwebs

To directly access those in your PHP script, you fetch them from the $_POST array:

echo $_POST['name']; // marcus

To loop through your data, you need not run it through json_decode(), nor can/do you access $_POST['data'] in the manner you are since it does not exist.

Your foreach() loop is redundant. The data in question (that you're looking to return) is already stored in the $_POST array.

Instead, just encode the $_POST array and send it back. This is all you need in your PHP script:

echo json_encode($_POST);

Then, since the response will be JSON, you can access the values by key/property in your $.ajax().success() callback function:

...
success: function(result) {
    console.log(result.name) // will log the value stored in 'name'
},
error: function(xhr, textStatus, errorThrown) {
    console.log('Status: ' + textStatus, 'Error: ' + errorThrown)
}