if statement not evaluating correctly - php

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.

Related

Ajax success not reading PHP echo as string

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:');
}
});

$.ajax get return value from a PHP file

here I have jQuery ajax calling a .php file that SOMETIMES executes let's say the following
echo "hello"
Here it is:
$.ajax({
type: "POST",
url: myurl.php
data: data_string,
timeout: 6000,
success: function () {
}
});
I would like to know: is it possible to make the ajax return ERROR and not SUCCESS when something like the previous echo is executed in the PHP file? I mean, checking inside this $.ajax if the php file is executed as I would or not.
EXPLAINING BETTER:
I get error when the request could not be completed and success when it could. But I would like to get like a return value from this PHP file. If it returns 1, I wanna do something. If it returns 2, instead, I wanna do something else. Hope I explained it better..
Thanks in advance.
I recommend using json_encode() within your PHP file. For example:
echo json_encode(array('success' => 'do_foo'));
exit();
Then you can add a conditional within the success callback:
$.ajax({
type: "POST",
url: myurl.php
data: data_string,
dataType: "JSON", //tell jQuery to expect JSON encoded response
timeout: 6000,
success: function (response) {
if (response.success === 'hello'){
console.log(response);
} else {
console.log('else');
}
}
});
Based on your question make php return 1 or return 2. You can make it return 1 on failure and 0 (which is null) on success. Then you can do this for your ajax return.
$.ajax({
type: "POST",
url: "YOUR URL",
data: dataString,
success: function(server_response)
{
if(server_response == 1)
{
alert("You have made a mistake");
return true;
}
HERE YOU WILL PUT WHAT HAPPENS ON SUCCESS
}
});
$.ajax({
type: "POST",
url: myurl.php
data: data_string,
timeout: 6000,
success: function (msg) {
if (msg != "Hi")
{
//TODO
} else
{
//TODO
}
}
});
You can use error callback for this:
$.ajax({
type: "POST",
url: myurl.php
data: data_string,
timeout: 6000,
success: function () {
},
error: function() {
/* Code reacting to error here */
}
});
Also, there are other callback opportunities which you can check out at $.ajax documentation page.
If you are going to "say" fron PHP that there is an error, this can be done with 2 ways:
You can print in PHP a keyword meaning an error and then check it in you success function:
success: function (data) {
if (data == 'error') {
} else {
}
}
Or, the other way, you can provide with PHP right headers to cause "error". Then you can use the error callback as usual. I would choose this way.

Cant get value back from PHP

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.

Jquery submits form but does not fade my div

The title almost says it all. I have a jquery code i've written, im not good at it but this is what i achieved:
$("#myForm").submit(function(){
//alert($(this).serialize());
$.post("submit.php", $(this).serialize(), function(data){
if(data == success) {
$("#add_vote").fadeOut("fast");
$("#verification_sent").fadeIn("fast");
$("#wrong").fadeOut("fast");
} else {
$("#wrong").fadeIn("fast");
}
});
return false;
});
The form gets submitted well but the fadeIn and fadeOut's I have does not work. Do anyone know why?
Verify what submit.php returns, and what is in data.
if(data == success) {
This looks suspicious, did you meant if (data == "success") { ? (success is a variable, probably undefined; "success" is a string.)
What is success in:
if(data == success) {
Maybe you mean:
if(data == "success") {
Or else you maybe have misunderstood the $.post function?
$.post("submit.php", $(this).serialize(), function(data){
Lets break it up:
"submit.php" // the url (OK)
$(this).serialize() // The data (OK)
function(data){ // The callback on success
And its only a helper function for the $.ajax method, Witch also have a error callback:
var ajaxObj = $.ajax({
type: 'POST',
url: "submit.php",
data: $(this).serialize()
});
ajaxObj.success(function(){
// Success
});
ajaxObj.error(function(){
// Error
});

problem with jquery from.submit and ajax

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');
}
});

Categories