How to get responds from php to jquery ajax - php

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
}

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
?>

Stop Execution Php

I have this code , iam trying to use javascript to stop executing but its not working with javascript , any suggestions ? Am just trying to stop executing if the return was false from the javascript
if(mysql_num_rows($runzz)==0){
echo "<p align='center'><font size='5'>This Item $code1 - $code2 - ".$rw2['description']. "</br></br> Doesn't Exist In The <u><b>".$rowto['name']."</b></u></br></br> Wanna Add IT ?</font></p>";
?>
<script>
function check(){
var r = confirm("Press a button!");
if (r == true) {
return true;
} else {
return false;
}
}
check();
</script>
<?php
}
$insert="INSERT INTO transfercopy(warehouseidfrom,warehouseidto,qty,itemid,uid)VALUES('$from','$to','$qty','$codeid','$uid')";
$run=mysql_query($insert,$con);
if(!$run)die("error".mysql_error());
I am adding sample code to give you an idea, how you could use AJAX Call with it.
<?php
if(mysql_num_rows($runzz)==0){
echo "<p align='center'><font size='5'>This Item $code1 - $code2 - ".$rw2['description']. "</br></br> Doesn't Exist In The <u><b>".$rowto['name']."</b></u></br></br> Wanna Add IT ?</font></p>";
?>
<script>
function check(){
var r = confirm("Press a button!");
if(r) {
// Add additional parameter
// You could use POST method too. Use whatever make sense to you.
var urlLink = 'http://www.example.com/warehouse/record.php?from=<?php echo $from?>&to=<?php echo $to?>';
$.ajax({
type: 'GET',
url: urlLink,
success: function(data) {
if(data == 'success') {
return 'You have successfully added new record!';
}
},
error: function(data) {
console.log(data);
}
});
} else {
return false;
}
}
check();
</script>
<?php } ?>
<?php
// -- New File: record.php File
//
// You might wanna add the check, that it's the legit request and all the PHP Validation
$form = $_GET['from'];
$to = $_GET['to'];
$qty = $_GET['qty'];
$codeid = $_GET['codeid'];
$uid = $_GET['uid'];
$insert="INSERT INTO transfercopy(warehouseidfrom,warehouseidto,qty,itemid,uid)VALUES('$from','$to','$qty','$codeid','$uid')";
$run=mysql_query($insert,$con);
if(!$run) die("error".mysql_error());
else return 'success';
?>

check if php-clause true or false using jquery

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.

NaN error in ajax callback

I am getting a NaN error in my ajax callback function and can only think it has to do with an array in PHP. I have been trying to find ways to correct it but have come up against a brick wall.
What is supposed to happen is that PHP queries the database and if there are no results send a response to ajax and issue the error message. However, all I am getting is NaN. The error stems from the success code below.
I would be grateful if someone could point out my error.
PHP code:
$duplicates = array();
foreach ($boxnumber as $val) {
if ($val != "") {
mysql_select_db($database_logistor, $logistor);
$sql = "SELECT custref FROM boxes WHERE custref='$val' and status = 'In'";
$qry = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($qry) < 1) {
$duplicates[] = '[ ' . $val . ' ]';
$flag = 1;
} else {
$duplicates[] = $val;
}
}
}
//response array with status code and message
$response_array = array();
if (!empty($duplicates)) {
if ($flag == 1) {
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'ERROR: ' . implode(',', $duplicates) . ' needs to be in the database to be retrived.';
}
//if no errors
} else {
//set the response
$response_array['status'] = 'success';
$response_array['message'] = 'All items retrieved successfully';
$response_array['info'] = ' You retrieved a total of: ' . $boxcount . ' boxes';
}
//send the response back
echo json_encode($response_array);
Relevant ajax:
$("#brtv-result").html(msg.message+msg.info);
jQuery code:
$(function() {
$("#BRV_brtrv").submit(function() {
var send = $(this).serialize();
$.ajax({
type: "POST",
url: "boxrtrv.php",
cache: false,
data: send,
dataType: "json",
success: function(msg) {
if( msg.status === 'error') {
$("#brtv-result").fadeIn(1000).delay(1000).fadeOut(1000);
$("#brtv-result").removeClass('error');
$("#brtv-result").removeClass('success');
$("#brtv-result").addClass(msg.status);
$("#brtv-result").html(msg.message);
}
else {
$("#brtv-result").fadeIn(2000).delay(2000).fadeOut(2000);
$("#brtv-result").removeClass('error');
$("#brtv-result").addClass('success');
$("#brtv-result").addClass(msg.status);
$("#brtv-result").html(msg.message+msg.info);
//location.reload(true);
//$('#brtv-result').addClass("result_msg").html("You have successfully retrieved: "+data.boxnumber).show(1000).delay(4000).fadeOut(4000);
$("#BRV-brtrv-slider").val(0).slider("refresh");
$("input[type='radio']").attr("checked",false).checkboxradio("refresh");
var myselect = $("select#BRV-brtrv-department");
myselect[0].selectedIndex = 0;
myselect.selectmenu("refresh");
var myselect = $("select#BRV-brtrv-address");
myselect[0].selectedIndex = 0;
myselect.selectmenu("refresh");
}
},
error:function(){
$("#brtv-result").show();
$("#brtv-result").removeClass('success');
$("#brtv-result").addClass('error');
$("#brtv-result").html("There was an error submitting the form. Please try again.");
}
});
return false;
});
});
NaN (pronounced nan, rhymes with man) only happens when you try to do an operation which requires a number operand. For example, when you try to Number('man') you'll get this error.
What you return from your PHP file, is simply an array which contains simply data. So, the problem is in your JavaScript. You have to send more parts of your JavaScript, so that we can see it thoroughly.
However, I recommend that you use Firebug and set a breakpint at the correct place (the callback function start), and check the stack trace of the calls to diagnose the problem.

Categories