Clearing input field depending on callback
I have simple script which contains two pages - script.php and function.php. Script.php contains one input field with ID #code , one link with ID #submit and jquery function
$('#submit').click(function () {
$.ajax({
url: 'function.php',
type: "POST",
data: "text=" + $("#code").val(),
dataType: 'text',
success: function(data) {
$('#info').html(data);
}
});
return false;
});
How can I clear #code input field value depending on the return result from function.php? For example, if query is incomplete function.php will only show message in #info field, but if query is complete script will show message a开发者_StackOverflow社区nd clear input field value.
Consider returning JSON data from function.php, so something like this
{"clearCode":"true","info":"Some HTML"}
Then you can use the jQuery function getJSON.
This means you can return a boolean which decides whether to clear #code or not and also return some html for #info
return any status from your php page like success or failure, and then check it in success method, because success is executed if ajax call is completed successfully regardless of result,
you can do
$('#submit').click(function () {
$.ajax({
url: 'function.php',
type: "POST",
data: "text=" + $("#code").val(),
dataType: 'text',
success: function(data) {
if (data == "success")
{
$("#code").value("");
}
else
{
$('#info').html(data);
}
}
});
return false;
});
hope this helps.
From your example, you could return a specific HTTP code:
In PHP:
if(not_valid) { Header("HTTP/1.1 403 Forbidden"); die(); }
In JavaScript:
$.ajax({ ...,
success: function() { /*ok*/ },
statusCode: {
403: function() { /*wrong*/ }
}
)};
精彩评论