Verify data from PHP file with get method (AJAX) - php

I want to use an if statement to compare data from a PHP file.
I'm using AJAX to get the data from PHP files and append them to HTML.
This will be an example of code.
PHP_file.php
if ($active == "ready") {
echo "true";
} else {
echo "false";
}
AJAX Function
$.get("PHP_file.php", function(data, status){
if (status == "success"){
if (data == "true") {
//do something
} else{
//do something else
};
}
});
The AJAX function doesn't do what I want, it always ends up in the "else" statement. Can I read the data, and compare it, with jQuery?
UPDATE [SOLVED]
I found the problem: some functions we're working properly so it was always going to the else statement.
Thank you for the help everyone, and sorry for the misunderstanding.

Related

Return true to jquery from php file

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;

Check with jquery if result/echo from PHP starts with "abc"

I am using jquery and ajax to submit forms without page reloading and then depending on the result (whether it is a success or an error) I print the message in two different divs. Since success and error in ajax only checks the client/server connection I echo some stuff from PHP when query succeeds and depending on that I condition what to do with the message. Jquery/ajax part looks like that (normally I use two different divs, but to simplify the example I will use alerts):
success: function (result) {
if (result == 'success') {
alert("Success!");
} else {
alert("There was an error.");
}
},
This works perfectly, but I would like to improve its usability.
Now the question is: can I use in if (result == part something like str.match? For example if there were some problems running the query I would echo in php echo "Error: >error description here<"; Could I then somehow use str.match(/^Error/) in my if condition and echo the entire message?
Don't use string matching for this task. Use HTTP response codes - that's what they're there for! The http_response_code function in PHP is designed for this exact purpose:
<?php
if ( /* error condition */ ) {
http_response_code(400); // "Bad request" response code
echo 'Invalid parameters';
}
else {
echo 'Success'; // response code is 200 (OK) by default
}
Then you can use jQuery's done and fail callbacks to handle the two cases separately:
$.ajax(url, params)
.done(function(response) { alert('all good: ' + response); })
.fail(function(response) { alert('error: ' + response); })
To check if the message starts with Error: you can use indexOf:
if (result.indexOf('Error:') === 0) {
// Starts with `Error:`
}
indexOf will return the index starting from 0 where Error: is found in the result string.
Reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
The indexOf() method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found.
to answer the 'improve' part of your question i would do some JSON.
php:
//Your code here and create an associative array like so:
if($errors){
$data(
'results'=>'errors',
'message'=>'it failed'
);
}else{
$data(
'results'=>'success',
'message'=>'it worked'
);
}
echo json_encode($data);
and then your js would be somthing like:
success: function (result) {
if (result.results == 'success') {
alert(result.message);
} else if (result.results == 'errors' {
alert(result.message);
}
},
related : http://www.dyn-web.com/tutorials/php-js/json/array.php#assoc

How do I pass the correct data type to Javascript from PHP

I am using the jQuery post method to create a record in MySQL. When I evaluate the output of the PHP with ==, all three conditionals work properly. However, when I use ===, the first two conditionals return false. How do I pass the correct data type to Javascript from PHP?
jQuery:
$("#form").validate({
submitHandler: function(form) {
// do other stuff for a valid form
$.post('inc/process_form.php', $("#form").serialize(), function(data) {
//alert(data);
if (data == 1) {
$('#results').html("Success");
} else if (data == 2) {
$('#results').html("No Success");
} else {
$('#results').html(data);
}
});
}
});
This is the PHP (which I've truncated to only show the execute conditional):
$value = $stmt->execute();
if ($value === TRUE) {
echo 1; //success
} else {
echo 2; //failure
}
try this:
if(parseInt(data) === 1){
The problem is the return variable data is a string, you can't do anything (as far as I know) from PHP to return it as a integer.
As the comment by Marc Costello suggested, this makes the === useless since you are forcing both sides to be integer, so data == 1 is better in this case.
I never needed something like this but if you really have to you can simply cast it using +data:
data = +data;
if (data === 1) {
$('#results').html("Success");
} else if (data === 2) {
$('#results').html("No Success");
}
In this case you can pass boolean value instead of 0 or 1 i.e true or false from php

Java Script is not working inside the php

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']))

How can I echo a message and return a code to AJAX from PHP

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

Categories