jquery ajax dont work without firebug break point - php

I am using following method to call the php:
function validateEmaiAjax(email){
val = null;
$("#warning").load("https://localhost/Continental%20Tourism/register_ajax.php",{email: email}, function(rspns, stat, xml){
val = rspns;
});
if(val == ".")
return true;
else {
return false;
}
}
my php code is:
<?php
$dbc = mysqli_connect("localhost","root","pass","continental_tourism") OR die(mysqli_connect_error());
$email = $_REQUEST['email'];
$query = "SELECT email FROM customer_info WHERE email = '$email' ";
$r = mysqli_query($dbc, $query) OR die(mysqli_error($dbc));
if(mysqli_num_rows($r) > 0)
echo "Email address exists!";
else
echo ".";
?>
Basically this do check the database and if email exists shows "Email address exists!" if not I want to return true(so I echo "." and compare it). The weird thing is if i put a break point using firebug near if(val == ".") program works correctly and returns true. If I remove that break point function always return false. I cant understand why this happens. Please help! Thanks.

The reason you have this problem is because you have performed an asynchronous request. This means that the if(rspns == ".") will be reached before the response has been received from the server, and the result will always be false.
In order to wrap this code in a function the returns a boolean and does not require a callback function (a blocking procedure) you will need to use a synchronous request:
function validateEmaiAjax(email) {
// This is the correct way to initialise a variable with no value in a function
var val;
// Make a synchronous HTTP request
$.ajax({
url: "https://localhost/Continental%20Tourism/register_ajax.php",
async: false,
data: {
email: email
},
success: function(response) {
// Update the DOM and send response data back to parent function
$("#warning").html(response);
val = response;
}
});
// Now this will work
if(val == ".") {
return true;
} else {
$("#warning").show();
return false;
}
}

If you want to make that code work you should use the $.ajax method instead of load and set async to false to make it wait for the response.
http://api.jquery.com/jQuery.ajax/
$.ajax({
url:"https://localhost/Continental%20Tourism/register_ajax.php",
async: false,
data: {email: email},
success: function(rspns, stat, xml){
val = rspns;
}
});

Why this
else {
return false;
$("#warning").show();
}
$("#warning").show(); will never be executed.
EDIT : There ya go :
function validateEmaiAjax(email){
var URL = 'https://localhost/Continental%20Tourism/register_ajax.php';
var Args = {email: email}
$('#warning').load(URL, Args, function(html){
if(html == '.'){
return true;
} else {
$('#warning').show();
return false;
}
});
return false;
}
Or you can try this also :
function validateEmaiAjax(email){
var URL = 'https://localhost/Continental%20Tourism/register_ajax.php';
var Args = {email: email}
$.ajax({
url: URL,
type: 'GET'
data: Args,
success: function(html){
if(html == '.'){
return true;
} else {
$('#warning').show();
return false;
}
}
});
return false;
}

This is because your function keeps running and hits the if(val == ".") before it's gotten the ajax response back. You need to but that whole if statement inside the ajax callback function.
function validateEmaiAjax(email){
var success;
$("#warning").load("https://localhost/Continental%20Tourism/register_ajax.php",{email: email}, function(rspns, stat, xml){
if(rspns == ".")
success = true;
else {
$("#warning").show();
success = false;
}
});
return success;
}
Also swapped the warning show and return so it would execute

Related

How to get true or false from PHP function using AJAX?

I tested status.php return value with var_dump($result) and alerted it out in check() function like this:
function check() {
$.ajax({
url: "status.php"
}).done(function(data) {
alert(data);
});
}
and it did return true or false depending on situation, but when I check if data is true or false inside of check() function it always returns false.
status.php:
<?php
function status(){
if(logged() === true) {
$result = true;
} else {
$result = false;
}
return $result;
}
status();
?>
check() function: always alerts "false" even though sometimes should be "true"
function check() {
$.ajax({
url: "status.php"
}).done(function(data) {
if(data === true){
alert("true");
} else {
alert("false");
}
});
}
You're not sending the return value of the status() function back to PHP. Use:
echo json_encode(status());
And change the AJAX call to expect a JSON response.
function check() {
$.ajax({
url: "status.php",
dataType: 'json'
}).done(function(data) {
alert(data);
});
}
you just echo the $result like this
ajax not returning value so that we have to echo it.
<?php function status(){
if(logged() === true) {
$result = true;
} else {
$result = false;
}
echo $result; } status(); ?>
and then should be like this
function check() {
$.ajax({
url: "status.php"
}).done(function(data) {
if(data == "true"){
alert("true");
} else {
alert("false");
}
}); }
Use
**dataType: 'json'**
function check() {
$.ajax({
url: "status.php",
dataType: 'json'
}).done(function(data) {
alert(data);
});
}
and on status.php use
echo json_encode(status());
You cannot get the response by return method in ajax. to get value "echo" whatever the result in the function , like
function status(){
if(logged() === true) {
$result = "1";
} else {
$result = "0";
}
echo $result;exit;
}
you will get the value 1 or 0 in your ajax success function
Ajax may not be returning a boolean true or false, rather a string.
So try and put true in double quotes:
if(data=="true")
You can also use the trim function on data to ensure no whitespace is present in the returned data, like so:
if($.trim(data)=="true")
Just Remove Type checking i.e '===' replace with '=='
function check() {
$.ajax({
url: "status.php"
}).done(function(data) {
if(data == true){
alert("true");
} else {
alert("false");
}
});
}

how do you pass booleans from PHP controller to Ajax request?

I used this system.. sendind a json with success = 0 or 1 depending on success or error, is this correct or there is a better more correct method to pass true or false to the ajax call?
if (empty($item)) {
// add to the DB
$return['success'] = 0;
return Response()->json($return);
} else {
$return['success'] = 0;
$return['message'] = "Already in Collection";
return Response()->json($return);
}
then in Ajax:
jQuery(function ($) {
$(document).ready(function () {
$("body").on("submit", ".dynamic-form", function (e) {
var form = $(this);
var span = $(form).find('input[name="span_id"]').val();
$.ajax({
url: form.prop('action'),
type: 'post',
dataType: 'json',
data: $(this).serialize(),
success: function (data) {
if (data.success == 1) {
alert("success");
}
else if (data.success == 0) {
alert("error");
}
}
});
e.preventDefault();
});
});
});
I use true or false and then compare like that if (data.success).
If you want a boolean send a boolean, but it's just my opinion.
This depends only on you, you can save your success as you do or to status...
<?php
if (empty($item)) {
// add to the DB
$return['success'] = true;
} else {
$return['success'] = false;
$return['message'] = "Already in Collection";
}
return Response()->json($return);

Using AJAX to call a PHP script

I am using AJAX to call a PHP script. I am using conditions to echo the proper error message in my PHP. When I do this, my AJAX and JQUERY do not work properly.
My JQUERY/AJAX:
if (email != 0) {
// Run AJAX email validation and check to see if the email is already taken
$.ajax({
type: "POST",
url: "checkemail.php",
data: dataString,
async: false,
success: function(data) {
var error= false;
if (data == 'invalid') {
var invalid= 1;
}
else if (data == 'taken') {
var taken= 1;
}
if (invalid == 1) {
alert('invalid email');
e.preventDefault();
}
if (taken == 1) {
alert('email taken');
e.preventDefault();
}
}
});
}
My PHP:
<?php
$email = true
if ($email == true) {
echo "taken";
}
?>
But, when I just put:
echo "taken";
The AJAX and JQUERY works exactly how it should and the respective error message pops up. "taken" is being echo'd either way, so I don't get what is going on. What could I be doing wrong?
You're missing your semicolon.
$email = true
needs to be
$email = true;
In your response, you will probably be getting a PHP error - unless your error messages are suppressed.

How can I get a PHP variable to AJAX?

I don't think I am passing the variable the right way between my separate PHP and AJAX files.
I am debugging this by triggering the second condition $status = 'info'; in my PHP file.
Currently, status is coming up as "undefined" for alert(data.status);
signup_process.php
if (condition){
$status = 'success';
else {
$status = 'info';
}
AJAX
function send() {
var data = $('#signup_form').serialize();
$.ajax({
type: "POST",
url: "signup_process.php",
data: data,
success: function (data) {
alert(data.status);
if (data.status == 'success') {
// everything went alright, submit
$('#signup_form').submit();
} else if (data.status == 'info')
{
console.log(data.status);
$("label#email_error").show();
return false;
}
}
});
return false;
};
I know that the 2nd condition is being triggered because I put a header redirect there just for testing and it worked fine.
Good to use json while return back data from php to ajax.
$return_data = array();
if (condition){
$return_data['status'] = 'success';
} else {
$return_data['status'] = 'info';
}
echo json_encode($return_data);
exit();
Now, if you are return back json data to ajax, then you need to specify return data type into ajax call as below
function send() {
var data = $('#signup_form').serialize();
$.ajax({
type: "POST",
url: "signup_process.php",
data: data,
dataType: 'json',
success: function (data) {
alert(data.status);
if (data.status == 'success') {
// everything went alright, submit
$('#signup_form').submit();
} else if (data.status == 'info')
{
console.log(data.status);
$("label#email_error").show();
return false;
}
}
});
return false;
};
You should send a JSON object back from php:
$data = array();
if (condition){
$data['status'] = 'success';
else {
$data['status'] = 'info';
}
header('Content-type: application/json');
echo json_encode($data);
The json_encode() method converts the array to a JSON object so you can access each array key by name on the js side.

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

Categories