jQuery and AJAX?
I'm making a simple form which has 5 input
elements for parts of an address. I use jQuery to build and send an AJAX request to a PHP file on my server. For some reason my jQuery is not properly able to read the values from my input
elements. What could be wrong?
Here is my jQuery:
$('#submitButton').click(function(){
$('#BBRequestBox').html('<img src="images/loading.gif" />');
alert('Info: ' + $('#name').val() + ' ' + $('#street').val() + ' '
+ $('#city').val() + ' ' + $('#state').val() + ' '
+ $('#zip').val() + ' ');
$.ajax({
type: "POST",
url: "./bbrequest.php",
data: {
name: $('#name').val(),
street: $('#street').val(),
city: $('#city').val(),
state: $('#state').val(),
zip: $('#zip').val()
},
success: function(msg){
$('#BBRequestBox').html('<p>' + msg + '</p>');
},
error: function(XMLHttpRequest, textStatus, errorThrown){
$('#BBRequestBox').html('<p> There\'s been an error: '
+ errorThrown + '</p>');
}
});
return false;
});
Here is my HTML:
<div id="BBRequestBox">
<form action="#">
<label>Name:</label><input type="text" name="name" id="name" class="textbox" />
<label>Street:</label><input type="text" name=开发者_运维技巧"street" id="street" class="textbox" />
<label>City:</label><input type="text" id="city" class="textbox" />
<label>State:</label><input type="text" id="state" class="textbox" />
<label>Zip:</label><input type="text" id="zip" class="textbox" />
<input type="submit" value="Send Me a Bitachon Builder!" id="submitButton" />
</form>
</div>
EDIT:
Live example at Bitachon.org/new. Click on "Get the Bitachon Builder. (Leftmost footer link)
You are replacing the html of your requestbox with the loading gif. So the inputs don't exist anymore when you're trying to access them.
$('#BBRequestBox').html('<img src="images/loading.gif" />');
you could do something like this:
$('#BBRequestBox').prepend('<img src="images/loading.gif"/>').find('form').hide();
OK, so because you are replacing the contents of the request box with your loading image, you are actually removing the tags that contained data PRIOR to processing them... as such, when your jQuery function looks for the elements, it cannot find them and for that matter their values...
If you remove this line: $('#BBRequestBox').html('<img src="images/loading.gif" />');
it will work...
I'm working on a way to get that loading image there in the mean time <- Looks like you already have the solution for that below :P
It should work. My guess is the input elements don't exist when you are trying to attach your click handler. Try wrapping your js in:
$(document).ready(function(){
// Your stuff goes here
});
I don't know why your code isn't working, but I suggest looking into the serialize() jQuery function instead of manually constructing your data object.. It will reduce the amount of code you need to write, which could eliminate your bug.
And we all know that coding smaller is a good idea. :-)
精彩评论