Reputation: 1702
Im using Codeigniter MVC framework and im struggling with Jquery Ajax. My Questions is how do you put a conditional statements inside the ajax success function?
Basically what I want to do is upon successful entry it will redirect to another page if not will show an error of: Mobile Number does not match or if empty Please fill up the blank.
Controller method
if($mobile_number == "") {
$data = array('message' => "Please fill up the blanks", 'success' => 'no');
}
elseif($mobile_number != "123") {
$data = array('message' => "Please does not match", 'success' => 'no');
}else {
#redirect('home/test');
$data = array('message' => "Mobile match.", 'success' => 'yes');
}
$output = json_encode($data);
echo $output;
my_ajax.js
$(document).ready(function(){
$("#request_submit").click(
function(){
var mobtel=$("#mobtel").val();
$.ajax({
type: "POST",
url: "post_action",
dataType: "json",
data: "mob_tel="+mobtel,
cache:false,
success: function (data) {
if(data.success == 'yes') {
$("#form_message").html(data.message).fadeIn('slow');
}
else if(data.success == 'no') {
alert('error');
}
}
});
});
});
Thanks in advance. Hope someone can help me here. (T_T)
Upvotes: 4
Views: 17600
Reputation: 4592
You could use a for loop to search for any keys in the callback object
If you want to see if an error key exists in the callback you could use:
success: function(cb)
{
for(errors in cb)
{
//checking for error key in the callback
}
}
Upvotes: 0
Reputation: 4924
Not sure if I understood your question well... From what I got this should nudge to the proper direction.
If I were you, I'd change my response to the following format:
$data = array(
'message'=> /* Your message */,
'success' => /* True or false */,
'case'=> /* 1,2,3 something unique to tell the cases apart */,);
echo json_encode($data);
So, in jQuery I can simply do this:
$.ajax({
type: "POST",
url: "post_action",
dataType: "json",
data: "mob_tel="+mobtel,
cache:false,
success: function (data) {
switch(data.case){
1: /*First case */
break;
2: /*Second... */
break;
3: /* You know the drill... */
break;
default:
/* If none of the above */
}
}
});
Since there are three cases in your code, it's best practice to handle them as three cases. More solid code, and less error prone.
I hope this helps!
Upvotes: 3
Reputation: 32070
In Controller method:
At the end of function use exit();
In my_ajax.js
$(document).ready(function(){
$("#request_submit").click(
function(){
var mobtel=$("#mobtel").val();
$.ajax({
type: "POST",
url: "post_action",
dataType: "json",
data: "mob_tel="+mobtel,
cache:false,
success: function (data) {
if(data.success == 'yes') {
$("#form_message").html(data.message).fadeIn('slow');
}
else{
if(data.message == "Please does not match"){
//show error message where ever you want
$("#form_message").html(data.message).fadeIn('slow');
}else{
//Do whatever you want to do :: to redirect can use window.location
alert('data.message')
}
}
}
});
});
});
Upvotes: 0