public function actionAjaxUpdate()
{
$action = $_GET['act'];
if(!isset($_POST['selectedId']))
{
echo '<script> alert("No row is selected"); </script>';
}
else
{
$selectedAll = $_POST['selectedId'];
if(count($selectedAll)>0)
{
foreach($selectedAll as $selectedId)
{
$model=$this->loadCompositeModel($selectedId);
switch ($action) {
case 'Delete':
$model['account']->delete();
break;
case 'Active':
$model['account']->active = '1';
break;
case 'Inactive':
$model['account']->active = '0';
break;
default:
break;
}
$model['account']->save();
}
}
}
}
List item
In this code Alert is not working, if no id is selected.So some one help me out. i have tried alot but js is not working.
I have used js inside the php and this is the first time when js is not working inside the php
Without seeing the code that makes the HTTP request, it is hard to say what the problem is.
Them most likely explanation that selectedId is set to an empty string when no id has been selected. The condition !isset($_POST['selectedId']) will then not give you the result you want. Use empty() instead (and make sure that 0 is not an acceptable id value).
Unless you're injecting the response back into the page, the Javascript will never be evaluated.
If you were to do...
document.write('<script src="/path/to/phpscript.php">')
then the response will be appended to the page and evaluated.
However, if you do...
$.ajax({
success: function(response) {
//Blah....
}
});
or something to that effect, the response is never evaluated, it's passed to your success function as a string. So you could just get the PHP to print 1 or 0 for success/failure - or even better return a Json object
<?php
...
if(!isset($_POST['selectedId']))
{
$Ret->Success = false;
$Ret->Reason = "No row is selected";
header("Content-Type: application/json");
print json_encode($Ret)
}
?>
Then use the $.getJson Ajax call to retrieve the response as a Js object (See this manual page)
It seems $_POST['selectedId'] is an array. then you should use isset for elements of $_POST['selectedId'] for example if (!isset($_POST['selectedId'][0]))
EDIT 1: try this one
$array_id = array_filter($_POST['selectedId']);
then use if (!empty($array_id)) instead of if (!isset($_POST['selectedId']))
Related
Alright so I am trying to put this thing together, but I do not understand what is the problem with this code. I am basically trying to return false in case name exists in the database, but no matter what ajax will just pass it as a "success"
Here is the code:
Running the
function checkName(username) {
$.ajax({
url:"assembly/handler.php",
type:"POST",
data:{func:"run_namecheck", user_name:username},
success:function(data){
return true;
},
error:function(data) {
return false;
}
});
}
The code is executed perfectly and it actually passed all the things it needs, and the PHP function does get called.
PHP function bellow.
public function nameExists($name) {
$handler = new sql();
$sql = $handler->connect();
$sql->real_escape_string($name);
$name_final = ucfirst($name);
$result = $sql->query("SELECT ime FROM users WHERE ime='".$name_final."'");
if($result->num_rows != 0) return true;
else {
$handler->log_write($name, "login_fail","NULL");
return false;
}
$sql->close();
return false;
}
Now the problem is success and the error. No matter what it will always be success. It doesn't like pay attention at when I return FALSE from the PHP at all and such.
AJAX calls are literally just an HTTP request, like any other HTTP request. You're not directly "executing" PHP code when you make an ajax call, you're doing an HTTP request to the server, which (eventually) executes a PHP script on your behalf.
That means any return from the PHP code are completely invisible to Javascript.
Only OUTPUT from PHP will ever be seen by Javascript, which means you need to echo that data, not return it.
And note that any HTTP response from PHP is also literally plain text. Any output you perform in PHP will be converted to text, which means that boolean false you're trying return will be converted to the string equivalent of a boolean false - an invisible zero-length string.
"error" condition in your js code is only for bed requests, like 500, 404 etc.
return a json { error: true } or something like with and use it in your js
success:function(data){
if(data.error) {
// do...
}
},
As far as I can see your code, you're returning nothing to client. You shall return some data that represents the boolean value about the user existence. For instance:
// PHP server-side
if( nameExists( $name)) echo "T";
else echo "F";
that will return value can then be captured by the data parameter in your AJAX function for success and be tested about the server answer.
// Javascript in client
success:function(data){
if( data === "T") return true;
else return false;
},
Hope I can help!
instead of return from php you need:
echo "True" or "false"
to on javascript side:
function checkName(username) {
$.ajax({
url:"assembly/handler.php",
type:"POST",
data:{func:"run_namecheck", user_name:username},
success:function(data){
if(data=='true'){
alert("success process");
}else{
alert("fail process");
};
},
error:function(data) {
console.log("error Ajax");
}
});
}
The data transferred between the client and the server is always text. You need to make sure that the client and server know how the client should deserialize the text. So you might return one of four things:
HTML (if it's going to populate page elements)
JSON (if you want a lightweight, fast way to send data to the client)
XML (if you want a heavier-weight, fast way to send data to the client)
Plain text (for whatever you want, really)
What the client does will depend on what Content-Type header you use in your PHP page.
so, use a header in PHP, for eg:
header('Content-Type', 'application/json');
...and the return this text from it:
{"success": true}
or
{"success": false}
I hope it will help.
I was looking at this question: Return true/false to javascript from php file
But is not what I'm looking for, as I don't need to return text/strings in JSON.
What I want is to return true or false statements from loaded php file to jQuery.
jQuery: (How I think it could work)
if($("#lvlupann").load("/templ/checknlvl.php") == true){
$("#lvlupann").addClass("nlvlann");
}
And the mighty php file : (checknlvl.php)
if(1 == 1){
return true;
}
But obviously it doesn't return true/false, and class is not added... I know I'm going probably wrong on it, but don't know what to overwrite...
Any help would be appreciated.
You are doing it wrong.
The .load() method is asynchronous and does not return the value from the server (it returns the element that it was called on: $("#lvlupann")), so using the returned value in an if statement does not make sense.
You have to wait for the request to finish before you can use the value, like so:
$("#lvlupann").load("/templ/checknlvl.php", function (value) {
if (value == true) {
$("#lvlupann").addClass("nlvlann");
}
});
As for the PHP file, the return true; will just stop the script. It does not send anything to the client. In order to send two or more things from PHP to the client you need to package the output in some fashion.
The $.get method would be useful:
$.get('/templ/checknlvl.php').done(function (data) {
$("#lvlupann").html(data.content);
if (data.success) {
$("#lvlupann").addClass("nlvlann");
}
});
<?php
echo json_encode([
'content' => '<strong>Some content...</strong>',
'success' => true,
]);
die;
If all you want to do is get a boolean value from the PHP script then something like this would do it:
$.get('/templ/checknlvl.php').done(function (value) {
if (value === "true") {
$("#lvlupann").addClass("nlvlann");
}
});
<?php
if (1 == 1) {
echo 'true';
} else {
echo 'false';
}
die;
Heres the issue. I have an an ajax function that is just checking if an email that a user inputs is already used.
The php script that it uses either sends back "true" or "false" strings depending on the result. When i get the response text back, or the "data" variable in the below function, and see if its == to "true" it never passes and always evaluates to false.
This is odd, because when I have printed out the data variable on
screen it shows as "true" when it should, but its just not being shown
as equal to "true" in the if statement. No idea what is happening
here.
AJAX FUNCTION:
function check_email() {
var email = document.sign_up_form.email_first.value;
document.getElementById("email1").innerHTML = ' <img src="loading.gif" width="15">';
$.ajax({
type: "GET",
url: "java_check_email.php",
data: "email="+email,
success: function(data){
if(data == "true"){
document.getElementById("email1").innerHTML = ' <img src="check.png" width="15">';
document.getElementById("email4").innerHTML = '';
}
else {
document.getElementById("email1").innerHTML = ' <img src="xmark.png" width="15">';
document.getElementById("email4").innerHTML = 'Email is already in use<br>';
}
}
});
}
UPDATE:
PHP script looks like this
<?php
include('functions.php');
$email = $_GET['email'];
$query_check = "removed for obvious reasons...";
$result_check = mysql_query($query_check);
if(mysql_num_rows($result_check) == 0){
echo 'true';
}
else{
echo 'false';
}
?>
Also, after calling console.log(data) when the ajax response is received i got a value of "true" in the js console.....
For debugging, try
if (data.replace(/\s+/g, '') == "true") {
...my money is on whitespace outside the <?php ?> tags. Note that if this solves the problem it should not considered the solution - the real solution is to remove the additional whitespace from the PHP script.
The < of the opening <?php tag should be the very first character in the file. For example:
This empty line will be output directly
<?php
^^^^ This whitespace will be output directly
Note also that the closing ?> tag is often unnecessary (as it seems to be in this case) and omitting it completely can help avoid problems like this.
If you want to return a boolean to JS you should simply echo 1 or 0, so you can just do this in the receiving Javascript:
if (data) {
I know this is old but I've had the exact same problem and couldn't fix it. I am realy sure it wasn't a white-space issue but I was able to solve it in a different way.
Maybe it's not the best way (I still want to know why it doesnt work in the usual way), but what I did was echo a 0 (for false) and a 1 (for true)
Then I parsed the data to an Integer, so my code looks like this:
function(data){
var result = parseInt(data);
if (result === 1){
$('#loginresult').html('OK');
} else {
$('#loginresult').html('NOT OK');
}
I hope I can help anyone with this workaround (but a good solution would be better)
All,
I have an AJAX function, that calls a PHP URL through html data type. I cannot use other datatypes for my AJAX requests due to server constraints. I am trying to print a message and also handle scenarios based on the return code. The following code doesn't seem to work. Can you advise?
Here's a simple AJAX call:
$.ajax({
type: "POST",
url: "validateUser.php",
dataType: html,
success: function(msg, errorCode){
if(errorCode == 10)
{
callAFunction();
}
else if(errorCode == 20)
{
callSomething();
}
else
{
doSomethingElse();
}
}
});
PHP CODE:
---------
<?php
function validateUser()
{
$username = 'xyz';
if (!empty($username) && strlen($username)>5)
{
echo 'User Validated';
return 10;
}
else if (empty($username))
{
echo 'Improper Username';
return 20;
}
else if (strlen($username)<5)
{
echo 'Username length should be atleast 5 characters';
return 30;
}
exit;
}
?>
Thanks
Your PHP is a just a function. It is not being called.
Also, you are not sending any data to your PHP file.
what you can do is print them in div something like this.
<div class="errorcode">30</div><div class="errormessage">Username length should be atleast 5 characters</div>
and then in your success function in ajax you can use jquery to parse the response text and use selectors like $(".errorcode").html() and $(".errormessage").html() and get the response. this makes things easy
also looks like you are not posting anything
Remove exit; at the end of validateUser(). It causes the execution of the entire script to stop immediately.
Since this is the last line of validateUser(), there is no need to add return.
Documentation: exit, return
Following is a part of an AJAX functionality to add classes and packs to session cart:-
The jquery part
function addClassToCart(itemId)
{
addItemToCart(itemId,true);
}
function addPackToCart(itemId)
{
addItemToCart(itemId,false);
}
function addItemToCart(itemId,isClass)
{
$.post(url+"/ajax/add_cart", { operation: 'add_cart','isClass':isClass, 'itemId': itemId},
function(data)
{
if(data.success)
{
alert("item added to cart");
}
}, "json");
}
The AJAX request processing php part -
//Checking operation and other posted parameters
if($_POST['isClass'])
{
//Code to add class to session cart
}
else
{
//Code to add pack to session cart
}
The strange thing
No matter whether I pass true/false (by calling addClassToCart() and addPackToCart()), always the code to add class to session cart executes.
If I put echo statements there like this:-
if($_POST['isClass'])
{
echo "see if condition ".$_POST['isClass'];
}
else
{
echo "see else condition ".$_POST['isClass'];
}
This is the output:-
addClassToCart() see if condition true
addPackToCart() see if condition false
Putting conditions like this in the jquery code however works fine:-
function addItemToCart(itemId,isClass)
{
if(isClass)
alert("is class");
else
alert("is pack");
}
Finally, if I alter the server side code to this:-
if($_POST['isClass'] === true)
{
echo "see if condition ".$_POST['isClass'];
}
else
{
echo "see else condition ".$_POST['isClass'];
}
These are the outputs -
addClassToCart() see else condition true
addPackToCart() see else condition false
So, why is the boolean variable treated as a string here? Am I doing something wrong in posting parameters?
Thanks,
Sandeepan
Also you can use filter_var function with filter FILTER_VALIDATE_BOOLEAN. According to php documentation it
Returns TRUE for "1", "true", "on" and "yes". Returns FALSE otherwise. If FILTER_NULL_ON_FAILURE is set, FALSE is returned only for "0", "false", "off", "no", and "", and NULL is returned for all non-boolean values.
So receiving of POST parameter will look like:
$isClass = filter_var($_POST['isClass'], FILTER_VALIDATE_BOOLEAN);
You aren't doing anything wrong per se, it's just that when it gets posted, it looks like this:
operation=add_cart&isClass=true&itemId=1234
PHP can't tell what the data type is because it isn't passed, it's always just a string of POST data, so compare it to "true" to do your checks, like this:
if($_POST['isClass'] === "true")
{
//Code to add class to session cart
}
else
{
//Code to add pack to session cart
}
This is a bit of an old question, but I'm surprised nobody has posted this here as solution.
Just use 1 and 0 instead of true and false when you're constructing your ajax requests.
When you do a == comparison, they'll be interpreted as true/false.
JS:
$.ajax({
url: '....',
data: {
foo: 1,
bar: 0
}
});
PHP:
<?php
if ($_GET['foo']) {
//...
} else {
//...
}
echo $_GET['bar'] ? 'bar is true' : 'bar is false';
?>
Send the data from your javascript as stringified JSON.
Make a PHP function to convert the strings 'true' and 'false' to boolean value.
Personally I like #2, which goes with Nick Craver's answer.