I'm trying to make an AJAX search for a website.
HTML:
<form id="search" method="post" action="search.php">
<input type="text" name="search" />
<input type="image" name="submit" alt="search" src="images/buttons/search.gif" />
</form>
$(function() {
var search_text = '';
$('form#search input[name=submit]').click(function() {
search_text = $('form#search input[name=search]').val();
$.get('../search.php',{ s: search_text });
return false;
});
});
In the search.php file I have the following:
<?php
$search = $_GET['s'];
if (isset($_POST['submit_x'])) {
$search = $_POST['search'];
$search = str_replace(' ','',$search);
$search = strtolower($search);
if($search == 'kingbabychosenheart' || $search == 'chosenheart' || $search == 'beltchosenheart') {
echo "<meta http-equiv='refresh' content='0;url=chosen_heart.php'>";
} else {
echo "<meta http-equiv='refresh' content='0;url=not_found.php'>";
}
}
?>
But this doesn't work. What else do I have to do to make this work?
Thanks
Well, first of, your form will not be usable with Javascript disabled. I hope you know that, since your form has no submit element per se.
With that in mind, you should use the submit()
event and attach it to the form, then trigger that event when the image is clicked.
$(function() {
var search_text = '';
$('#search').bind('submit',function() {
search_text = $('input[name=search]', $(this)).val();
$.get('../search.php',{ s: search_text });
return false;
});
$('#search img[name="submit"]').click(
$('#search').trigger('submit');
});
});
Or better still, use the jquery form plugin.
One problem is that get
has no callback - you ping the server, but do nothing with the reply:
$.get("/search.php", { s: search_text }, function(data){
alert("Data Loaded: " + data);
});
if you want to send data through AJAX, you must cancel the event by returning false in submit event in the form, to avoid send double data;
<form id="search" method="post" action="search.php" onsubmit="return false;">
<input type="text" name="search" />
<input type="image" name="submit" alt="search" src="images/buttons/search.gif" />
</form>
$(function() {
var _myform = $("form#search");
$(_myform).find("input[name='submit']").click(function(e) {
e.stopPropagation();
var search_text = $(_myform).find("input[name='search']").val();
$.get("../search.php",{ s: search_text });
});
});
in the PHP code, if you send data via GET, you will not receive anything for POST.
For that you should do the following:
$(function() {
var _myform = $("form#search");
$(_myform).find("input[name='submit']").click(function(e) {
e.stopPropagation();
var search_text = $(_myform).find("input[name='search']").val();
$.post("../search.php?s="+search_text,{ "submit_x": "" });
});
});