My form is returning data from PHP via jQuery. How can I create conditional statements based on the response in jQuery.
This is the jQuery:
$.ajax({
type: "POST",
url: "createAlbum.php",
data: postData,
success: function(data){
$('#message').fadeIn();
$('#message').html(data);
}
});
This is what it is returning from PHP:
if($error) {
echo $error;
}
else {
echo $success;
}
So if the response is success, the message should hide after a few seconds, but if it is an error, it should wait till the user corrects it. Something like this:
success: function(data){
$('#message').fadeIn();
$('#message').html(data);
if (data.response == 'success') {
alert('Success');
setTimeout(function() {
$('#message').fadeOut();
}, 5000 );
} else if (data.response == 'error') {
alert('Error');
}
}
Why don't you use the statusCode setting for your call to ajax() and have even more fine-grained control than just "success" and "error"? There are (or will be) many different ways your script could succeed or fail.
statusCode(added 1.5)Map Default: {}
A map of numeric HTTP codes and
functions to be called when the
response has the corresponding code.
For example, the following will alert
when the response status is a 404:
$.ajax({ statusCode: {
404: function() {
alert('page not found');
} } });If the request is successful, the status code functions
take the same parameters as the
success callback; if it results in an
error, they take the same parameters
as the error callback.
UPDATE:
I've added an example of how to use statusCode instead of success and error settings for ajax() call in Jquery. First, the test UI:
<html>
<head>
<title>jQuery Test Page</title>
<script type="text/javascript" src="jquery-1.6.js"></script>
<script type="text/javascript">
function displayMessage(message){
$('#message').fadeIn();
$('#message').html(message);
}
function successFunction(data){
displayMessage(data);
}
function notFoundFunction(){
displayMessage("Not Found!");
}
function errorFunction(){
displayMessage("An Error Occurred!");
}
function invokeAjax(test){
$.ajax({
type: "POST",
url: "test.php?test="+test,
//data: postData,
statusCode: {
200: successFunction,
404: notFoundFunction,
500: errorFunction,
}
});
}
</script>
</head>
<body>
<h1 id="message" style="display:none;"></h1>
Invoke Ajax - Success (200)<br>
Invoke Ajax - Not Found (404)<br>
Invoke Ajax - Error (500)<br>
</body>
</html>
And here's the PHP script called by the Ajax:
<?php
$test = $_GET['test'];
if($test == 'success'){
echo 'some meaningful data';
} else if($test == 'notfound') {
http_send_status(404);
} else if($test == 'error'){
http_send_status(500);
}
?>
I think it's pretty self-explanatory, but if you have any further questions, don't hesitate to ask.
Of course, to get AJ's solution to work, you need to respond from the server to the client with the correct headers - http://no.php.net/manual/en/function.header.php:
header('HTTP/1.1 404 Not Found');
or
header('HTTP/1.1 500 Internal Server Error');
Here is a list of HTTP codes: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
Hope this helps :)
Thank you for your helpful answers. I solved it using JSON though!
PHP:
if($error) {
echo json_encode(array('success' => false, 'text' => $error));
}
else {
echo json_encode(array('success' => true, 'text' => $success));
}
jQuery:
if (data.success) {
alert('Success');
setTimeout(function() {
$('#message').fadeOut();
}, 5000 );
} else {
alert('Error ' + data.text);
}
Related
so I have the following code that is calling a CheckEmail2.php. I know what I want to do in CheckEmail2.php but because my Ajax success is not working, I have minded the scope to just return a Json. below is my java script. When I launch my console, I see my string coming through that I am echoing in my CheckEmail2.php. so I know my php file is getting read but why won't my success function hit if my string is getting read? I can't get my success function to get called. It always goes to error.
<script type="text/javascript">
function validateForm(){
var email = document.forms["signupform"]["email"].value;
var result = false;
if (email != ""){
$.ajax({
type: "POST",
url: "/CheckEmail2.php",
data: { "User_Email": email },
dataType: "json",
success: function(resp){
console.log(resp);
if(resp == "Not Found"){
result = true;
}
else
{
result = false;
}
},
error: function(data, status){
console.log(data, status);
}
}); //end Ajax
}
return result;
}
</script>
here is my PHP
<?php
header("Content-type:application/json");
echo json_encode("Not Found");
?>
why is error always getting called?
I'm trying to get real-time message and response from this POST, but doesn't work for me. I want to display in this Ajax text from timezone.php - error or success Where I made mistake?
HTML
<form id="timezone_form">
<select name="timezone_select">
<option value="1">test 1</option>
<option value="2">test 2</option>
</select>
<input type="submit" value="Submit"/>
</form>
<div id="settings_ajax_message"></div>
JS
$(document).ready(function() {
$("#timezone_form").submit(function() {
$.ajax({
type: "POST",
url: "timezone.php",
data: $(this).serialize()
})
.done(function(data) {
$("#settings_ajax_message").html(data);
})
.fail(function() {
$("#settings_ajax_message").html(data);
});
return false;
});
});
timezone.php
<?php
$timezone = $_POST['timezone_select'];
if ($timezone == 1) {
echo '<div class="ch-mes-fixed-warning-animation"><div class="ch-mes-warning">error</div></div>';
} else {
echo '<div class="ch-mes-fixed-success"><div class="ch-mes-success">success</div></div>';
}
?>
First thing, you have to understand why your fail function would be called:
$(document).ready(function(e) {
// Prevent the form from actually submitting to the server
e.preventDefault();
$("#timezone_form").submit(function() {
$.ajax({
type: "POST",
url: "timezone.php",
data: $(this).serialize()
})
// Status code 200-299 was returned. The data was successfully returned from the server.
// PHP by default will always return 200 (Which signifys that the server processed the data, and is returning it)
.done(function(data) {
$("#settings_ajax_message").html(data);
})
// Status 300+ was returned from the server. This usually indicates an error on the server (ie. 404 not found, or 500 server error)
.fail(function() {
$("#settings_ajax_message").html(data);
});
return false;
});
});
You have 2 ways to handle this. 1, have your server actually return an error (Usually the preferred route for an API):
header("HTTP/1.0 422 Error");
In most cases, you should catch bad errors with .fail like if your server craps out. Have your server return 200 (Which will process the done function), but check for an error property:
<?php
// Tell javascript this is a json response:
header("Content-type: application/json");
$timezone = $_POST['timezone'];
if ($timezone == 1) {
echo json_encode(['error' => true, 'message' => '<div class="ch-mes-fixed-warning-animation"><div class="ch-mes-warning">error</div></div>']);
} else {
echo json_encode(['error' => false, 'message' => '<div class="ch-mes-fixed-success"><div class="ch-mes-success">success</div></div>');
}
?>
And your ajax:
$(document).ready(function() {
$("#timezone_form").submit(function() {
$.ajax({
type: "POST",
url: "timezone.php",
dataType: 'json', //IMPORTANT! PROCESS AS JSON
data: $(this).serialize()
})
.done(function(data) {
if (data.error) {
console.log(data);
//Do something with the error
$("#settings_ajax_message").html(data.message);
} else {
//No error. data.message will be the message
}
})
.fail(function() {
$("#settings_ajax_message").html(data);
});
return false;
});
At first, your field name is timezone_select, look here: <select name="timezone_select">. In PHP you checking another name: $timezone = $_POST['timezone'];
When I run this script, instead of the error inserting HTML in the page, it returns an alert like the success function - but with the error message instead.
AJAX
$(function() {
$('form').submit(function() {
$page_title = $('input[name="page_title"]').val();
$.ajax({
method: 'GET',
url: 'test-script.php',
datatype: 'jsonp',
jsonp: 'jsonp_callback',
data: {
page_title: ($page_title),
},
success: function(result){
alert(result);
},
error: function(result) {
$('#error').html('result');
}
});
});
});
PHP
<?php
if(isset($_GET)) {
if (! empty($_GET['page_title'])) {
$title = $_GET['page_title'];
print $title;
} else {
$error = ('Name required');
print $error;
}
}
add a http_response_code(); to your php to tell js, that there was an error. Also you better should send back a json encoded error string, that can be understood by javascript.
<?php
if(isset($_GET)) {
if (! empty($_GET['page_title'])) {
$title = $_GET['page_title'];
echo $title;
} else {
http_response_code(400);
$error = ["message"=>"Name required"];
echo json_encode($error);
}
}
See the list of appropriate response codes
EDIT:
Response to your comment "the HTML is inserted... then disappears"_:
You need to prevent the form from beeing submitted. To do that add event.preventDefault() to your onSubmit handler:
$('form').submit(function( event ) {
event.preventDefault();
// rest of your code...
Consider the following:
<?php
//daytime_check.php
$is_daytime = false;
if ($is_daytime) {
echo '1';
} else {
echo '0';
}
?>
==================================================================================
// javascript/jQuery
$.ajax({
type: 'POST',
url: 'daytime_check.php',
success: function(response) {
if(response == false) {
alert('Goodnight, brother');
} else {
alert('Day\'s a wastin, brother');
}
},
error: function() {
//handle error
}
});
This is how I have heretofore handled the responses from my AJAX'd PHP scripts. I'm hoping someone out there can give me some hints on a better way, as this current method feels pretty clunky.
Especially clunky is handling the "filtering" of the PHP script's output on the JS side. For example:
In this case, the response from PHP is going to be a JS var response ='0'. Now one can't simply use if (!response)... in JS to filter, because apparently !response evaluates to false, while, interestingly, response == false evaluates to true. Something to do with type juggling, I suppose.
Since the only way I can return things from PHP is in text (echo statements), I can't return proper true/false values to filter on when I get to the JS side. Is there a better way to handle this?
I hope this made at least a little sense.
You can stil return any type you would like to. Just use JSON response.
// you can return what ever you want via JSON
die(json_encode(array(
'isDateTime' => $is_datetime,
'message' => 'Some optional message to display',
'timestamp' => time()
)));
This will output this string:
{"isDateTime":false,"message":"Some optional message to display","timestamp":1332792739}
And on client side jQuery will parse this response:
$.ajax({
type: 'POST',
url: 'daytime_check.php',
dataType: 'json',
success: function(response) {
if (response.isDateTime) { ... }
// typeof response.isDateTime == 'boolean'
// alert(response.message)
},
error: function() {
//handle error
}
});
If you only have to display the message in success handler then why don't you return the message itself?
<?php
//daytime_check.php
$is_daytime = false;
if ($is_daytime) {
echo "Day's a wastin', brother";
} else {
echo "Goodnight, brother";
}
?>
$.ajax({
type: 'POST',
url: 'daytime_check.php',
success: function(response) {
alert(response);
},
error: function() {
//handle error
}
});
Here is a neat solution provided by an intelligent former co-worker.
Return values from your PHP scripts in the following manner:
<?php
// To return an error
echo json_encode(
array(
'success' => false,
'message' => '[error message here]',
)
);
// To return a successful response
echo json_encode(
array(
'success' => true,
'response' => [return value here],
)
);
This way, we can easily do logic on the JS side:
$.ajax({
type: 'POST',
url: 'ajax_example.php',
success: function(response) {
response = JSON.parse(response);
if (!response.success) {
alert(response.message);
} else {
console.log(response.response);
}
},
error: function() {
//handle error
alert('error doing ajax, mate');
}
});
this works:
$.ajax({
type: 'POST',
url: 'register.php',
data: {captcha: captcha
},
success: function() {
$('#loading').hide();
$('#success').fadeIn();
}
error: function() {
$('#loading').hide();
$('#captcha').fadeIn();
$('#catErrorB').fadeIn();
}
});
sends captcha response to PHP and if entered correctly, you can register. problem is, is that if you incorectly enter your captcha, the JQuery still runs the functions for a successful run although the PHP ran a "die" and did nothing.
In PHP, if the captcha is entered incorrectly is does this
if (!$resp->is_valid) {
die ("false");
}
else
{
register
}
How do I request the error that PHP spits out so I can do something like?
success: function(find error) {
if(error == "false")
{
$('#loading').hide();
$('#captcha').fadeIn();
$('#catErrorB').fadeIn();
}
else
{
$('#loading').hide();
$('#success').fadeIn();
}
}
EDIT!:
With your help heres what it looks like now and it works fantastic!!
$.ajax({
type: 'POST',
url: 'register.php',
dataType: "json",
data: {
challenge: challenge,
response: response,
zip: zip
},
success: function(result) {
if (!result.success) {
$('#loading').hide();
$('#captcha').fadeIn();
$('#catErrorB').fadeIn();
}
else {
$('#loading').hide();
$('#success').fadeIn();
}
}
});
and the PHP
if (!$resp->is_valid) {
$response = array(success => false);
echo json_encode($response);
}
else
{
$response = array(success => true);
echo json_encode($response);
Ya'll are the coolest. My first JQuery I've ever done, It's came out so awesome. This site rules!
I wouldn't use success/failure. Even if the script dies it is still going to return a 200 SUCCESS to your ajax call.
Use JSON to return responses depending on whether or not it is a success and parse and proceed with correct logic
<?php
if ( $resp->is_valid ) {
echo json_encode( array( 'status' => 'true' ) );
} else {
echo json_encode( array( 'status' => 'false' ) );
}
?>
Then you can parse the response in your AJAX call. Remember, if you call die('false'); that is still going to return a success message to your ajax function.
PHP:
if (!$resp->is_valid) {
$response = array(success => false);
echo json_encode($response);
}
else {
$response = array(success => true);
echo json_encode($response);
}
jQuery:
success: function(result) {
if (!result.success) {
// Wrong input submitted ..
}
else {
// Correct input submitted ..
}
}