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");
}
});
}
Related
I check two values with ajax. And if both are correct then i want to make a submit (post-back).
But the post-back doesn't work.
Here is the code:
$('form').submit(function () {
var correctCaptcha = false;
var correctWebcode = false;
$.ajax({
url: '/Competition/CheckForm',
type: "POST",
data: $(this).serialize(),
success: function (data) {
if (data == true) {
$('#recaptcha_response_field').removeClass("captchaError");
correctCaptcha = true;
}
else {
Recaptcha.reload();
$('#recaptcha_response_field').addClass("captchaError");
}
}
});
$.ajax({
// like the code above (for webcode)
});
if (correctCaptcha == true && correctWebcode == true) {
document.forms['form'].submit();
}
else { return false; }
});
Use Async:false
$.ajax({
url: '/Competition/CheckForm',
type: "POST",
async:false,
data: $(this).serialize(),
success: function (data) {
if (data == true) {
$('#recaptcha_response_field').removeClass("captchaError");
correctCaptcha = true;
}
else {
Recaptcha.reload();
$('#recaptcha_response_field').addClass("captchaError");
}
}
});
This will cause the infinite loop:
if (correctCaptcha == true && correctWebcode == true) {
document.forms['form'].submit();
}
So use use like this here
if (correctCaptcha == true && correctWebcode == true) {
return true;
}
else {return false;}
Since ajax is async in nature you cannot expect those variables to be set right away when ajax call. You can either set async to false or submit the form inside success handler. Try this.
$('form').submit(function () {
$.ajax({
url: '/Competition/CheckForm',
type: "POST",
data: $(this).serialize(),
success: function (data) {
if (data == true) {
$('#recaptcha_response_field').removeClass("captchaError");
$('form')
.unbind('submit')//we dont need any handler to execute now
.submit();
}
else {
Recaptcha.reload();
$('#recaptcha_response_field').addClass("captchaError");
}
}
});
$.ajax({
// like the code above
});
return false;//To prevent the form from being submitted.
});
By default, $.ajax works asynchronously, your way won't submit the form, you should submit the form in the callback function.
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);
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.
JS:
$(function() {
load_custom_topics()
// load_main()
});
function load_custom_topics(){
$.ajax({
type: "POST",
async: false,
url: 'http://rickymason.net/thebump/index.php/ajax/load_custom_topics',
dataType: 'json',
data: { },
success: function(page){
alert(page);
}
});
event.preventDefault()
}
load_custom_topics
public function load_custom_topics()
{
$check = $this->page_model->check_active_topic();
if ($check == FALSE)
{
$page['content'] = 'TEST equals FALSE';
} else {
$page['content'] = 'TRUE';
}
echo json_encode($page);
}
going to the page index.php/ajax/load_custom_topics returns this:
{"content":"TEST equals FALSE"}
The alert is not firing! Any idea why?
Actually, on inspecting a request to your controller, I found that you weren't setting the proper headers the ajax call expects (text/json).
See codeigniter's Output class.
Using
$this->output->set_content_type('application/json')->set_output(json_encode($page));
instead of
echo json_encode($page);
should do the trick.
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));
}