I have a simple PHP script which, when it executes correctly from an AJAX call, ends with:
echo "ok";
Yet when I try to parse this information it tells me its not a string.
In the example below the result is: alert('error: Type Mismatch');
Why does JQuery not read the php echo as a string?
$.ajax({
url: '/ajax/actions/imageUpload.php?act_id=<?=$act_id?>',
type: 'POST',
success: function (response) {
if(typeof response == typeof 'string'){
if( response == 'ok')
alert('all is good');
else
alert('error:');
} else {
alert('error: Type Mismatch');
}
}
});
Screenshot below shows that the response is correct and simply says 'ok'
As I'm reading from jquery Api Doc I understand that you can get a "string" or something else as a response, based on what kind of dataType you passed (if u did) in your $.ajax object. Otherwise it will be assumpted from jQuery, based on some its own logic.
In my opinion you should avoid every assumption and explicitly pass your dataType based on the response format you'll send.
So,
in case you'll set response.php to return
echo "ok";
you should set dataType "text" in your ajax call:
$.ajax({
url: 'imageUpload.php',
type: 'POST',
dataType: "text",
...
and get the response with:
if(typeof response == "string")
{
console.info(response);
...
Or
in case you'll set response.php to return something like
echo json_encode(array("data" => "ok"));
you should set dataType "json":
$.ajax({
url: 'imageUpload.php',
type: 'POST',
dataType: "json",
...
and get the response with:
if(typeof response == "object")
{
console.info(response.data);
...
$.ajax({
url: '/ajax/actions/imageUpload.php?act_id=<?=$act_id?>',
type: 'POST',
success: function (response) {
if (typeof response === "string"){
if (response == 'ok')
alert('all is good');
else
alert('error:');
} else {
alert('error: Type Mismatch');
}
}
});
Do it another way:
In you php script echo back a JSON: json_encode("ok");
In AJAX specify dataType: "json" and add event:
complete: function(jsondata, stat)
{
if(stat == "success")
alert( $.parseJSON( jsondata.responseText ) );
}
The response is not string type, it is a PlainObject object.
success
Type: Function( PlainObject data, String textStatus, jqXHR jqXHR )
typeof response == 'object' // true
Try this:
$.ajax({
url: '/ajax/actions/imageUpload.php?act_id=<?=$act_id?>',
type: 'POST',
dataType: "text",
success: function (response) {
if( response == 'ok')
alert('all is good');
else
alert('error:');
}
});
Related
I am trying to figure out how to just display a particular response from php using ajax for example. I have a php which gives the following response -
echo 'Success'; //Display only this
//Some other process
echo 'Something else for other process';
JS
$.ajax({
type: "POST",
url: "some.php",
data: {action: 'test'},
dataType:'JSON',
success: function(response){
$( '#name_status' ).html(response);
}
});
Use if else.
And while sending AJAX request, send conditional parameters.
For example, flag: set it to either yes or no.
Get these parameters $_POST ed in PHP back end.
Depending upon the value of AJAX sent parameter, print the response.
JS:
$.ajax({
type: "POST",
url: "some.php",
data: {action: 'test', 'flag' : 'yes'},
dataType:'JSON',
success: function(response){
$( '#name_status' ).html(response);
}
});
Set flag to yes or no // This is just sample.
In PHP,
if (isset($_POST['flag'] && $_POST['flag'] == 'yes') {
echo 'Success'; //Display only this
}
else {
echo 'Something else for other process';
}
You will have send json_encode to receive a JSON response and will have to accordingly change the PHP too. Below is the updated code that you can try:
PHP:
if($_POST['action'] == 'test') {
$returnArray = array('message' => 'Success');
} else {
$returnArray = array('message' => 'Something else for other process');
}
echo json_encode($returnArray);
JS
$.ajax({
type: "POST",
url: "some.php",
data: {
action: 'test'
},
dataType: 'JSON',
success: function(response) {
var responseObj = jQuery.parseJSON(response);
$('#name_status').html(responseObj.message);
}
});
I apologize for my bad english :)
I'm doing php file with ajax request. json response comes in the format of. but in some cases can be redirect. In this case I want the redirect of the page.
Could you please help me. Thank's.
Example PHP File :
<?php
$status = $_POST['status'];
if($status == 'a'){
// return json response
}else{
echo "<form action='http://www.url.com'>..</form><script type='text/javascript'>form.submit();</script>";
}
?>
Example JS File :
$.ajax({
type: "POST",
url: 'http://www.my_php_file.com'
});
Use success function https://api.jquery.com/jQuery.ajax/
$.ajax({
type: "POST",
url: 'http://www.my_php_file.com'
data: { status : statusVar },
success: function(response){
if (response.status == 'a'){
$( "#results" ).append( response);
}else{
window.location = 'http://www.url.com'
}
});
});
Try this.
url: "http://www.my_php_file.com",
success: function(data) {
document.location.href='YouNewPage.php';
}
You need to detect if the response data is valid JSON:
$.ajax({
type: "POST",
url: 'http://www.my_php_file.com',
success: checkAJAX
});
function checkAJAX(data)
{
var response = $.parseJSON(data);
if(typeof response === "object")
{
}
else
{
// If the AJAX response is not JSON, append the HTML to the document
$('body').append(data);
}
}
Return the html that you want to echo as JSON also:
if($status == 'a'){
// return json response
} else {
echo json_encode(array("redirect" => "<form action='http://www.url.com'>..</form><script type='text/javascript'>form.submit();</script>"));
}
And check redirect in the ajax response:
$.ajax({
type: "POST",
dataType: "json",
url: 'http://www.my_php_file.com',
success: function(data) {
if(typeof data.redirect !== "undefined") {
$("body").append(data.redirect);
}
}
});
Just two reminders, there will be no redirection if request fails( no fail callback) and I assume your casual JSON response doesn't have an attribute redirect.
so i am making a $.ajax call and returning json data. in said data there is an element named status. I am testing this: if(data.status === "success"){ ..do something..}. I know that the json data from the $.ajax call is in fact "success" (i know from the developers tools in chrome that the php script is returning {status: success}) however nothing in the if statement is being evaluated. and if i add an else statement to the if statement, that code DOES get evaluated. here is my code:
$.ajax({
type: "POST",
url: "./php/checkuser.php",
datatype: "json",
success: function(data){
console.log(1);
if(data.status === "success"){
console.log(2);
$.get("./mainmenu.html", function(html){
$("#content").html(html);
console.log(3);
});
$.ajax({
type:"POST",
url:"./php/loaduserdata.php",
dataType:"json",
success:function(data){
console.log(4);
if(data.status === "success"){
console.log(5);
var lastlevel = data.lastlevel;
if(lastlevel === 0){
console.log(6);
$("#continue-wrapper").removeClass("enabled").addClass("disabled");
$('<img />').attr('src', "./images/menuitem_continue-disabled.png").attr('id', "continue").attr('alt', "Continue").load(function(){
$("#continue-wrapper").html($(this));
});
} else {
console.log(7);
$("#continue-wrapper").removeClass("disabled").addClass("enabled");
$('<img />').attr('src', "./images/menuitem_continue-enabled.png").attr('id', "continue").attr('alt', "Continue").load(function(){
$("#continue-wrapper").html($(this));
});
}
}
}
});
} else {
console.log(8);
}
},
error: function(thrownError){
console.log(thrownError);
}
});
in the console for output i get 1 and 8. I'm stumped can someone see something that i can't?
In the first ajax request you have datatype it should be dataType, so data is just a string and data.status is undefined.
JavaScript
$.ajax({
type : 'POST',
url : 'post.php',
data: dataString,
success:function (data) {
if (data==null) { alert("darnit!!!!");}
//$("#response").append(data);
alert(dataString);
}
});
});
in PHP file just a simple
print_r($_REQUEST);
Also tried
echo "got iT!";
But nothing, been looking of over tried differant things but no luck
first //alert (dataString); works
but after the success:function (data) I don't get any alerts - no response within the page!
What am I doing wrong?
There's a SyntaxError in your snippet. I'm not sure if that's also in your real code.
Be sure to use json_encode in your PHP file and dataType: 'json' in jQuery.ajax. And always use an error callback as well. You don't want your application to become indefinitely frozen if something fails.
Something like this:
$.ajax({
url: 'api.php',
data: {
action: 'greet',
foo: 'bar',
baz: 'quux'
},
type: 'POST',
dataType: 'json',
}).then(function (response) {
console.log(response); // DEBUG
if (response.error) {
alert('Greet Error: ' + response.error);
} else {
alert(response.greet);
}
}).catch(function (jqXHR) {
console.log('AJAX Error', jqXHR); // DEBUG
alert('AJAX Error: Request failed');
});
PHP:
<?php
$input = $_POST;
$response = array();
if (!isset($input['action'])) {
$response['error'] = 'Action parameter required';
} else {
if ($input['action'] === 'greet') {
if (!isset($input['foo']) || !isset($input['bar'])) {
$response['error'] = 'Invalid greet request';
} else {
$response['greet'] = 'Welcome home, David!';
}
} else {
$response['error'] = 'Unknown action';
}
}
header('Content-Type: application/json; charset=utf8');
echo json_encode($response);
First: you missed dataType property from ajax function, next, you need to pass json type data, and you had a syntax error in code, try this:
$.ajax({
type : 'POST',
url : 'post.php',
dataType: 'text',
data: {
data_to_pass: dataString
},
success:function (data) {
if (data==null) {
alert("darnit!!!!");
} else {
//$("#response").append(data);
alert(dataString);
}
});
});
in PHP:
$dataString = $_POST['data_to_pass'];
if($dataString) {
echo "got IT!";
}
JQuery ignoring your data return usually means it doesn't understand the format that's being returned, or doesn't know what to expect. Set the dataType to an acceptable format and also double check that your PHP script is actually sending something back to the page in Firebug's console.
$.ajax({
type : 'POST',
url : 'post.php',
data: dataString,
dataType: 'text',
success:function (data) {
if (data==null) { alert("darnit!!!!");}
//$("#response").append(data);
alert(dataString);
}
});
});
I would like share the following, and I think I've solved the problem.
Besides the fact that I did made a mistake, retrieving the values from the form a bit wrong.
so the first alert gave me name=[Object name], now that was stupid.
The problem of not getting results seemed to be a problem with jquery itself, in my case.
I do not know if it is the same problem other people are having. I replaced the included file of jquery 1.7 with 1.4.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
than with the following code (only from $.ajax).
var dataString = $("#contactForm").serialize();
$.ajax({
type: 'POST',
url: './php/mail.php',
data: dataString,
success: function(msg){
if (msg === 'sent'){
$('#success').text('Message sent!');
} else{
$('#success').text('Mail Error. Please Try Again.!');
}
}
});
Now i have it working - and gonna tweak it a bit to my needs!
Thx all for all help!
Try this:
$.ajax({
type : 'POST',
url : 'post.php',
data: dataString,
success:function (data) {
if (data===undefined) { alert("darnit!!!!");}
//$("#response").append(data);
alert(data);
}
});
});
Also I would look into using json_encode on an array in your php file and returning a json object.
below is the code i am using
$(document).ready(function(){
$("form").submit(function(event) {
event.preventDefault();
var val = $("#captcha_text").val();
$.ajax({
url: 'checkAnswer.php',
type: 'POST',
dataType: 'text',
data: {
answer: val
},
complete: function(data)
{
console.log(data);
if($.trim(data) == "true")
$("form")[0].submit();
else
alert('Wrong Answer');
}
});
});
});
checkAnswer.php has this one line only which is
echo "true";
i do not know why the javascript if condition in the complete function is always going to else part and showing alert('Wrong Answer')
does any one know what could be the problem. ? In the firebug console i do see the response comming back from my ajax and response value is "true"
use:
if($.trim(data.responseText) == "true")
complete receives as 1st argument jqXHR(an extended XMLHTTP-Request-object) and not the data depending on dataType.
Or use success instead of complete
Well i think you have to do this:
$.ajax({
url: 'test.php',
type: 'POST',
dataType: 'text',
data: {
answer: val
},
complete: function(jqXHR, textStatus)
{ //it returns an jqXHR object
if($.trim(jqXHR.responseText) == "true")
$("form")[0].submit();
else
alert('Wrong Answer');
}
});
This is because jQuery returns a jqXHR object look here for reference.
EDIT You can also try this:
$.ajax({
url: 'test.php',
type: 'POST',
dataType: 'text',
data: {
answer: val
},
success: function(data)
{
if($.trim(data) == "true")
alert('ok');
else
alert('Wrong Answer');
}
});