For simple transfer of data from PHP to AJAX, Json encoding or key value pairs are not always necessary. It can be simply done using string handling.
A sample code explaining this functionality is below.
$query = "SELECT email FROM login WHERE email = '". mysqli_real_escape_string($conn,$email) ."' AND password = '". mysqli_real_escape_string($conn,$pass) ."'" ;
$result = mysqli_query($conn,$query);
$row=mysqli_fetch_row($result);
$row_cnt = mysqli_num_rows($result);
$s_email = $row[0];
if ($row_cnt == 1) {
$response="success";
} else {
$response = "Invalid Credentials";
}
$conn->close();
$_SESSION["email"]= $s_email;
echo $response;
This code shows how a 'success' response is sent back to ajax calling the php code. Further in ajax the following could be done to retrieve the response.
$.ajax({ type : 'POST',
data : {email: $('#email').val(), password: $('#pass').val()},
url : 'login.php',
success: function (data) {
if(data == 'success'){ //the value echoed from php can be stored in the data variable of ajax
window.location.assign('upload.php');
}
else{
alert(data);
}
},
error: function ( xhr ) {
alert("error");
}
});
The above concept can be extended to return MULTIPLE VALUES also. This method allows simple tranfer of data from PHP to AJAX in a string format.
We have to follow a simple step of echoing everything we need to send as a response from the php to ajax, seperated by a unique seperator.
echo $response.#;
echo $email.#;
echo $password.#;
echo "Hello".#;
echo "World";
Then the variable data in ajax could be simply retrieved as in the above example and a simple function like,
var res = data.split("#");
data, being the variable within ajax.
The res array can then be used within js for whatever purpose we need.