Snehal Snehal - 1 month ago 5x
jQuery Question

how to show error message if result in json is fail?

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;
$discount_arr ['result'] = 'success';
$discount_arr['msg'] = 'Valid Code';
$discount_arr['url'] = base_url('cart');
$discount_arr['redirect'] = 1;
echo json_encode($discount_arr);


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


function checkStatus(){
var discount_code = $(".cart-secondary .cart-discount-code .discount-code").val();

url : "<?php echo base_url('cart/validate/'); ?>",
type : "POST",
data : {discount_code: discount_code} ,
cache : false,
statusCode: {
404: function() {
alert( "page not found" );
success:function(data, textStatus, jqXHR)
if(textStatus == 'success'){
$('.cart-secondary .cart-discount-code-show span').html(discount_code);

error: function(jqXHR, textStatus, errorThrown) {
//if fails

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'){
    /* ... */