Reputation: 27
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);
Upvotes: 0
Views: 64
Reputation: 3622
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
}
Upvotes: 1
Reputation: 1481
I would return a JSON object back to my ajax. This way I can divide my messages up better.
$("#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);
}
}
});
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.
Upvotes: 1