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.
Related
I'am trying to get the results from the PHP page to the AJAX so that the AJAX knows if it's successful or not.
I'am very new to AJAX so not sure if am correct or not.
MY AJAX is as follows:
if ($("#register_form").valid()) {
var data1 = $('#register_form').serialize();
$.ajax({
type: "POST",
url: "register.php",
data: data1,captcha: grecaptcha.getResponse(),
success: function(msg) {
console.log(msg);
//check if response is true
if (msg == true) {
$('.messagebox').hide();
$('#alert-message').html(msg);
$('.messagebox').slideDown('slow');
$("#btn").text('Please Wait...'); // a
top.location.href = "index.php?msg=login"; //redirection
alert('SUCCESS');
} else {
$('messagebox').fadeIn(1000, function(){
$("#alert-message").html(msg).show();
alert('FAILED');
});
}
}
});
Register.php is as follows:
if (isset($_POST['g-recaptcha-response'])) {
$secret = '';
//get verify response data
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success == true) {
//Success: do code to store your data...
$result = true;
} else {
die($msg_recaptcha);
}
return $result;
}
If its success then it has to redirect to index.php?msg=login or else it has to show the error message. Can someone pls help me on this.
Do try to send the data in the curly braces because due to , the code might consider the success as a part of data.
data: {data :data1,captcha: grecaptcha.getResponse()},
And on the PHP page you should get the name of the posted data by which you have attached your data as
if (isset($_POST['captcha'])) {
$secret = '';
//get verify response data
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success == true) {
//Success: do code to store your data...
$result = true;
} else {
die($msg_recaptcha);
}
return $result;
}
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");
}
});
}
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);
Am I doing something wrong with the following code? I can't seem to get alert("success") to process when the Ci session expires. Below is my jquery and Ci code:
setInterval(function() {
jQuery.getJSON("<?=base_url()?>index.php/regUserDash/sessionExpire", function(data) {
var sessionState = jQuery.parseJSON('{"sessionExpired":"true","sessionExpired":"false"}');
if(sessionState.sessionExpired === "true") { // if session is expired run the following code
var dataString = 'true';
jQuery.ajax({ // send the expired signal to Ci so that it knows the session has expired
type: 'POST',
dataType: 'JSON',
url: '<?=base_url()?>index.php/regUserDash/extendSession',
data: {'dataString': true},
success: function(data) {
if (data.extendedSession == true) {
alert('success');
} else {
return false;
}
}
});
} else if(sessionState.sessionExpired == "false") {
return;
}
});
}, 120000); // loop through every 2 minutes
CodeIgniter Code:
public function sessionExpire() {
if ($this->session->userdata("logged") == "1") {
echo json_encode(array("sessionExpired" => false));
} elseif($this->session->userdata("logged") == "0") {
echo json_encode(array("sessionExpire" => true));
}
} public function extendSession() {
// set loggedIn session var
$this->session->set_userdata('logged', '1');
// return json to ajax call
echo json_encode(array("extendedSession" => true));
}
jQuery.parseJSON('{"sessionExpired":"true","sessionExpired":"false"}'); return first sessionExpired = true and second sessionExpired = false, which overwrite the first.
So, here is one way to do this (need test):
setInterval(function() {
jQuery.getJSON("<?=base_url()?>index.php/regUserDash/sessionExpire", function(data) {
if(data.sessionExpired == "true") { // if session is expired run the following code
// var dataString = 'true'; // Remove this
jQuery.ajax({ // send the expired signal to Ci so that it knows the session has expired
type: 'POST',
dataType: 'JSON',
url: '<?=base_url()?>index.php/regUserDash/extendSession',
data: {'dataString': true},
success: function(data) {
//if (data.extendedSession == true) {
alert('success');
//} else {
// return false;
//}
// Remove commented code, because extendSession() always return true
}
});
} else {
return 'Session not expired!';
}
});
}, 120000); // loop through every 2 minutes
And CI functions:
public function sessionExpire()
{
if ($this->session->userdata("logged") == "1") {
echo json_encode(array("sessionExpired" => false));
} elseif ($this->session->userdata("logged") == "0") {
echo json_encode(array("sessionExpired" => true));
}
}
public function extendSession()
{
// set loggedIn session var
$this->session->set_userdata('logged', '1');
// return json to ajax call
echo json_encode(array("extendedSession" => true));
}
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