dantheman
dantheman

Reputation: 273

How to perform an IF / ELSE with a post (ajax)?

I have two pages, one is a php page while the other is an html page. I use the $.post method to call the php page (perform some functions), return the data to the html page and insert the data into text boxes. However I am not that familiar with JQuery and I don't know how to create an if / else statement in case the php page produces an error.

My php page checks for exceptions and if one is caught I want the html page to insert the error message in a text field.

try{  
$ip=getIP();
$country = geoCheckIP($ip, $date);
echo json_encode(array('ip' => $ip, 'country' => $country, 'campaignID' => $campaignID));
}catch (Exception $e){
echo json_encode(array( 'errormsg' => $date . ' - Error: ' . $e->getMessage()));
}

Then on my html page I use the post method to call my php page and insert values into the text box.

<script type="text/javascript">
$.post("ip.php", function( data ){
$("#ip").val(data.ip);
$("#country").val(data.country);
$('#campaignID').val(data.campaignID);
$('#error').val(data.errormsg);
}, "json");
</script>

How can I perform an if else statement so that if ip, country, or campaign id have an error I only fill the error text field instead?

Upvotes: 0

Views: 212

Answers (1)

A1rPun
A1rPun

Reputation: 16837

You can check if the errormsg property is filled like this:

if(data.errormsg) {
    $('#error').val(data.errormsg);
} else {
    $("#ip").val(data.ip);
    $("#country").val(data.country);
    $('#campaignID').val(data.campaignID);
}

But to do it even better (credits to @itachi)

$.post("ip.php", function( data ){
    //handle success
    $("#ip").val(data.ip);
    $("#country").val(data.country);
    $('#campaignID').val(data.campaignID);
}, function( data ){
    //handle fail
    $('#error').val(data.errormsg);
});

You should also return an appropriate Status code from PHP when you use the above code.

Upvotes: 1

Related Questions