Ajax select post with real-time message - php

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'];

Related

Ajax query, php file is getting read but can't enter success function

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?

jQuery AJAX call returns results before page headers resulting in parseerror

I am trying to create a simple AJAX call using JSON, but I keep getting a parse error on the result and when I check the resultText it shows the source code of the entire page, with the JSON response showing a success above the page headers.
Here is my AJAX call, where #class is a select box with values.
$("#class").change( function () {
if($('#class').val().length > 0){
$.ajax({
type: "GET",
url: "http://192.168.0.9/ajax",
data: 'class_id=' + $("#class").val(),
datatype: 'json',
async: 'true',
beforeSend: function() {
alert("Before send!");
},
success: function(result){
if (result.status){
$('#result').html(result);
} else {
alert('request unsuccessful!');
}
},
complete: function() {
alert("Complete!");
},
error: function (request,error) {
alert('A jQuery error has occurred. Status: ' + error +':'+ request.responseText);
$("#result").html(request.responseText);
}
});
} else {
alert('Please make a selection');
}
return false;
});
This is my PHP function that returns the result
$result = array();
$result['status'] = "success";
$result['message'] = "Types";
header("Content-Type: application/json; charset=utf-8", true);
echo json_encode($result);
Finally, this is the response I am getting in my error alert:
A jQuery error has occurred status:parseerror
{"status":"success", "message":"Types"}<!DOCTYPE html>
<html>
...rest of my page from where the request was sent
I am hoping this is a simple error and someone can tell me what I am doing wrong?
Perhaps your parameter should be pass in JSON format:
data: "{'class_id':'" + $("#class").val() + "'}",
Try to remove datatype:'json' from the Javascript and header("Content-Type: application/json; charset=utf-8", true); it should be recognize itself

Handle error in jQuery.ajax() when something doesn't work

I have a php file with a form that is sent using jQuery.ajax(). The problem that I have if the email is not sent and the error message is not shown.
$(document).ready(function () {
$('input[type="submit"]').click(function () {
$.ajax({
url: "mail.php",
type: "POST",
data: {
name: $('input[name="name"]').val(),
email: $('input[name="email"]').val(),
msg: $('input[name="msg"]').val()
},
cache: false,
success: function(responseText) {
$('#result').css('background', 'green');
},
error: function(responseText) {
$('#result').css('background', 'red');
}
});
return false;
});
});
As the email is not sent the error not shows anything but the success yes. So, I change my mail.php code for that other code.
<?php
if(2 > 4) {
true;
} else {
false;
}
?>
When I press the button, the success action stills working and I don't know why.
The error callback is only triggered if the ajax call fails, not if the PHP mail function fails, and not if you return false, that would be a success as you received something back from the server (the string "false").
To catch errors like that you can either trigger an error from PHP or just catch it in the success handler:
success: function(data) {
if (!data || $.trim(data) == 'false') {
$('#result').css('background', 'red');
}else{
$('#result').css('background', 'green');
}
},
and PHP
<?php
echo 2>4 ? 'true' : 'false';
?>
Remove the error function & make changes to your success function
$.ajax({
url: "mail.php",
type: "POST",
data: {
name: $('input[name="name"]').val(),
email: $('input[name="email"]').val(),
msg: $('input[name="msg"]').val()
},
cache: false,
success: function(responseText) {
if(responseText)$('#result').css('background', 'green');
else $('#result').css('background', 'red');
}
});
The error function will not trigger unless jQuery fails to connect to your php file, in this case you would wan't to handle your own errors, first off what does this do?
if(2 > 4) {
true;
} else {
false;
}
this would not send anything back to jQuery i recommend the following
if(2 > 4) {
echo 'true';
} else {
echo 'false';
}
then in your jQuery
$(document).ready(function () {
$('input[type="submit"]').click(function () {
$.ajax({
url: "mail.php",
type: "POST",
data: {
name: $('input[name="name"]').val(),
email: $('input[name="email"]').val(),
msg: $('input[name="msg"]').val()
},
cache: false,
success: function(result) {
if(result === 'true') {
$('#result').css('background', 'green');
} else {
$('#result').css('background', 'red');
}
},
error: function(error) {
alert(error)
}
});
return false;
});
});
In your both cases, the success callback is fired:
success: function(responseText) {
if(!!responseText) //!! convert string to boolean
$('#result').css('background', 'green');
else
$('#result').css('background', 'red');
},
First in mail.php file echo that you want to return:
<?php
if(2 > 4) {
echo "true";
} else {
echo "false";
}
?>
And then in success function do that:
success: function(responseText) {
if(responseText) {
$('#result').css('background', 'green');
} else {
$('#result').css('background', 'red');
}
}
It also depends on the version of the jquery you are using. If its 1.9 then you can handle it using the done, fail and always function
For 1.9
var request = $.ajax({
url: "mail.php",
type: "POST",
data: {
name: $('input[name="name"]').val(),
email: $('input[name="email"]').val(),
msg: $('input[name="msg"]').val()
}
});
request.done(function(e){
//GET THE STATUS FOR THE EMAIL FROM THE PHP SCRIPT
//ASSUMPTION THAT FETCHING e=1/0 - 1 - Success, 0 - Failure
if(parseInt(e))
{
$("#result").css("background","green");
}
else
{
$("#result").css("background","red");
}
});
1) Your php script doesn't return anything. For instance, if you eliminate all javascript from your html page, and your form's action attribute specifies myphp.php, and myphp.php looks like this:
<?php
$html = "<html><head></head><body><div>Hello world.</div></body></html>";
?>
What will be displayed after you click on the form's submit button?
2) The error function is called if the request fails. Getting a response of nothing or false from your php script is not a failure of the request. A successful request means that the browser sent out a request, the server received the request, the server caused your php script to execute, and the server sent back the results of your php script as a response. A request fails if the server is too busy to respond to the request, the server crashes while handling your request, you request a file that doesn't exist, etc.

Validate if website exists with AJAX

I'm trying to check if a website exists with an ajax call, but I'm not sure I am getting it right. On my page I grab a URL on click
$("#go").click(function() {
var url = $("#url").val();
$.ajax({
type: "POST",
url: "/ajax.php",
data: "url="+url,
success: function(){
$("#start").remove();
},
error: function(){
alert("Bad URL");
}
});
});
a=And then check on ajax.php
$url = $_POST['url'];
ini_set("default_socket_timeout","05");
set_time_limit(5);
$f=fopen($url,"r");
$r=fread($f,1000);
fclose($f);
if(strlen($r)>1) {
return true;
} else {
return false;
}
It seems I am getting SUCCESS no matter what... What am I missing?
It seems I am getting SUCCESS no matter what... What am I missing?
This is extremely pretty straightforward.
Because of this reasons:
// You have no idea what server respond is.
// that is you can't parse that respond
success: function(){
$("#start").remove();
}
Which should be
success: function(respond){
//you don't have to return TRUE in your php
//you have to echo this one instead
if ( respond == '1'){
$("#start").remove();
} else {
//handle non-true if you need so
}
}
In php replace this:
if(strlen($r)>1) {
return true;
} else {
return false;
}
to
if(strlen($r)>1) {
print true; //by the way, TRUE is a constant and it equals to == 1 (not ===)
}
Oh yeah, also don't forget to fix this as well:
data: "url="+url,
to data : {"url" : url}
As Nemoden said, you get a success message even if it returns false.
You need to check the data returned and then remove the element.
for example
$("#go").click(function() {
var url = $("#url").val();
$.ajax({
type: "POST",
url: "/ajax.php",
data: "url="+url,
success: function(response){
if (response == 'whatever you are returning') {
$("#start").remove();
}
},
error: function(){
alert("Bad URL");
}
});
});
Success callback is called whenever server-side script returned an answer (there were no connectivity errors or server-side errors). Is this answering your question?
See the difference:
$("#go").click(function() {
var url = $("#url").val(),
ajax_data = {url: url};
$.post({
"/ajax.php?cb=?",
ajax_data,
function(response){
if (response.status) {
// URL exists
}
else {
// URL not exists
}
$("#start").remove();
},
'json'
});
});
php back-end:
printf('%s(%s)', $_GET['cb'], json_encode(array('status' => (bool)$url_exists)));

Conditional statements based on PHP response via jQuery

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

Categories