I'm trying to submit a variable from a form to an ajax request of a php file, and output the contents of the php file to a div.
Here's my main file:
<div>
<form name="zipform">
<p style="color:#cccccc;">Enter your Zipcode: <br><input type="text" name="zipcode">
<input type ="Button" Value="Search Providers" onClick="showAndClearField(this.form)">
</p>
</form>
</div>
<div id="result"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function showAndClearField(frm)
{
var zip = frm.zipcode.value;
frm.zipcode.value = "";
$.ajax({
url: "testphp.php?zipcode="+zip,
success: function (data) {
document.write("content of the executed page: " + data);
$("#result").html(data);
},
error: function (xhr, status, error) {
if (xhr.status > 0) document.write("got error: " + status);
}
});
}
</script>
Here's the testphp.php file:
<?php
$zipcode = $_GET["zipcode"];
echo '<div><p>'.$zipcode.'</p></div>';
?>
The above results in a blank page of "got error: error"
What am I doing wrong?
You can just do..
<?php
if (isSet ($_GET ['zipcode']))
{
$zipcode = $_GET["zipcode"];
echo '<div><p>'.$zipcode.'</p></div>';
exit;
}
?>
html
<div>
<form name="zipform">
<p style="color:#cccccc;">Enter your Zipcode: <br><input type="text" name="zipcode" id='zipcode'>
<input type ="Button" Value="Search Providers" id="getZip">
</p>
</form>
</div>
<div id="result"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready (function (){
$("#getZip").on ("click", function (e){
var zip = $("#zipcode").val ();
$.ajax({
url: "test1.php",
data: {zipcode: zip},
type: "GET",
success: function (d) {
document.write("content of the executed page: " + d);
$("#result").html(d);
},
error: function (xhr, status, error) {
if (xhr.status > 0) document.write("got error: " + status);
}
});
e.preventDefault;
});
});
</script>
Kinda my way of doing it, yet it works wonders.
try $.get
this is easier
$.get(
'testphp.php',{'zipcode':zip}
).done(function(data)
{
$("#result").html(data);
})
you want send get method without var
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.