Ajaxでは、成功部分は常に実行されます。しかし、エラーがある場合、私は正常を実行したくありません。代わりに私はエラーメッセージを表示したい。割引コードが存在すると、コードと共にいくつかのdivを表示/非表示してからリダイレクトする。そうでなければエラーdivにjsonレスポンスで表示されるエラーメッセージを表示する。どうすればこれを達成できますか?ここでjsonの結果が失敗した場合のエラーメッセージの表示方法
JSONレスポンスです:
{result: "fail", msg: "Code is not valid", redirect: 0}
コントローラ:
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>
アヤックス:
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);
}
});
}
を行います失敗した場合はdivと置き換えられ、結果が成功した場合にのみ発生します@low_rents – Snehal
@Snehalは私の更新を見て、別の間違いを発見しました。 –
訂正してくれてありがとう:-) @low_rents – Snehal