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

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.

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?

Ajax select post with real-time message

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

Codeigniter Ajax error communication error

I am trying to check if username already exists in the table using ajax input onchange trigger in CodeIgnitor view.
Ajax function on the view
<script>
$('#username').on('change',function(e){
var u_name=$(this).val();
$.ajax({
type: "POST",
url: "<?php echo site_url('home/checkUserExist');?>",
data: { u_name: u_name },
dataType: "html",
success: function(msg){
$('#error_msg').empty();
$('#error_msg').append(msg);
},
error:function(error){
$('#error_msg').append("There is some errors on server : " + error.error);
return false;
}
});
});
</script>
Controller function
function checkUserExist()
{
$u_name= strip_tags(mysql_real_escape_string(trim($this->input->post('u_name'))));
if($this->public->checkMemberExisit($u_name)==false)
{
echo "<p>Username Exists, Try another username</p>";
}
else
{
echo "<p>Username Available</p>";
}
}
but i keep getting this error :
There is some errors on server : function (){if(h){var d=h.length;!function f(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this}
Can anyone tell me whats going on. it used to work before.

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

validate form without refreshing page and showing error through validationEngine

I'm using in the same page a validation engine with date picker.
Datepicker: http://jqueryui.com/demos/datepicker/
Validationengine: http://www.position-relative.net/creation/formValidator/demos/demoValidators.html
I've added a jQuery.noConflict(); to make it work (at the beginning of the code).
Now, I need to make my insert through a PHP file, but without refreshing the page, and by displaying an error message in the same bubble of validationEngine (for example when the email is already registered in the BDD).
should I import jQuery to make my insert in the same page
without causing conflicts, or can I use one on the query already used
for the same purpose?
How do I display a server response through the validationEngine?
My code is the following one.
$(".btn_newsletter").live('click', function() {
$.ajax(
{
url: "php/functions/signin.php"+nomfichier,
success: function(data) {
if (data.check==0) {alert('Error : Sorry '); return false;}
if (data.check==1) {alert('yep!!!');
}
},
cache: false,
type: "POST",
dataType: 'json'
});
}
This is my PHP code.
$ip= $_SERVER["REMOTE_ADDR"];
$select = "select * from av_newsletter where email='".$_POST['email']."'";
$exist = $_BASE->query_array($select);
if ($exist) {
$check = "0";
}
else {
$ajout="INSERT INTO av_newsletter(id,sub_date,email,ip) VALUES (NULL,now(),'$email','$ip')";
$add=$_BASE->query($ajout);
if ($add) {
$check="1";
}
}
$return_arr["check"] = $check;
echo json_encode($return_arr);
It doesn't work; I've no alert, but also no errors.
If you are not tied in too deeply to your 'Validationengine' I would recommend using this one, is has served me well for years, it has support for making remote checks so you could do something like this:
$(document).ready(function(){
var save_options = {
success: userSaved, //callback function
url: '/users/save',
response: 'json',
method: 'post'
};
var validationObj = {
rules: {
name: "required",
email: {
email: true,
required: true,
remote: "/user/check_email/"
}
},
messages: {
name: "Please name yourself",
email: {
required: "Please enter your email address",
email: "Invalid email address",
remote: "Email already in use."
}
},
errorPlacement:function(error, element) {
error.appendTo( element.next() );
},
submitHandler: function(form) {
$(form).ajaxSubmit(save_options);
},
success:function(label) {
label.html(" ").addClass("checked");
}
};
});
And then on the PHP side at the '/users/check_email' endpoint the PHP does the following:
echo $emailExists ? json_encode(false) : json_encode(true);
Ok, before we spam the comments and get to far off topic, please execute this code which should get you started in getting it to work eventually.
$(".btn_newsletter").live('click',function() {
alert('clicked'); // click is executed
$.ajax({
url: "php/functions/signin.php"+nomfichier,
success: function(data) {
alert(data); // should alert the data
if(data.check==0){ alert('Error : Sorry '); return false; }
if(data.check==1){ alert('yep!!!'); }
},
error: function(request, status, error) {
alert('failed '+status);
},
cache: false,
type: "POST",
dataType: 'json'
});
});
it works :)
$(".btn_newsletter").live('click',function() {
var data ="email="+$('#email').val();
$.ajax({
url: "php/functions/signin.php"+"?"+data,
success: function(data) {
if(data.check=='1'){ alert('yep!!!'); }
if(data.check=='0'){ alert('Error : Sorry '); return false; }
},
cache: false,
type: "POST",
dataType: 'json'
});
});
and in my signin.php I catch the value of the input like this $email=$_REQUEST['email']
Thanks a lot! time for me to see about validation engine how to link this with :)

Categories