check if php-clause true or false using jquery - php

hey there i have this script´s:
$.ajax({
url: "checkAvailability.php",
type: 'POST',
dataType: "json",
data: 'username=' + $(this).data('id'),
success: function(data) {
if (result == 1) {
$("#select-err").text(data.error ? data.error : "");
}
else {
$("#select-err").text(data.error ? data.error : "");
}
}
});
in checkAvailability.php:
$availabilityChecker = new AvailabilityChecker($config);
if($availabilityChecker->check_availability($_POST['username'])) {
echo json_encode(array("error" => "is ok"));
$result = 1;
} else {
echo json_encode(array("error" => "Wrong chose"));
$result = 0;
}
while testing i found out that this is not the correct way to check if a php-clause is true or false, so i need your help...could anyone show me how to check this via jquery? greetings and thanks!
UPDATE:
i changed to:
$availabilityChecker = new AvailabilityChecker($config);
if($availabilityChecker->check_availability($_POST['username'])) {
echo 1;
} else {
echo 0;
}
and:
$.ajax({
url: "checkAvailability.php",
type: 'POST',
dataType: "json",
data: 'username=' + $(this).data('id'),
success: function(data){
if(data == 1){
$("#select-err").text(data.error ? data.error : "is ok");
}
else{
$("#select-err").text(data.error ? data.error : "not ok");
}
}
});
it works, BUT:
if data == 1, on my page "1" is displayed, why and how can i fix this?

Instead of doing this
if (result == 1) {
do this
if (data.result == 1) {
inside your success callback javascript file.
Then in your PHP file instead of these:
echo json_encode(array("error" => "is ok"));
echo json_encode(array("error" => "Wrong chose"));
do these instead:
echo json_encode(array("error" => "is ok", "result"=>1));
echo json_encode(array("error" => "Wrong chose", "result"=>0));
What I did is I included result as a property in the JSON coming from AJAX call. So instead of only having the error property you also have the result property in the JSON.

in php change to this
$availabilityChecker = new AvailabilityChecker($config);
if($availabilityChecker->check_availability($_POST['username'])) {
echo json_encode(array("error" => "is ok" , "result"=>1));
} else {
echo json_encode(array("error" => "Wrong chose" , "result"=>0));
}
and in jquery
check as
if(data.result==1){
// do the same
}else{
}

Don't echo json_encode(array("error" => "is ok")); in php in if-else statement, just echo result in both cases.
In you ajax it on success callback, it will return everything that is on ur php page i.e. result which may be 1 or 0. SO check if data==1 or data==0 instead of result.

Related

Cannot get data from json_encode in jQuery AJAX with php

I have an AJAX call from jQuery to PHP where the PHP responds with a json_encode array, but the values of the array are not accessible in jQuery.
The status is OK, but the responseText is undefined.
$(document).ready(function () {
$("#comments_form").on("submit", function(e) {
e.preventDefault();
e.stopPropagation();
$.ajax({
type: 'POST',
url: 'process_in.php',
data: {
first: $("#firstname").val(),
second: $("#lastname").val(),
third: $("#mail").val(),
fourth: $("#phone").val(),
fifth: $("#message").val()
},
success: function(result) {
var x = jQuery.parseJSON(result);
alert(x.f);
},
});
});
})
<?php
include ('connection.php');
if (isset($_REQUEST['first']) && isset($_REQUEST['second']) && isset($_REQUEST['third']) && isset($_REQUEST['fourth']) && isset($_REQUEST['fifth']))
{
$firstname = $_REQUEST['first'];
$lastname = $_REQUEST['second'];
$email = $_REQUEST['third'];
$contact = $_REQUEST['fourth'];
$message = $_REQUEST['fifth'];
$data = array();
$data["f"] = xssafe($firstname);
$data["l"] = xssafe($lastname);
$data["e"] = xssafe($email);
$data["c"] = xssafe($contact);
$data["m"] = xssafe($message);
echo json_encode($data);
}
function xssafe($d)
{
$x = filter_var($d, FILTER_SANITIZE_STRING);
return $x;
}
A good practice is to always catch the errors too. In your ajax request there is no error callback to handle the exception.
Use dataType: "JSON" instead of jQuery.parseJSON(); so that if json in unparsable you get the callback in the error block.
$.ajax({
type: 'POST',
url: 'process_in.php',
dataType: 'JSON',
data: {
first: $("#firstname").val(),
second: $("#lastname").val(),
third: $("#mail").val(),
fourth: $("#phone").val(),
fifth: $("#message").val()
},
success: function(result) {
console.log(result.f);
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
console.log(msg);
}
});
You can learn how to debug the code and check your error logs
Now lets get to your code, there are many possible cases that you are not getting the value.
It could be your php code or it could be your jquery.
In php to check whether its returning a valid json hit the url in browser like this
http://.../process_in.php?first=foo&second=foo&third=foo&fourth=foo&fifth=foo
As in your php code you haven't return any value so add an else part for the
if (isset($_REQUEST['first']) && isset($_REQUEST['second']) && isset($_REQUEST['third']) && isset($_REQUEST['fourth']) && isset($_REQUEST['fifth']))
{
$firstname = $_REQUEST['first'];
$lastname = $_REQUEST['second'];
$email = $_REQUEST['third'];
$contact = $_REQUEST['fourth'];
$message = $_REQUEST['fifth'];
$data = array();
$data["f"] = xssafe($firstname);
$data["l"] = xssafe($lastname);
$data["e"] = xssafe($email);
$data["c"] = xssafe($contact);
$data["m"] = xssafe($message);
echo json_encode($data);
} else {
echo json_encode(['error'=>'Invalid request']);
}

How to return value from second page to jquery page

I need to get the value from second page member_verify.php in my jQuery resonse which is in first page. I need to get $age value in first page. Now message displays correctly.
I need to get the age which I fetched in member_verify.php with $age=$fet['Age'];:
function memberid(em) {
var memid=$("#memid").val();
$.ajax({
type:'post',
url:'member_verify.php',
data:{memid: memid},
success:function(msg){
if (msg.length> 0) {
alert(msg);
}
else{
$("#disableDiv :input").attr("disabled", false);
}
}
});
}
member_verify.php
<?php
$s=$_POST['memid'];
include "common/config.php";
$echeck="select * from insmemberdetails where LoginId='".$_POST['memid']."'";
$echk=mysqli_query($conn,$echeck);
$fet=mysqli_fetch_assoc($echk);
$age=$fet['Age'];
$ecount=mysqli_num_rows($echk);
if($ecount=='0')
{
echo "Member Id Not exists";
}else
{
$fet=mysqli_fetch_assoc($echk);
$verify=$fet['verify'];
if($verify=='0')
echo "Member Id not Verified";
}
?>
Change your member_verify.php to get age in ajax response otherwise you will get validation message.
<?php
$s=$_POST['memid'];
include "common/config.php";
$echeck="select * from insmemberdetails where LoginId='".$s."'";
$echk=mysqli_query($conn,$echeck);
$ecount=mysqli_num_rows($echk);
if($ecount <= 0)
{
echo "Member Id Not exists";
}
else
{
$fet=mysqli_fetch_assoc($echk);
$age=$fet['Age'];
$verify=$fet['verify'];
if($verify==0)
{
echo "Member Id not Verified";
}
else
{
echo $age;
}
}
?>
And below is your JS file.
function memberid(em) {
var memid=$("#memid").val();
$.ajax({
type:'post',
url:'member_verify.php',
data:{memid: memid},
success:function(data){
console.log(data);
}
else{
$("#disableDiv :input").attr("disabled", false);
}
}
});
}
Hope this will help you.
May be you could know something about json.
php code:
if($ecount!=0){
echo json_encode(array(
errno: 0,
data: $age
));
}else{
echo json_encode(array(
errno: 500,
errmsg: 'your error info'
));
}
your js here:
$.ajax({
// add this option
dataType: 'json'
})
And if you try that :
<?php
$age=$fet['Age'];
$champAgeExist = isset($age);
if (champAgeExist == true) {
echo $age
?>

How to get responds from php to jquery ajax

Hi I am trying to echo out certain messages from the php code back to my ajax. But normally I would only have one echo message but this case I have 2. But I have no idea on how to assign each echo to one one .html()
$("#finish").submit(function(){
$.ajax({
type:"GET",
url:"checkFinish.php",
data: $("#finishProj").serialize(),
success: function(data){
$("#add_sucess").html();
$("#add_err").html();
}
}
});
if(!empty($mile1) && $mile1Pay == 'unPaid'){
$error = 'Payment Not Completed';
echo $error;
}
if(!empty($mile2) && $mile2Pay == 'unPaid'){
$error = 'Payment Not Completed';
echo $error;
}
if(!empty($mile3) && $mile3Pay == 'unPaid'){
$error = 'Payment Not Completed';
echo $error;
}
if(empty($error)){
$success = "Success";
echo $success;
}
I would like my echo $error to go inside the $("#add_err").html(); and echo $success to be in the $("#add_sucess").html(); How do I specify it? Cause normally if I only have one thing to echo out I would just $("#add_sucess").html(data);
I would return a JSON object back to my ajax. This way I can divide my messages up better.
JavaScript
$("#finish").submit(function(){
$.ajax({
type:"GET",
url:"checkFinish.php",
dataType: "JSON",//ajax now expects an JSON object to be returned
data: $("#finishProj").serialize(),
success: function(data){
//now that data is a JSON object, you can call the properties via data.prop
$("#add_sucess").html(data.success);
$("#add_err").html(data.error);
}
}
});
PHP
if(!empty($mile1) && $mile1Pay == 'unPaid'){
$error = 'Payment Not Completed';
}
if(!empty($mile2) && $mile2Pay == 'unPaid'){
$error = 'Payment Not Completed';
}
if(!empty($mile3) && $mile3Pay == 'unPaid'){
$error = 'Payment Not Completed';
}
if(empty($error)){
$success = "Success";
}
echo json_encode(array("error" => $error, "success" => $success));//json_encode an associative array and echo it back to request
exit();
Just make sure you have $success and $error defined before, otherwise you'll probably get an error.
Pass the flag of success : 1 for success and error: 0 for error from server side.
And at ajax success you can identify the response by checking data.res is 1 or 0. For example :
On server :
if($id > 0 ) // for success
{
// do other stuff
$data['res'] = 1 ;
}
else// for error
{
// do other stuff
$data['res'] = 0 ;
}
echo $json_encode($data);
On Client side :
success: function(data){
if(data.res==1)
{
$("#add_sucess").html();// add success message
}
else
{
$("#add_err").html();// add error message
}
}
Note : - Don't forget to use dataType: "json", in your Ajax call.
Update :-
If you are setting the string in success than set the success message or error on error message. so you check with EMPTY check on client side like :
if(data.success_msg != "")
{
$("#add_sucess").html(data.success_msg);// add success message
}
else
{
$("#add_err").html(data.error_msg);// add error message
}

jquery.ajax json wrong?

hey i have a problem submitting my data via jquery and back:
$.ajax({
url: "checkAvailability.php",
type: 'POST',
data : {data:JSON.stringify(data)},
success: function(data) {
if (data.result == 0) {
alert("0")
}
if(data.result == 1) {
alert("1")
}
}
});
so,
ONE of those if-conditions must be true, because of:
checkAvailability.php:
if(isset($_POST['data'])) {
define('SECURE', true);
include "storescripts/connect_to_mysql.php";
require 'AvailabilityChecker.php';
$config = array(etc..);
$availabilityChecker = new AvailabilityChecker($config);
$data = $_POST['data'];
$data = json_decode($data,true);
preg_match( '/(\d+(\.\d+)?)/', $data['x'] , $m);
$x = $m[0];
if($availabilityChecker->check_availability($x)) {
echo json_encode(array("error" => "is ok", "result"=>1));
} else {
echo json_encode(array("error" => "not ok", "result"=>0));
}
}
data.result have to be 1 OR 0.
anybody can tell me why there is no alert-message? greetings!
UPDATE:
$.ajax({
url: "checkAvailability.php",
type: 'POST',
data : {data:JSON.stringify(data)},
success: function(data) {
if (data.result == 0) {
alert("0")
} else { alert("fail-1") }
if(data.result == 1) {
alert("1")
} else { alert("fail-2") }
}
});
now i get first the fail-1 alert and than the fail-2 alert, so both if-conditions are false, why?
You need to specify the dataType, otherwise jquery will instead try to guess what you are trying to do. In this case it is incorrectly guessing text/html rather than application/json.
$.ajax({
url: "checkAvailability.php",
type: 'POST',
dataType: 'json',
data : {data:JSON.stringify(data)},
success: function(data) {
if (data.result == 0) {
alert("0")
} else { alert("fail-1") }
if(data.result == 1) {
alert("1")
} else { alert("fail-2") }
}
});
You should also properly set the content-type header in php, before you echo the json.
header('Content-type: application/json');
You can get away with doing either-or, but i'd suggest doing both.
a solution can be
success: function(d) {
data = jQuery.parseJSON(d);
if (data.result == 0) {
alert("0")
}
if(data.result == 1) {
alert("1")
}
}
this becouse $.ajax will no decode the result text from the page for you.
what the php code is doin in fact is to print a json string to the stream.
Note that the the output passed to success can be any sort of text (also xml code on simply text)
You need to set the correct content type header in your php file:
header('Content-Type: application/json');
//snip
echo json_encode(array("error" => "is ok", "result"=>1));

Jquery ajax parsing error for json

I am trying to send some data using php and jquery ajax using json datatype method.
Here is my code:
$("#username").on("keyup change keypress", function () {
var username = $("#username").val();
$.ajax
({
type: "POST", // method send from ajax to server
url: window.location.protocol + '//' + window.location.host + '/' + "admin/admins/user_exists",
data: {
username: username
},// Specifies data to be sent to the server
cache: false, // A Boolean value indicating whether the browser should cache the requested pages. Default is true
contentType: "application/json",
dataType: 'json', // The data type expected of the server response.
success: function (response_data_from_server) {
for (var key in response_data_from_server)
var result = response_data_from_server[key] + ""; // JSON parser
if (result == 'true') {
console.log("---------------- in true");
$("#username_alert").text("ERROR");
$('#username_alert').removeClass("alert-success");
$("#username_alert").css("visibility", "visible");
}
else {
if (result == 'false') {
console.log("---------------- in false");
$("#username_alert").text("NO ERROR");
$("#username_alert").css("visibility", "visible");
$('#username_alert').addClass("alert-success");
}
else {
if (result == 'empty') {
console.log("---------------- in empty");
$("#username_alert").text("ERROR");
$("#username_alert").css("visibility", "visible");
$('#username_alert').removeClass("alert-success");
}
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
and it always goes to an error function. The error that I receive is the following:
parsererror SyntaxError: Unexpected token  {}
My url location is correct and is indeed returning the correct json format. Here is my php code:
public function user_exists()
{
$username = $this->input->post("username");
$is_exists = "false";
$this->load->database();
if ($username != "")
{
$rows = $this->db->query("
SELECT * FROM `admins` WHERE `username` = '" . $username . "'
")->num_rows();
if ($rows > 0)
{
$is_exists = "true";
}
else
{
$is_exists = "false";
}
}
else
{
$is_exists = "empty";
}
$arr = array ('result' => $is_exists );
$response = json_encode($arr);
echo $response;
}
I've debugged it million times, the firebug sees the response as correct and expected json, however the client side seems to refuse to get it as a json respone, for what I believe.
Will appreciate any help!
...
header('Content-type: application/json');
echo $response;
Maybe you could use "header('Content-type: application/json');" before "echo"

Categories