New to AJAX. A little unsure about how to submit a GET request without having the entire page reload.
- User visits
www.example.com/products/
- Types 'Gardening Tools`
- Results load inline with URL changes to
www.example.com/products/results?search=Gardening+Tools
all done without page reloading. - Any user can use the URL
www.example.com/products/results?search=Gardening+Tools
and get the same result.
Note: Bullet point 4 is important. It must not be some hacky way of just adding the parameters to the URL to make it look like that. Some users might want to bookmark (besides that's why I used a GET
request in the first place).
So here is a basic representation of my code that works for a POST
:
The form: your basic submission using POST
, I want this to be GET
.
<form id="submit" action="" method="POST">
<input type="text" name="search"/>
<button type="submit"></button>
</form>
jQuery: Using .ajax()
we send a POST
request to /products/results.php
$('form#submit').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'results.php',
data: "search="+encodeURIComponent($('input[name="search"]').val()),
dataType: 'json',
success: function(data) {
//inject some html into page
}
});
}
results.php: (also just to be sure am I protected against SQL injects here? magic quotes are off).
$query = $_POST['search'];
$query = mysql_real_escape_string($query);
$query = htmlspecialchars($query);
//you get the point: straight forward db connect, query and return as json
So I've tried changing all the POST
s to GET
s but it did not work. Is there a concept I'm not understanding?
I think it could be something to do with the $('form#submit').submit(function (e)
and preventDefault() functions. However preventDefault is required for stopping the page reloading.