My success/error handling is not working as expected. In this example my php runs as intended, however, the intent of the processing failed. Let's say I was looking up a username in the database... if I found the username I would return $ajax_result['success'] = 'success';, but if I did not find the username I would return nothing. The success call works fine, but the error call is not firing.
The error in firebug I am getting is TypeError: response is null and therefore the error alert I have set does not fire.
What is the best way to solve this without actually returning $ajax_result['success'] = 'whatever';
example return from php would be something like this when processing went as expected:
$ajax_result['success'] = 'success'; // add success info
echo json_encode($ajax_result); // return result array to ajax
for 'errors' I am simply returning :
echo json_encode($ajax_result); // which is null in this case
the ajax:
var showInfo = function() {
$('#show-user').on('click', function () {
var $form = $(this).closest('form');
$.ajax({
type: 'post',
url: '/spc_admin/process/p_delete_user_show.php',
data: $form.serialize(),
dataType : 'json'
}).done(function (response) {
if (response.success == 'success') {
alert('success');
}
else
{
alert('error');
}
});
});
}
You can not json_encode a null value, easiest and cleanest way to make this work would probably be to make success a bool and set it to either true or false depending on if it succeeded or not (This is ususaly what most user expects a 'success' or 'result' parameter in response to be, not a string).
//PHP:
header('Content-Type: application/json'); // To let the client know that its json-data.
$ajax_result['success'] = $wasSuccessfull; // true or false
die(json_encode($ajax_result)); // Exit the script with the json response.
//JavaScript:
if (response.success) {
alert('success');
} else {
alert('error');
}
try this one:
if (!response.success) {
alert('error');
}
else
{
alert('success');
}
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 have this php that returns an array if an error is triggered, else, it returns a <DIV>
if(!empty($error)) {
$true = true;
$res = array('info' => '$error', 'error' => '$true');
echo json_encode($res);
die();
} else {
// no error
echo "<div> no error </div>";
}
I think my problem lies in the dataType:json parameter because it expects JSON_ENCODED format? I just want to append the <DIV> (non json_encoded) if the else condition is met.
$.ajax
({
type : 'POST',
url : 'submitForm.php',
data : formData,
dataType : 'json',
success : function(data) {
if(data.error == true) {
console.log(data.info); //display error
} else {
console.log(data);
//some jquery to append the <div>
}
}
})
Checking the headers appears to be okay, and the preview tab, returns the <DIV> data
Request Method:POST
Status Code:200 OK
But its not appending, Nor the <DIV> being shown in console.log.
Is there a way i could disable the dataType if a certain PHP condition is met? OR, a proper way of handling json_encoded along side with non json_encoded format in the same PHP file?
just return your html using json too
PHP
if(!empty($error)) {
$true = true;
$res = array('info' => $error, 'error' => $true);
} else {
// no error
$res = array('html'=>"<div> no error </div>");
}
echo json_encode($res);
HTML
$.ajax
({
type : 'POST',
url : 'submitForm.php',
data : formData,
dataType : 'json',
success : function(data) {
if(data.error == true) {
console.log(data.info); //display error
} else {
console.log(data);
$('div').append(data.html);
}
}
})
Using json for errors and html (or pseudo html) for regular responses struggles a bit to me.
That being said, if you really want to do that, you obviously can't use dataType: 'json' option because this instructs $.ajax() to expect (and parse) json data so, if what is received is not a valid json string, then an exception will be thrown.
But anyway you can emulate it by parsing json data yourself. For example:
dataType: "text",
success: function(data) {
try {
data = JSON.parse(data);
if (! data.error) { // What if you send json witout error flag?
data.error = true;
data.info = "Received json without error info."
};
} catch (e) {
data = {
contents: data,
};
};
if (data.error) {
console.log(data.info);
} else {
console.log(data.contents);
// Or whatever you want to do wit received STRING
},
I have a simple Javascript funcion:
function checkParams()
{
$.ajax(
{
url: 'login.php',
type: "GET",
contentType: false,
cache: false,
processData: false,
async: true,
data:
{
user: $("#user").val(),
pass: $("#pass").val()
},
success: function(data)
{
$("#mydiv").load("loader.php");
},
error: function()
{
$("#mydiv").load("index.php");
}
});
}
And A simple PHP function which checks for the right user & pass string and I should return an error condition if something fails..
I found examples where it's suggested to do something like:
function foo()
{
/* code ... */
/*error condition */
echo "error";
}
But honestly, it's not working..
How can I tell to ajax, from PHP, that I want ro return an 'error condition' ?
The jQuery.ajax() error handler only fires when the HTTP status result indicates an error; that is, the page returns a 4xx or 5xx status code.
You can do one of the two following options:
1) Set the status code with header('HTTP/1.0 400 Bad Request') (or any other relevant HTTP status code) before you echo "error".
2) Rather than using an error status, have both your success and failure conditions emit an array, converted to JSON withjson_encode(), that is then decoded in your javascript and processed into a success or failure as appropriate in your success function.
In this bit of code change to RETURN SOMETHING
success: function(data)
{
return true;
},
error: function()
{
return false;
}
basically
$result = your ajax return;
if ($result)
{
header('Content-Type: application/json');
}
else
{
header('HTTP/1.1 500 Internal Server Yourserver');
header('Content-Type: application/json; charset=UTF-8');
die(json_encode(array('message' => 'ERROR', 'code' => 'whatever you want to call it')));
}
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)));
I'm using jQuery and AJAX to validate my form when someone creates a new user on my website. I'm programming in OOP PHP, together with the jQuery and AJAX.
I'm using this code:
$.ajax({
type: "POST",
url: "includes/classes/handler.php?do=addLogin",
data: dataString,
success: function() {
$('.sideBarNewUserWrap').fadeOut();
}
});
return false;
But how do I return an error message, if the e-mail already exists?
Hope it's info enough, else I'll just add some more.
Thanks in forward :)
* UPDATE *
This is my PHP checking if email exists:
$email_count = mysql_num_rows($check_email);
if($email_count){
return false;
}
* UPDATE *
success: function(data){
if(data.error){
$('.sideBarNewUserWrap').fadeOut();
} else {
$('.sideBarNewUserError-email').fadeIn();
}
Now this looks pretty much as a failure because.
if(data.error) then it's okay?
Shouldn't it be something like:
if(date.error){
//Error message
}
And not the other way around?
Well, If I try to enter an email which already exists, it tells me as it should, but why does this work? In my eyes I'm doing something wrong here?
php:
$result = array('error' => true); // or $result = array('error' => false);
echo json_encode($result);
js:
success: function(response) {
if (response.error) {
// ...
}
}
You can get the response in the function:
$.ajax({
type: "POST",
url: "includes/classes/handler.php?do=addLogin",
data: dataString,
success: function(response) {
if (response == "ok")
{
$('.sideBarNewUserWrap').fadeOut();
}
else
{
// error happend
}
}
});
return false;
You can return string, int in PHP or even XML, JSON, whatever you want to validate on client side
You can return data by using an echo in your handler.php file.
To receive this in jQuery just place a parameter in the success function of the Ajax function.
success: function(returnedValue)
{
// Here you check if returned value e.g. "returnedValue == 1"
}
basically in the handler.php you should verify whether email already exists or not and then send to the client (at least) two different responses (eg. 0: email exists, 1:ok).
In the success callback you can read the response data so you can tell the user the operation status