Send a boolean value in jQuery ajax data - php

I'm sending some data in an Ajax call. One of the values is a boolean set to FALSE. It is always evaluated as TRUE in the PHP script called by the Ajax. Any ideas?
$.ajax({
type: "POST",
data: {photo_id: photo_id,
vote: 1,
undo_vote: false}, // This is the important boolean!
url: "../../build/ajaxes/vote.php",
success: function(data){
console.log(data);
}
});
In vote.php, the script that is called in the above Ajax, I check the boolean value:
if ($_POST['undo_vote'] == true) {
Photo::undo_vote($_POST['photo_id']);
} else {
Photo::vote($_POST['photo_id'], $_POST['vote']);
}
But the $_POST['undo_vote'] == true condition is ALWAYS met.

A post is just text, and text will evaluate as true in php. A quick fix would be to send a zero instead of false. You could also put quotes around your true in PHP.
if ($_POST['undo_vote'] == "true") {
Photo::undo_vote($_POST['photo_id']);
} else {
Photo::vote($_POST['photo_id'], $_POST['vote']);
}
Then you can pass in true/false text. If that's what you prefer.

You can use JSON.stringify() to send request data:
data : JSON.stringify(json)
and decode it on server:
$data = json_decode($_POST);

You can use 0 and 1 for undo_vote and type cast it in php:
JS side:
undo_vote: 0 // false
Server side:
$undovote = (bool) $_POST['undo_vote']; // now you have Boolean true / false
if($undovote) {
// True, do something
} else {
// False, do something else
}

Related

Trying to send bool via ajax [duplicate]

I'm sending some data in an Ajax call. One of the values is a boolean set to FALSE. It is always evaluated as TRUE in the PHP script called by the Ajax. Any ideas?
$.ajax({
type: "POST",
data: {photo_id: photo_id,
vote: 1,
undo_vote: false}, // This is the important boolean!
url: "../../build/ajaxes/vote.php",
success: function(data){
console.log(data);
}
});
In vote.php, the script that is called in the above Ajax, I check the boolean value:
if ($_POST['undo_vote'] == true) {
Photo::undo_vote($_POST['photo_id']);
} else {
Photo::vote($_POST['photo_id'], $_POST['vote']);
}
But the $_POST['undo_vote'] == true condition is ALWAYS met.
A post is just text, and text will evaluate as true in php. A quick fix would be to send a zero instead of false. You could also put quotes around your true in PHP.
if ($_POST['undo_vote'] == "true") {
Photo::undo_vote($_POST['photo_id']);
} else {
Photo::vote($_POST['photo_id'], $_POST['vote']);
}
Then you can pass in true/false text. If that's what you prefer.
You can use JSON.stringify() to send request data:
data : JSON.stringify(json)
and decode it on server:
$data = json_decode($_POST);
You can use 0 and 1 for undo_vote and type cast it in php:
JS side:
undo_vote: 0 // false
Server side:
$undovote = (bool) $_POST['undo_vote']; // now you have Boolean true / false
if($undovote) {
// True, do something
} else {
// False, do something else
}

Passing of javascript variable data to php variable in the same php file

I have a javascript that needs to pass data to a php variable. I already searched on how to implement this but I cant make it work properly. Here is what I've done:
Javascript:
$(document).ready(function() {
$(".filter").click(function() {
var val = $(this).attr('data-rel');
//check value
alert($(this).attr('data-rel'));
$.ajax({
type: "POST",
url: 'signage.php',
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
});
});
Then on my php tag:
<?php
if(isset($_GET['subDir']))
{
$subDir = $_GET['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
I always get the fail text so there must be something wrong. I just started on php and jquery, I dont know what is wrong. Please I need your help. By the way, they are on the same file which is signage.php .Thanks in advance!
When you answer to a POST call that way, you need three things - read the data from _POST, put it there properly, and answer in JSON.
$.ajax({
type: "POST",
url: 'signage.php',
data: {
subDir: val,
}
success: function(answer)
{
alert("server said: " + answer.data);
}
});
or also:
$.post(
'signage.php',
{
subDir: val
},
function(answer){
alert("server said: " + answer.data);
}
}
Then in the response:
<?php
if (array_key_exists('subDir', $_POST)) {
$subDir = $_POST['subDir'];
$answer = array(
'data' => "You said, '{$subDir}'",
);
header("Content-Type: application/json;charset=utf-8");
print json_encode($answer);
exit();
}
Note that in the response, you have to set the Content-Type and you must send valid JSON, which normally means you have to exit immediately after sending the JSON packet in order to be sure not to send anything else. Also, the response must come as soon as possible and must not contain anything else before (not even some invisible BOM character before the
Note also that using isset is risky, because you cannot send some values that are equivalent to unset (for example the boolean false, or an empty string). If you want to check that _POST actually contains a subDir key, then use explicitly array_key_exists (for the same reason in Javascript you will sometimes use hasOwnProperty).
Finally, since you use a single file, you must consider that when opening the file the first time, _POST will be empty, so you will start with "fail" displayed! You had already begun remediating this by using _POST:
_POST means that this is an AJAX call
_GET means that this is the normal opening of signage.php
So you would do something like:
<?php // NO HTML BEFORE THIS POINT. NO OUTPUT AT ALL, ACTUALLY,
// OR $.post() WILL FAIL.
if (!empty($_POST)) {
// AJAX call. Do whatever you want, but the script must not
// get out of this if() alive.
exit(); // Ensure it doesn't.
}
// Normal _GET opening of the page (i.e. we display HTML here).
A surer way to check is verifying the XHR status of the request with an ancillary function such as:
/**
* isXHR. Answers the question, "Was I called through AJAX?".
* #return boolean
*/
function isXHR() {
$key = 'HTTP_X_REQUESTED_WITH';
return array_key_exists($key, $_SERVER)
&& ('xmlhttprequest'
== strtolower($_SERVER[$key])
)
;
}
Now you would have:
if (isXHR()) {
// Now you can use both $.post() or $.get()
exit();
}
and actually you could offload your AJAX code into another file:
if (isXHR()) {
include('signage-ajax.php');
exit();
}
You are send data using POST method and getting is using GET
<?php
if(isset($_POST['subDir']))
{
$subDir = $_POST['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
You have used method POST in ajax so you must change to POST in php as well.
<?php
if(isset($_POST['subDir']))
{
$subDir = $_POST['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
Edit your javascript code change POST to GET in ajax type
$(document).ready(function() {
$(".filter").click(function() {
var val = $(this).attr('data-rel');
//check value
alert($(this).attr('data-rel'));
$.ajax({
type: "GET",
url: 'signage.php',
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
});
});
when you use $_GET you have to set you data value in your url, I mean
$.ajax({
type: "POST",
url: 'signage.php?subDir=' + val,
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
or change your server side code from $_GET to $_POST

Conditional if statement after AJAX post using response, is this ok?

A form i'm using with a single input uses AJAX to post to the server. I plan to take the input's value which is a string and check if the string already exists in the database. I'll us in_array() and if the string doesn't exist insert it to the database and echo 1 or else 0 if it's a duplicate, sending back 1 or 0 as a result.
In my AJAX i'm using this simple function on success, if the result returns 1 i'll use jQuery to display a success message, or else i'll display an error and exit. Is this a good method to validate server side and not have the form submit by returning 1 or 0 and exit(); for duplicates?
success: function(result)
{
if(result == 1)
{ string was inserted to db }
else
{
duplicate exists
exit();
}
Thanks
I would have personally made it so in the php, I return a json encoded identity array with some of the information about the response. I usually include more information than needed, for debugging purposes and possible future changes.
if($results >= 1){
$duplicate_exists = 'true';
}elseif($results < 1){
$duplicate_exists = 'false';
};
$result = array(
'exists' => $duplicate_exists ,
'status' => $status,
'time' => time()
// etc
);
echo json_encode($result)
Then to decode the json into an object in javascript:
success: function(result){
result = jQuery.parseJSON(result)
// you can also use eval(result) , but it's much slower.
if(result.exists == 'false'){
// string was inserted to db
}else{
// duplicate exists
exit();
}
You can use the below code using AJAX and JS to post and retrieve the result.
$.ajax({
url: 'https://api.github.com/gists',
type: 'POST',
dataType: 'json',
data: JSON.stringify(data)
})
.success( function(e) {
res = jQuery.parseJSON(e);
if(res.exists == 'false'){
// string was inserted to db
}
else if(res.exists == 'true'){
// duplicate exists
exit();
}
})
.error( function(e) {
//there was error
});

PHP json_encode for JQuery

I'm working on a method in my class that outputs error messages for both ajax and regular post request. The PHP part works fine, but the json part doesn't seem to. Here is my method:
public $formError = false;
public $phpErrors = '';
public $jsonErrors = array();
// ------------------------------------------------------------
// ERROR PROCESSING
// ------------------------------------------------------------
private function responseMessage($bool, $msg) {
$return['error'] = $bool;
$return['msg'] = $msg;
if (isset($_POST['plAjax']) && $_POST['plAjax'] == true) {
$this->jsonErrors[] = $return;
} else {
foreach ((array) $msg as $key => $value) {
$this->phpErrors .= $msg;
}
}
$this->formError = true;
}
I think, the problem is that no matter if it is just a single error message or multiple, the json object is always wrapped with square brackets. I couldn't find anything online that would show an example. The messages look like this:
SINGLE ERROR:
[{"error":true,"msg":"Error message 1 ..."}]
MULTIPLE ERRORS:
[{"error":true,"msg":"Error message 1 ..."},{"error":true,"msg":"Error message 2 ..."}]
Firebug shows 200 OK but my JQuery does not output any messages:
$.ajax({
type: 'POST',
url: plSubmitUrl,
data: plFormData,
dataType: 'json',
cache: false,
timeout: 10000,
success: function (data) {
if (data.error === true) {
// display error message
plResponse(data.msg, true);
...
} else if (data.error === false) {
// display success message
plResponse(data.msg, true);
...
}
},
When I was showing only one message at a time, the JQuery was working fine.
Any help would be great. Thanks
Dont use strict equality operator === since from PHP you are actually sending string, instad of:
if (data.error === true)
Use:
if (data.error == true)
Since multiple error contains more than one index, so it might not picking data.
check length for more than error.
$.ajax({
type: 'POST',
url: plSubmitUrl,
data: plFormData,
dataType: 'json',
cache: false,
timeout: 10000,
success: function (data) {
var x = data.length;
if(x == 1){
if (data.error === true) {
// display error message
plResponse(data.msg, true);
...
} else if (data.error === false) {
// display success message
plResponse(data.msg, true);
}
}else{
jQuery.each(data,function(key,val){
// do whatever you need
}
}
header('Content-Type: application/json');
Add this right before echoeing in your PHP script to let jquery know it has to parse the whole string as JSON.
And use "==" to compare instead of "==="

jQuery.ajax / CodeIgniter (PHP) : Returning TRUE/FALSE in PHP, how can I get jQuery to see this?

I've built a function for checking a username. I'm using it as a callback for form validation in CodeIgniter, and it works nicely. However, I'd like to also use it with AJAX to check on the fly if the user has JS enabled. So my controller has this:
function check_username($s = FALSE)
{
if ($s):
$this->db_common->like('username', $s);
$query = $this->db_common->get('users');
if ($query->num_rows() > 0):
$this->form_validation->set_message('check_username', 'Username taken. Choose another!');
return FALSE;
else:
return TRUE;
endif;
else:
echo 'Username required';
endif;
}
And my HTML/JS is this:
$(document).ready(function()
{
var delayed;
$("#username").keyup(function()
{
clearTimeout(delayed);
var value = this.value;
if (value)
{
delayed = setTimeout(function() {
$.ajax
({
type: "POST",
url: "<?php echo base_url(); ?>auth/check_username/",
data: $("#username").val(),
success: function(html)
{
$("#username_check").html(html);
}
});
}, 100);
}
});
});
Basically, I'm returning FALSE if the username exists and TRUE if it does exist. How do I get my jQuery AJAX to see that? Basically, I want jQuery to check if it's false, then say 'username exists' and if it's true, then 'username is okay'.
Do something like the following:
echo 'ok';
return TRUE;
The reason for this is that jQuery can't see the boolean values returned by PHP as they're not send to the browser's output.
Basically, I'm returning FALSE if the username exists and TRUE if it does exist. How do I get my jQuery AJAX to see that?
You can't directly. I would output 0 or 1 instead.
I would return true or false as JSON boolean from your PHP script and use javascript's eval() function to evaluate that to a javascript var.
There is a way to do it with PHP and jQuery. Here is an example...
simply have your php script echo back true or false.
PHP-> echo true; or echo false;
$.post("your_url/your_class/your_method", { } ,
function(data) {
if(data) alert('true');
else alert('false');
}, "json")
.error(function() { //alert("an AJAX error occurred!");
});

Categories