Jquery Ajax PHP - How to determine if the PHP code executed successfully? - php

So this is my idea, I have a login jquery dialog on my homepage that blocks anyone from using the webpage (behind the login form dialog). I use ajax to submit the information entered to a php page which then checks if the username/password combo exists in the database. If it does, I return true and then close the dialog box (allowing access to the site).
How do I use ajax to check if my php script (from the executed page) returns true or false?
I was assuming the success/error options of the ajax function were checking this, but the below code doesnt seem to work.
$('.login').dialog({
closeOnEscape: false,
title: false,
modal: true,
width: 'auto',
show: {effect: "fade", duration: 1500},
title: 'Login',
buttons: {
"Login": function() {
$.ajax({
async: false,
type: 'POST',
url: 'sql/login.php',
success: function(){
alert( "Success!");
},
error: function(){
alert( "Failed!" );
},
dataType: "html"
});
}
}
});
$(".login").dialog().parents(".ui-dialog").find(".ui-dialog-titlebar").remove();

What I did was to put an echo at the end of my php with the variabel that is put in true or false, the I did this function inside the success option it is like this:
success: function(response){
if(response){
alert( "Success!");
}else{
alert( "Failed!" );
}
}
This worked for me, and you can put this in the php
if($myvar){
$anothervar=1;
}else{
$anothervar=0;
}
echo $anothervar;
so you can do this:
success: function(response){
if(response==1){
alert( "Success!");
}else{
alert( "Failed!" );
}
}
this is the way that I do it and it works fine
Hope it is useful

No. The success and error options relate to the success or failure of the XHR request. You need your php script to output something and check that. For example if your php script outputs "ok" (i.e. echo("ok");) if the verification is successful, you would use an ajax request such as this one
$.ajax({
url: 'sql/login.php',
success: function(data) {
if(data=="ok") {
alert('Login successfull.');
} else {
alert('Login failed.');
}
}
});

In your login.php:
if($_POST['data']){
$curData = $_GET['country'];
$query = "SELECT * FROM yourTable
WHERE tblData = '$curData'";
$result = mysql_query($query) or die;
if($result>0)
echo "<p class='checkExistance'>Data Exists</p>";
else
echo "<p class='checkExistance'>Data doesnt Exist</p>";
}
In your javascript:
function isSuccess(){
if($('.checkExistance').text() === "Data Exists"){
success($('.checkExistance').text()); //alert success!
}else{
success($('.checkExistance').text());
}
}
Did not really check if that works, but you pretty much get the idea. On AJAX call, do this:
$.ajax({
//
..
success:isSuccess
});
or
success:function(){
if($('.checkExistance').text() === "Data Exists"){
success($('.checkExistance').text()); //alert success!
}else{
success($('.checkExistance').text());
}
}
Make sure you implement alert() within the success() function..Hope that helps.

According to your information I assumed that your php page will do a validation and you make them return true or false within the php script
There are 2 problems in your code
1.your php page will return true or false within itself,in the other hand they won't send the result to ajax result unless you send them out like Tomm's said above
2.success() and error() of $.ajax are determined by the success of request NOT BY RESULT which mean that even if your php echo "false" it will trigger success() event because THE REQUEST IS SUCCESSFULLY SENT.

Related

Returning php variable from jQuery ajax call

Im sure this is a simple solution, however I have had no success in my attempts as my jQuery & ajax is not the greatest. I am making an ajax call to my php script which is doing error checking for a form. If there are errors, I am showing a hidden div and displaying the error messages no problem. However if there are no error messages, I would like an alert to appear. The issue is the alert does not display when there are no errors
Javacript
$.ajax({
url: '../assets/inc/process.php',
type: 'post',
data: formData,
dataType: 'html'
})
.always(function(data){
if (data == 'success'){
alert('it worked!');
}
else{
$('#responsediv').show();
$('#responsediv').html(data);
}
});
});
I have also tried
if (data.success == 'success'){
alert('it worked!');
}
else{
$('#responsediv').show();
$('#responsediv').html(data);
}
PHP
if ($result_new_row){
$success = 'success';
echo $success;
}
I know for sure that the new row is being inserted as I can see it in the database.
Any help is appreciated. Thanks!
Pass the data back from PHP as an array (PS data type should be json)
PHP
if ($result_new_row){
$return['result'] = 'success';
//comment this out when you are positive it's working
echo "hello";
} else {
$return['result'] = 'error';
}
print(json_encode( $return);
jQuery
$.ajax({
url: '../assets/inc/process.php',
type: 'post',
data: formData,
dataType: 'json'
})
.always(function(data){
if (data.result == 'success'){
alert('it worked!');
} else {
$('#responsediv').show();
$('#responsediv').html(data);
}
});
});
If this isn't returning correctly make sure your PHP function is actually working right first.
If you use Chrome you can see your AJAX calls by bringing up the inspector and changing to the network tab, then clicking XHR will show you each AJAX request, what is being sent and the response.

AJAX call not returning values from PHP

I am making an AJAX call but its not returning a value in the success handler. This is my AJAX call. I have checked that it's hitting the PHP file correctly
var msj;
$.ajax({
type: "POST",
url: "ajaxFile.php",
data: {
name: name,
status: status,
description: description,
action: 1
},
sucess: function(data){
msj = data;
alert(data);
}
});
alert(msj);
My PHP code is as follow:
if (isset($_POST['action']))
{
if ($_POST['action'] == 1)
{
$obj = new project($_POST['name'], $_POST['active'], $_POST['description']);
$obj = testInput($obj);
$check = validateName($obj->getName());
if ($check == 1)
{
echo $nameError;
}
else
{
print "asdasdasd";
}
}
}
Please help me tracking the mistake.
As far as I can see there's a syntax error in your code. There's sucess instead of success.
You are only providing a "success" callback function. You should also provide an "error" callback so you can debug and see what is wrong. You can also provide a "complete" callback that will be used in both alternatives.
var msj;
$.ajax({
type:"POST",
url:"ajaxFile.php",
data:{name:name,status:status,description:description,action:1},
complete:function(data){
msj=data;
alert(data);
}
});
alert(msj);
In your PHP, you could add
header('Content-Type: application/json');
to make sure JQuery identify well your web service.

$.ajax Success - If returns always false

I have a strange error within my $.ajax call here:
//CHECK USERNAME
$('#username').focusout(function() {
var id = $(this).attr('id');
var username = ($(this).val());
$(this).removeClass('hint').removeClass('hint_validated');
if (!$(this).val() || !regexUser($(this).val())){
//INVALID
$('#'+id+'_hint').hide().addClass('hint').show().html(usernameInvalid);
}else{
//VALID -> CHECK USERNAME FROM DB IF CONFIG = TRUE
if (checkUsername == true){
//LOADING FROM DB
$('#'+id+'_hint').hide().addClass('hint_check').show().html(usernameCheck);
$.ajax({
cache: false,
type: 'POST',
url: 'classes/ajax_check.php', //all that does currently is echo "USERNAMEVALID"
data: {username: username},
success: function(response){
if (response == "USERNAMEVALID") {
$('#'+id+'_hint').hide().removeClass('hint_check').addClass('hint_validated').show().html(usernameValid);
}else{
alert("ERROR");
};
},
error: function(){
$('#'+id+'_hint').hide().removeClass('hint_check').addClass('hint').show().html(usernameError);
}
});
}else{
$('#'+id+'_hint').hide().addClass('hint_validated').show().html(usernameValid);
}
}
});
The success function is called but the IF clause throws always FALSE. Why?
If the success function is only alert (response); it actually alerts USERNAMEVALID
I've worked with these functions before but I can't find the error here... Thanks for reading, any help is apreciated.
cheer
PrimuS
Check for empty lines. There is a difference between seeing:
alert("Hi\n");
alert("Hi");
You see the same, but it is not. Try this:
alert(encodeURI("Hi\n"));
alert(encodeURI("Hi"));
Where, it alerts this way:
Hi%0A
Hi
PS: If you are using a good browser other than IE, please use console.log() instead of alert(). So that you can check what is printing and what not!
Fiddle: http://jsfiddle.net/XaT6S/

Identifying what is returned when submitting a form using jquery

Is it possible to identify what a page returns when using jquery? I'm submitting a form here using jquery like this:
$("#sform").submit(function() {
$.ajax({
type: "POST",
data: $(this).serialize(),
cache: false,
url: "user_verify.php",
success: function(data) {
$("#form_msg").html(data);
}
});
return false;
});
​
The user_verify.php page does its usual verification work, and returns error messages or on success adds a user to the db. If its errors its a bunch of error messages or on success its usually "You have successfully signed up". Can I somehow identify using jquery if its errors messages its returning or the success message. So that way if its errors I can use that data in the form, or if its success, I could close the form and display a success message.
Yes, it's this:
success: function(data) {
$("#form_msg").html(data);
}
You can manipulate data in any way you want. You can return a JSON (use dataType) encoded string from server side and process data in the success function
success: function(data) {
if(data->success == 'ok'){
// hide the form, show another hidden div.
}
}
so user_verify.php should print for example:
// .... queries
$dataReturn = array();
$dataReturn['success'] = 'ok';
$dataReturn['additional'] = 'test';
echo json_encode($dataReturn);
die; // to prevent any other prints.
You can make you php return 0 if error so you do something like this inside
success: function(data) {
if(data==0){
//do error procedure
}else{
//do success procedure
}
}
Hope this helps
You can do and something like this:
$.ajax({
type:"POST", //php method
url:'process.php',//where to send data...
cache:'false',//IE FIX
data: data, //what will data contain
//check is data sent successfuly to process.php
//success:function(response){
//alert(response)
//}
success: function(){ //on success do something...
$('.success').delay(2000).fadeIn(1000);
//alert('THX for your mail!');
} //end sucess
}).error(function(){ //if sucess FAILS!! put .error After $.ajax. EXAMPLE :$.ajax({}).error(function(){};
alert('An error occured!!');
$('.thx').hide();
});
//return false prevent Redirection
return false;
});
You can checke the "data" parameter in "success" callback function.
I noticed that there is a problem in your code. Look at this line :
data: $(this).serialize(),
Inside $.ajax jquery method, "this" is bind to the global window object and not $('#sform')

jQuery, AJAX - How to tell if script returned false

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

Categories