Handling ajax success response - javascript

PHP: lockState.php
require '../dbconn.php';
$query = mysql_query("select id, lockState,name from register_db where Id=1");
$items = array();
while ($row = mysql_fetch_object($query)) {
array_push($items, $row);
}
echo json_encode($items);
Result from query
[{"id":"1","lockState":"No","name":"Local Application"}]
Index.php
$.ajax({
type: "POST",
url: "feed/lockState.php",
data: ({id: 1}),
cache: false,
dataType:"json",
success: function (response) {
alert(JSON.stringify(response)); // [{"id":"1","lockState":"No","name":"Local Application"}]
alert(response.name); //***undefined***
if(response.name=='Local Application'){
callMyFunction(response.name);
}
},
error: function () {
alert("Oops..!! Something wrong!);
}
});
I'm totally lost where I'm doing wrong in using 'Success' response. Even I tried to JSON.parse(response) and tried to access the key:value, but still same undefined. Please help.

response[0].name will help you.

Look at your PHP. See $items = array(); where you create an array.
Look at the data you are getting. See the [ and ] around it.
You have an array containing an object. You need to read the first value out of that array.
var object = response[0];
var name = object.name;

The way you tried would work if the response was:
{"id":"1","lockState":"No","name":"Local Application"}
But your response is:
*[*{"id":"1","lockState":"No","name":"Local Application"}*]*
The brackets mean the response is an array, [], containing an object, {};
As others have mentioned; the way to retrieve values out of an array can be done by using array_variable[0] to for example select the first.
In your example try this:
alert(response[0].name); //***undefined***

Related

How to make the ajax 'data' that come with 2 values to get each value separately?

<?
function phpfunction(){
//insert data to database //some codes work inside this.
$return_arr[] = array($arrResult, // include only one value
$response_array['status'] );//success or not success value
return $return_arr;
}
?>
This $return_arr[] value return to the javascript ajax file >>
$.ajax({
url: 'PHPMethodCalls_AL.php',
type: 'post',
data: {... post many values to php function.. },
success: function(data) {
alert(data);
//data is successfully come as this format >> [[["Testing123"],"success"]]
var results = JSON.parse(data);
alert(results);
// this alert got >> Testing123,success
},
//this one is post value to function
$newCIarrayList = array();
$newCIarrayList = phpfunction(..data include );
echo json_encode($newCIarrayList);
What should I do to get each value as "Testing123" and "success" value separately? I tried with split(",") function but it didn't work.
You can seperate in php function before response to ajax like below .Then you can get easy
<?
function phpfunction(){
//insert data to database //some codes work inside this.
$return_arr = array("data" =>$arrResult, // include only one value
"status" =>$response_array['status'] );//success or not success value
return $return_arr;
}
?>
var results = JSON.parse(data);
alert(results.data || results.status);
What you get back in success: function(data) is a stringified json of a nested array: [[["Testing123"],"success"]].
To get your status and payload out of this structure, you can use the following snippet.
var data = '[[["Testing123"],"success"]]';
var parsedData = JSON.parse(data);
console.log(parsedData); // quite nested
var status = parsedData[0][1];
console.log(status);
var payload = parsedData[0][0][0];
console.log(payload);
Or using ES6 destructuring:
var data = '[[["Testing123"],"success"]]';
var parsedData = JSON.parse(data);
[[[payload], status]] = parsedData;
console.log(status);
console.log(payload);
I would however suggest that you revise your php-side code, and make it so that it forms a simpler structure, ideally:
{"status": "success", "payload": "Testing123"}

Ajax array only returns 1 value?

I am new to PHP and Ajax so please bear with me. I've searched around and found some answers but still am having trouble. I have an array of check box input values. If a user checks an item it is added to my array list. An example would be:
listOfPrograms = [chrome, firefox, sqlworkbench]
I want to send this array list to a PHP script on my server. My current Ajax script is as follows:
function ajaxPostToPhp(listOfPorgrams)
{
$.ajax
({
url: 'script.php',
type: 'post',
data: ("listOfPrograms" : listOfPrograms), // I believe this is where my issues lies as I do not know exactly that this is doing. I have read the PHP documentation. I tried converting to JSON and kept getting a 500 error.
success: function(data)
{
console.log(data);
}
});
}
My PHP script is as folllows:
$myArray = $_Request['listOfPrograms'];
echo $myArray;
This returns only 1 item from the array. I tried setting myArray = [] but I get an undefined index.
Thanks for your help! Sorry for such a noob question.
You need to fix a few things:
1- Javascript array:
var listOfPrograms = ['chrome', 'firefox', 'sqlworkbench'];
2- Ajax Data:
function ajaxPostToPhp(listOfPrograms)
{
myListData = {};
myListData['Programs'] = listOfPrograms;
$.ajax({
url: 'script.php',
type: 'post',
data: myListData,
success: function(data)
{
console.log(data);
}
});
}
3- Php Code:
$myArray = $_POST['Programs'];
var_dump($myArray);
You are passing an array as post parameter but they can only be strings. You should convert the array to a JSON string first. An easy function for that purpose is JSON.stringify()
var listOfPrograms = ["chrome", "firefox", "sqlworkbench"]
// I guess you need strings here
function ajaxPostToPhp(listOfPorgrams) {
$.ajax ({
url: 'script.php',
type: 'post',
// Convert listOfPrograms to a string first
data: ("listOfPrograms" : JSON.stringify(listOfPrograms)),
success: function(data) {
console.log(data);
}
});
}
jquery will kindly turn array values in ajax post data to an array for you. the issue is that in php you can't just echo an array. as a commenter stated, your php file needs to look like
$myArray = $_Request['listOfPrograms'];
echo json_encode($myArray);
also you should consider using $_POST over $_REQUEST

jQuery Ajax call not returning anything

I have an Asynchronous call in jQuery where a POST request returns an HTTP 200, but there is no response text or anything to work with from the endpoint in question.
I'm confused as to what could be the cause on my Localhost, as when I use the same call to poll a service like JSONTest, I get a valid object back in return.
This is what the result endpoint looks like, written in PHP using Slim
$app->post("/search", function() use ($app) {
try {
$request = $app->request;
$body = $request->getBody();
$input = json_decode($body);
//Prepare search string
$query = "%". $input->query . "%";
$grade = '%grade ' . $input->grade . "%";
$meta = $input->meta;
$proc_results = array();
$item = new stdClass();
$item->id = 1;
$item->source = "source";
$item->type = "lesson_plan";
$item->description = "Description of the Lesson Plan";
$item->date_created = 1234567890;
$proc_results[] = $item;
$app->response()->header('Content-Type','application/json');
$app->response()->body(json_encode($proc_results));
} catch (Exception $e) {
}
});
This call does return a JSON response when using a utility like POSTMAN, but when I use the following test jQuery code, I get an Object that has no responseText or any sign that my interpreter has the object.
$.ajax({
"type":"POST",
"url":"http://localhost:9001/search",
"data":{"query":"math","grade":"4"}
}).done(function(result) {
console.debug(result);
});
Am I missing a component in my done() call to poll the resources? Is my Slim call sending malformed JSON? If needed I can get a working demo up online.
Type, url, data should not be strings. Try as not string. It should work. Also the keys of data shouldnot be string.
Try this
$.ajax({
type:"POST",
url:"/search",
data:{query:"math",grade:"4"}
}).done(function(result) {
console.debug(result);
});
Try setting the datatype to be JSON, expanding on #doniyor's answer:
$.ajax({
type:"POST",
url:"/search",
datatype:"json",
data:{query:"math",grade:"4"}
}).done(function(result) {
console.debug(result);
})
see: http://api.jquery.com/jquery.ajax/
Seems from your comments that you are looking for JSON as a result.
I found the root cause: I was not sending valid JSON for PHP to parse. By adding JSON.stringify it responds as expected:
$.ajax({
type:"POST",
url:"http://localhost:9001/search",
dataType:"json",
contentType: "application/json",
data: JSON.stringify({"query": "math", "grade": "4", "meta": "z"})
}).done(function(result) {
console.debug(result);
});
Thanks guys for helping.

Sending JSON to PHP using ajax, troubles with data

my javascript won't go into my Database.php file.
Anyone knows what's wrong?
I know there is another thread with this question but it just doesn't work for me.
I have this in javascript
var Score = 5;
//Score insert
var postData =
{
"Score":Score
}
$.ajax({
type: "POST",
dataType: "json",
url: "Database.php",
data: {myData:postData},
success: function(data){
alert('Items added');
},
error: function(e){
console.log(e.message);
}
});
and this in php
function InsertScore(){
$table = "topscores";
if(isset($_POST['myData'])){
$obj = json_encode($_POST['myData']);
$stmt = $conn->prepare("INSERT INTO " + $table + " VALUES (?)");
$stmt->bind_param('s', $obj);
$stmt->execute();
}
else{
console.log("neen");
}
$result->close();
change this line
success: function InsertScore(data){
to this
success: function(data){
the success parameter of jquerys ajax method has to be a anonymous function (without a name) or one defined in javascript but definitely not a php function.
You should read up on variable scope, your $table variable is not defined in the scope of your function.
You also have an sql injection problem and should switch to prepared statements with bound variables.
You are trying to send an object to your PHP file instead of a JSON data type.
Try 2 use JSON2 to stringify your object like this :
var scoreINT = 9000;
var usernameSTRING = "testJSON"
var scoreOBJ = {score:scoreINT,username:usernameSTRING};
var jsonData = JSON.stringify(scoreOBJ);
this would give you the following result "{"score":9000,"username":"testJSON"}"
You would be able to send this with your AJAX if you change ( if you follow my variable names ofcourse )
data: {myData:postData}
to
data: {myData:jsonData}
This would already succesfully transfer your data to your PHP file.
regarding your error messages and undefined. the message "e.message" does not exist. so thats the "undefined" you are getting. no worries here.
I noticed the succes and error are called incorrectly. I've just deleted them because there is no need to.
Next. moving up to your PHP.
you would rather like to "DECODE" then to encode your encoded JSON.
you could use the following there :
$score = json_decode($_POST['json'],true);
the extra param true is so you are getting your data into an array ( link )
or you could leave the true so you are working with an object like you already are.
Greetings
ySomic

Check return value when parsing json array in javascript

I'm a beginner in ajax and json so I'm sorry if this question is a bit stupid. I'm retrieving the data(city id and name) and put them in an array then use json_encode. Then I call the getCities function but I'm not sure if I'm getting the correct cities. I tried using document.write but there's no output. How can I know if I'm getting the correct ones? Thank you for your help.
Here's the getCities.php:
$json = array();
$query = "SELECT cityID, cityName FROM city";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$coord = array('id' => $row['cityID'],'city' => $row['cityName']);
array_push($json, $coord);
}
$jsonstring = json_encode($json);
And here's the javascript part:
function getCities(){
var string = $.ajax ({
url: "getCities.php",
dataType: 'json'
}).responseText;
return JSON.parse(string);
}
$(document).ready(function (){
var city = getCities();
while (city.length > 0) {
document.write(city.pop + "<br/>");
}
});
There are 2 easy ways to do this. First of all I use Google Chrome (or Firefox) to facilitate testing. Look at the docs and you will see that your $.ajax call will also accept a success function. You could put it in the ajax call under dataType like this:
var string = $.ajax ({
url: "getCities.php",
dataType: 'json',
success: function(data) {
console.log(data);
}
});
string.done();
Notice how I changed the end of the ajax call. It is now saying, when this call is done, call the success function. You can also put an error function in the ajax call if you want to have something print out in case of an error. The success function will then be called when the data returns. It will print in the console of your Chrome debugger. Google that term to find out how to show it, super easy stuff. You can also put a break point on the console.log function call (Google how to do that also) and you will be able to inspect the object that is returning from your ajax call.
Also, the console.log will not work in IE as far as I know.
Have fun.
function getCities(callback){
var string = $.ajax ({
url: "getCities.php",
dataType: 'json',
success:callback
});
}
$(document).ready(function (){
getCities(function(data){
console.log(data);
var city = JSON.parse(data);
if (city.length > 0) {
document.write(city.pop + "<br/>");
}
});
});
Ajax is asyn, you cannot use var city = getCities();. Because when you call that, ajax response has not arrived yet. You need to pass in a callback function, and when ajax response has arrived, call that function to get the response.

Categories