In Ajax, the success part always executes. But if there is an error , I don't want to execute the normal; instead I want to show an error message.If the discount code is present then show/hide some div along with code and then redirect, else display the error message which we get in json response in the error div. How can i achieve this ?
Here is json response :
{result: "fail", msg: "Code is not valid", redirect: 0}
controller :
if($result == 'exp'){
$discount_arr ['result'] = 'fail';
$discount_arr['msg'] = 'Promotion code expired';
$discount_arr['redirect'] = 0;
}else{
$discount_arr ['result'] = 'success';
$discount_arr['msg'] = 'Valid Code';
$discount_arr['url'] = base_url('cart');
$discount_arr['redirect'] = 1;
}
echo json_encode($discount_arr);
HTML :
<div class="cart-secondary cart-discount-code">
<label for="cart_Code">
Discount Code </label>
<input type="text" class="discount-code" name="cart_discountCode" id="cart_discountCode">
<span class="error coupon-error"></span>
<div class="confirm-coupon"></div>
<button type="submit" value="addCoupon" name="addCoupon" id="add-coupon" onclick="checkStatus()">
Apply </button>
Ajax:
function checkStatus(){
var discount_code = $(".cart-secondary .cart-discount-code .discount-code").val();
$.ajax(
{
url : "<?php echo base_url('cart/validate/'); ?>",
type : "POST",
data : {discount_code: discount_code} ,
cache : false,
dataType:'json',
statusCode: {
404: function() {
alert( "page not found" );
}
},
success:function(data, textStatus, jqXHR)
{
if(textStatus == 'success'){
$('input[name=cart_discountCode]').val(discount_code);
$('.cart-secondary .cart-discount-code-show span').html(discount_code);
$(".cart-discount-code").fadeOut();
$(".cart-discount-code-show").fadeIn();
if(data.redirect){
window.location.reload();
}
}
},
error: function(jqXHR, textStatus, errorThrown) {
//if fails
console.log(errorThrown);
}
});
}
Please help
just use an else for your if comparison.
update: you are accessing the wrong variable of your success-callback. you are not interested in the textStatus, you want to read the data you are returning by yourself. the returned json object is saved in the data variable:
if(data.result == 'success'){
/* ... */
}else{
$(".error").text(data.msg);
}
You can access those information in data variable of success callback of the AJAX function.
Use it like this,
success:function(data, textStatus, jqXHR)
{
if(data.result != 'fail'){
$('input[name=cart_discountCode]').val(discount_code);
$('.cart-secondary .cart-discount-code-show span').html(discount_code);
$(".cart-discount-code").fadeOut();
$(".cart-discount-code-show").fadeIn();
if(data.redirect){
window.location.reload();
}
} else {
alert(redirect.message);
if(data.redirect==1) {
// redirect here..
}
}
}
So access those data using,
data.message
data.redirect
data.result
It's normally as you access property of any JavaScript object.
If you are getting
{result: "fail", msg: "Code is not valid", redirect: 0} in success block,
then do this
success:function(data, textStatus, jqXHR)
{
if(data.result !== 'fail' && textStatus == 'success'){
$('input[name=cart_discountCode]').val(discount_code);
$('.cart-secondary .cart-discount-code-show span').html(discount_code);
$(".cart-discount-code").fadeOut();
$(".cart-discount-code-show").fadeIn();
if(data.redirect){
window.location.reload();
}
}
},
Related
I am working on notifications in php.
In header file, I have written this function:
$(document).ready(function() {
setInterval(getNotifys, 10000);
function getNotifys(){
$.ajax ({
method: "POST",
url : 'get_notification.php',
success : function(data){
console.log(data);
$('.notifications').html(data);
}
});
}
});
And here is get_notification.php;
<?php
include("global.php");
if($logged==0){
header("location:".$baseurl."login.html");
exit();
}
$data=mysqli_query($con,"select * from notifications where admin=1 and resolved=0") or die (mysqli_error());
$count = mysqli_num_rows($data);
?>
<span class="badge badge-danger" style="margin-bottom:25px"><?php echo $count; ?></span>
It works perfectly over most of the pages, but in some pages, it occurs that instead of displaying count to notification icon, it shows whole page HTML. Even when I console in success function, It consoles whole page HTML. I am so confused why is it happening. Any ideas?
use json and create that span stuff in your javascript code.
<?php
include("global.php");
if(!$logged) {
http_response_code(401); // catch this error in ajax
exit();
}
$data = mysqli_query($con,"select * from notifications where admin=1 and resolved=0");
if(!$data) {
http_response_code(500); // catch this error in ajax
exit();
}
$count = mysqli_num_rows($data);
echo json_encode(['count' => $count]);
JS:
$(document).ready(function() {
setInterval(getNotifys, 10000);
function getNotifys(){
$.ajax ({
method: "POST",
url : 'get_notification.php',
success : function(data){
let data = JSON.parse(data);
console.log(data);
$('#notifications_count').html(data.count);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
});
HTML:
<span class="badge badge-danger" style="margin-bottom:25px" id="notifications_count"></span>
Did not test this, but this shows you how you could do it.
so I have the following code that is calling a CheckEmail2.php. I know what I want to do in CheckEmail2.php but because my Ajax success is not working, I have minded the scope to just return a Json. below is my java script. When I launch my console, I see my string coming through that I am echoing in my CheckEmail2.php. so I know my php file is getting read but why won't my success function hit if my string is getting read? I can't get my success function to get called. It always goes to error.
<script type="text/javascript">
function validateForm(){
var email = document.forms["signupform"]["email"].value;
var result = false;
if (email != ""){
$.ajax({
type: "POST",
url: "/CheckEmail2.php",
data: { "User_Email": email },
dataType: "json",
success: function(resp){
console.log(resp);
if(resp == "Not Found"){
result = true;
}
else
{
result = false;
}
},
error: function(data, status){
console.log(data, status);
}
}); //end Ajax
}
return result;
}
</script>
here is my PHP
<?php
header("Content-type:application/json");
echo json_encode("Not Found");
?>
why is error always getting called?
I have send query ajax request to server. The server response in two variable that is errmsg or successmsg . so how can i understand response is whether errmsg or successmsg. More code explain below
script.js
$.ajax({
url:"abc.php",
method:"POST",
data:$('#form').serialize(),
success:function(data){
?????????
}
error:function(data){
.......
}
});
abc.php
<?php
if (condition) {
$successmsg = hello;
echo "$successmsg";
}
elseif (condition) {
$errmsg = Error Occured;
echo "$errmsg";
}
elseif (condition) {
$successmsg = welcome;
echo "$successmsg";
}
else {
$errmsg = Bye;
echo "$errmsg";
}
?>
return error or success depending on what you are doing with your code in php for example
return iferror ? ['errmsg' = 'Error'] : ['successmsg'=>'success'];
then get your response in ajax like
$.ajax({
url : 'your-url,
data : {your - data},
success: function(response){
if(response.successmsg){
console.log(response.successmsg);
}
else{
console.log(response.errmsg);
},
error: function(response){
console.log(response);
}
});
You can return the server's response using this code:
<?php
if ($textvar > 500){
echo 'SUCCESS';
}else{
echo 'ERROR';
}
?>
Then the Ajax code can be:
$.ajax({
cache: false,
url: '/js/checkmsgs.php',
success: function(res){ // This will be applied if the php code is completlly done without any programming mistakes.
if (res == 'SUCCESS'){
alert('Success');
}else{
alert('Error !');
}
},
error: function(){ // this one will be applied if the php code have a mistake !
alert('eeeeeerrror');
}
});
jQuery modal is executed fine, but I don't know what am I missing when I want to display an alert message when the form is successfully executed by php?
$.post(
'name.php',
{ ime: ime, location: location },
function(data){
if (data.success) {
alert("form posted!");
}
else {
$("#dialog-form").dialog("open");
}
},
"json"
);
==========================The PHP============
if ($result == false) {
echo json_encode(array('success' => false, 'result' => 0));
exit;
}
echo json_encode(array('success' => true, 'result' => $result));
$sql2 = "DELETE FROM $names WHERE name='$ime'";
$result2 = mysql_query($sql2);
Looks as if the value of data.success is not coming back as true or false (or evaulating as a boolean like you're expecting).
Try:
$.post(
'name.php',
{ ime: ime, location: location },
function(data){
if (data.success == 'true') {
alert("form posted!");
}
else {
$("#dialog-form").dialog("open");
}
},
"json"
);
You could also use FIDDLER to see the value coming back from the server.
http://www.fiddler2.com/fiddler2/
the success has 3 argument success(data, textStatus, jqXHR)
I believe you may want textStatus
.success:
A function to be called if the request succeeds. The function gets
passed three arguments: The data returned from the server, formatted
according to the dataType parameter; a string describing the status;
and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object.
$.post(
'name.php',
{ ime: ime, location: location },
function(data, textStatus, jqXHR){
if (textStatus == "success") {
alert("form posted!");
}
else {
$("#dialog-form").dialog("open");
}
},
"json"
);
Something is wrong with this AJAX function but I do not see what.
AJAX
$('.review').click(function() {
var idatas = $(this).attr('rel');
var idata = 'idata=' + idatas;
$.ajax({
type: 'POST',
url: '<?php echo $thisposturl;?>?review',
data: idata,
beforeSend: function() {
$(this).addClass('ractive');
},
dataType:'json',
success: function(data) {
$('#dbody').html(data.ioutput);
$('.cright').height($('#dropout').height());
$('#dropout').addClass('dropopen');
},
error: function(data) {
$('#dbody').html('arse biscuity');
$('.cright').height($('#dropout').height());
$('#dropout').addClass('dropopen');
}
});
PHP
<?php
$rid = $_POST['idata'];
$ireviews = get_posts('post_type=reviews&p='.$rid.'&numberposts=-1');
foreach ($ireviews as $ireview) :
setup_postdata($post);
$ioutput = '<div class="iavatar"></div>
<div class="ititle">'.get_the_title($ireview).'<br />
<div class="iauthor">'.get_the_author($ireview).'</div></div>
<div class="icontent">'.get_the_content($ireview).'</div>';
endforeach;
echo json_encode(array('ioutput'=> $ioutput));
?>
According to Firebug the response is this
{"ioutput":"<div class=\"iavatar\"><\/div>\n<div class=\"ititle\">What a lovely course<br \/>\n<div class=\"iauthor\">pm master<\/div><\/div>\n<div class=\"icontent\">This intimate layout, with its undulating and springy fairways that zigzag in amongst the woodland setting, calls for accurate driving and precision shot-making into the well-bunkered greens; another classic Colt trademark. Position, not power, is the name of the game here.<\/div>"}
But it is going to error function and not putting the content in #dbody
Any ideas?
Try using the $.ajaxSetup() to get the correct error like this:
$(function() {
$.ajaxSetup({
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
In case of any error in the Ajax call, you will get proper alert.