I want to submit a form to a PHP script, let the script do its magic, then return said magic into a div as a visual indicator of its success/failure/change in status.
I have a form which I submit (I've cut out a lot of extraneous inputs/text areas, etc. of code which aren't important):
HTML:
<form name="ajaxform" id="ajaxform" method="post" action="ajax.php">
<table>
<tr class="left">
<td>Reporter:</td>
<td>//list of people</td>
</tr>
<tr class="left">
<td width="75%">
<p><label for="start">Start:</label>
<input type="text" name="start" id="start"></p>
<p><label for="end">End:</label>
<input type="text" name="end" id="end"></p>
</td>
</tr>
<tr>
<td>
<input name="sid" type="hidden" id="sid" value="<?=$sid?>">
<input name="table" type="hidden" id="table" value="add">
<input name="submit" type="submit" id="submit" value="Submit" class="submitForm">
</td>
</tr>
</form>
<div id="messageResponse"></div>
On submitting, the following JS gets run:
JS:
$(function() {
$('#ajaxform').validate({ // initialize the plugin
errorClass: "invalid",
submitHandler: function (form) {
$.ajax({
type:'POST',
url:'ajax.php',
data: $(form).serialize(),
success: function() {
$('#messageResponse').fadeIn(500);
$('#messageResponse').addClass('ui-state-highlight ui-corner-all').removeClass('ui-state-error');
$('#messageResponse').text('Success!' + result);
},
error: function (xhr, ajaxOptions, thrownError) {
$('#messageResponse').fadeIn(500);
$('#messageResponse').addClass('ui-state-error ui-corner-all').removeClass('ui-highlight-error');
$('#messageResponse').text(xhr.status + ' ' + thrownError + ': Something went wrong - check your inputs and try again.');
}
});
setTimeout(function(){ $('#messageResponse').fadeOut(500); }, 5000);
// resets fields
$('#ajaxform')[0].reset();
}
});
});
And then I have the script which get's picked out from a list of several PHP scripts based on the table variable passed from the form's hidden table input:
PHP:
if($_POST['table'] == "add"){
// Do mysql query which gives me an array
$result = array("foo" => "bar", "captain" => "coke");
echo(json_encode($result));
}
I want to submit my form, have it find the appropriate code in ajax.php and execute it, then return the result of that PHP script to messageResponse div. Where is this failing so miserably?
You should pass the result
variable in your success
method:
success: function (result) {
console.log(result);
}
In addition:
Set the type of data that you're expecting back from the server:
dataType: 'json'
Set the header of your result as JSON (in your PHP file):
header('Content-Type: application/json; charset=utf-8');
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다