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

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

Related

Set hidden input fields and submit data on same button click [duplicate]

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.

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

Checking if user exists jquery validator,ajax and codeigneter

I m trying to check if a username exists or not but even if the username doesn't exists it keeps saying "Username already exists" this is my javascript code:
$.validator.addMethod("checkUsername",
function(value, element) {
var test = "";
$.ajax({
type:"GET",
url: site_url + "/ajax/checkusername/" + value,
success: function(result){
if(result=="exists")
return false;
else
return true;
}
});
},
"Username Already Exists."
);
$("#myform").validate({
rules: {
username2: {
required: true,
minlength: 6,
checkUsername:true
},
password2: {
required: true,
minlength: 6
},
email: {
required: true,
email: true
}
}
});
});
This is my controller code:
public function checkusername($username)
{
$this->load->model('user_model');
$user = $this->user_model->getUser($username);
if($user == null)
{
echo json_encode("notexists");
}
else
{
echo json_encode("exists");
}
}
Any Ideas about this how this can be solved?
Thanks in advance.
Why are you encoding the response as JSON when you're not parsing JSON with your ajax?
What happens when you simply do this?:
public function checkusername($username)
{
$this->load->model('user_model');
$user = $this->user_model->getUser($username);
if($user == null)
{
echo "notexists";
}
else
{
echo "exists";
}
}
EDIT:
$.validator.addMethod("checkUsername",
function(value, element) {
var result = false;
$.ajax({
type:"GET",
async: false,
url: site_url + "/ajax/checkusername/" + value,
success: function(msg) {
result = (msg == "exists") ? false : true;
}
});
return result;
},
"Username Already Exists."
);
$.ajax read a string. Cause you do echo json_encode this string is json.
You can use $.getJSON in stead of $.ajax
$.getJSON( site_url + "/ajax/checkusername/" + value, function( json ) {
if(json=="notexists"){alert('Not exists')}
});
or add $.parseJSON to your original code:
if($.parseJSON(result)=="exists")
update: i had to change my answer
your function doesn't return the result of your $.ajax. $.ajax had to set your return value. Cause can't return before your ajax has been finished, you also have to add async: false to your request (see: How do I make jQuery wait for an Ajax call to finish before it returns?)
$.validator.addMethod("checkUsername",
function(value, element) {
var test = false;
$.ajax({
type:"GET",
async: false,
url: site_url + "/ajax/checkusername/" + value,
success: function(result){
if(result=="notexists") {test = true; }
}
});
return test;
},
"Username Already Exists."
);

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.

jQuery and Ci not properly processing a logout feature

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

Categories