I simply have:
<script>
$('#blah').on('click', function(){
$.ajax({
type: 'POST',
url: 'ajax.php',
data: {"xxx":"yyy", "zzz":"nnn"}, // my variables...
success: function(response){
// response = "success,123" from server side
// so for accessing to the values "success" and "123" I just:
status = response.split(",")[0];
count = response.split(",")[1];
// now "status" and "count" are undefined in IE while it's working in all other browsers
}
});
});
</script>
As you can see in the above code, the server response to the Ajax is "success,123".
for accessing to values "success" and "123" I do:
status = response.split(",")[0];
count = response.split(",")[1];
Now status and count are undefined in IE while they are good in every other browsers.
What should I do to fix this?
Thanks
While I'm not sure why IE does this and I can't really test now, a smarter alternative would be to use JSON for response. If you use PHP, json_encode could be used to turn a simple array to JSON:
<?php
echo json_encode(array('status' => 'success', 'count' => 123));
And then:
// your response originally looks like this:
// { status: 'success', count: 123 }
// you can define $.ajax with { dataType : 'JSON' } instead of:
response = $.parseJSON(response);
console.log(response.status);
console.log(response.count);
If you're not using PHP just search for the way to do it on your language.
This will also save you the headache of handling responses which contain your separator inside later on (sentences with , in them, for example)
That's because you haven't defined the variables.Instead of:
status = response.split(",")[0];
I would try
var status = response.split(",")[0];
Related
I'm using Jquery's ajax method, and I need help parsing data coming back from backend server.
server response will be either "valid" or "not valid.
Currently my "if statement logic is not working, this is what I have tried so far).
$.ajax({
url: 'php/phone-valid.php',
type: 'POST',
data: {userid: $.trim($('#userid').val())},
success: function(data) {
console.log(data);
if (result.indexOf("not valid")) {
("#mustbevalid").val("You must validate your phone number");
console.log("Phone hasn't been validated");
e.preventDefault();
};
}
});
Your help is highly appreciated.
You're checking result.indexOf, but your response data is in data not result. Additionally, indexOf returns the position, which could be 0. So change to:
if(data.indexOf("not valid") > -1) {
Side note: this method of checking a result is error-prone and usually undesirable. It would be better for you to output a JSON object with a success property.
Example success response:
echo json_encode(array('success' => true));
// Outputs: {"success":true}
Example error response:
echo json_encode(array('success' => false));
// Outputs: {"success":false}
Now, you can parse the JSON:
$.ajax({
...
dataType : 'json', // <-- tell jQuery we're expecting JSON
success: function(data) {
if (data.success) {
// success
} else {
// error
};
}
});
indexOf will return the position in the string. So use this instead:
if(data.indexOf("not valid") == 0)
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
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.
I have a php script which is sucessfully connecting to and sending an email through the Mandrill API. As dumb as it sounds, I can't figure out how to parse the following JSON reponse:
Array
(
[0] => Array
(
[email] => matt#mattblum.com
[status] => sent
[_id] => eedced1b58e24668907024e937afeabd
[reject_reason] =>
)
)
Full ajax call is:
$.ajax({
type: 'POST',
url: 'mandril.php',
data: formData.serialize(),
success: function(returnedData) {
var response = returnedData;
status = response[0]['status']; // I've also tried different combos of this
if(status == "sent") {
msgs('Message sent!');
var alreadySent = true;
} else {
msgs(response);
}
},
error: function(e) {
console.log(e);
}
The code I've tied to read the 'status' element:
console.log(response[0]['status']);
console.log(response[0][1]);
console.log(response[0][0]['status']);
console.log(response[0][0][1]);
Another thing I don't understand is that:
var response = returnedData;
console.log(response[0]);
Returns a capital 'A' and nothing else.
I'm sure it's something dumb that I'm doing but any help is greatly appreciated.
Matt,
Looks like your PHP array syntax is being captured as text and sent as a response to your post. If you specify JSON on the Mandrill/PHP side (and the ajax/jquery side) your jquery call should be able to parse the response.
console.log(response[0]) is returning 'A' because that's the first character of the string.
Add 'json' on the query side and json_encode($response) on the php side.
Im using ajax .POST to run php script that suppose to return true/false. Im returning true/false using "echo" in my script. But after i get the result back to JS i compare the received text in an IF statement that never works! here is my code
$.ajax({ url: 'admin_checkuser.php',
data: {action: window.myId},
type: 'post',
success: function(output) {
if (output == "true"){
and here is the php script that being called
include_once('class.MySQL.php');
$userid = $_POST['action'];
$oMySQL = new MySQL();
$query = "Select * FROM videotable WHERE uid = '$userid'";
$oMySQL->ExecuteSQL($query);
$bb = $oMySQL->iRecords;
$aa = $oMySQL->aResult;
if ($bb == 0){
$query = "INSERT INTO videotable VALUES ('','$userid','true')";
$oMySQL->ExecuteSQL($query);
echo 'true';
exit();
}else{
$sharing = mysql_result($aa,0,"share");
echo $sharing;
exit();
}
I made sure that i receive true\false by doing "alert(output)" and it always displays true\false so i really dont understand why my IF statement fails even when alert(output) shows true
Thanks in advance!
Trying to parse the type of an ajax response tends to be super unreliable, in my experience.
For that reason, I (now) make darn sure that whenever I write a server side function that is meant for returning ajax data, I keep it perfectly in line with my own set response "standard", and then set my response type in the ajax method to JSON.
Doing so makes handling errors much more predictable.
An example of a standardized response would be:
$ajaxResponse = array(
'data' => $someData,
'result' => true,
'message' => 'your yadayada was succesful',
'timestamp' => time()
);
print json_encode($ajaxResponse);
and in ajax, your response would be like:
success: function( response ) {
if(response.result) {
alert(response.message);
}
}
Sorry if this isn't much help but you could try:
$.ajax({ url: 'admin_checkuser.php',
data: {action: window.myId},
type: 'post',
dataType: 'json',
success: function(output) {
if (output) { ... }
and
echo json_encode(true);
// echo json_encode($sharing);
The jQuery documentation gives more detail on what this call returns: http://api.jquery.com/jQuery.ajax/.
success(data, textStatus, jqXHR)Function, Array
A function to be called if the request succeeds. The function gets
passed three arguments: The data returned from the server, formatted
according to the dataType parameter; a string describing the status;
and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery
1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.
It looks like you are expecting the data that is returned from the AJAX call to be the string "true" in your test, so if that isn't passing it must be you are getting back something other than this exact string.
I recommend using the net tab of Firebug in Firefox to see the XHR request and to examine the response of what you are getting back to see if it is something other than what you expect.