HTML search form allow input text immediately [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Focus Input Box On Load
i need a HTML search form that allow input text immediately. Same as Google. we needn't click to input text into search form

What you are looking for can be achieved a few different ways. The easiest would be via a AJAX POST via jquery. I'll give you a little example:
Let's pretend your search input has a name attribute such as "keywords"
$(function(){
$("input[name='keywords']").keyup(function(){
$(".search_results").slideUp("normal", function(){
$.ajax({
type: "POST", url: "searchquery.php",
data: {keywords: $(this).val()},
success: function(response){
if(response != "error")
{
$(".search_results").html(response);
$(".search_results").slideDown();
}
else
{
alert("Error Searching. Please refresh the page and try again.");
}
}
});
});
});
});
Then you need to have searchquery.php handle searching the database and returning the data in html format. Maybe something like this:
if(trim($_POST["keywords"]) != "")
{
$keywords = mysql_real_escape_string($_POST["keywords"]);
//search the DB for maybe 5 top results and return them in something like a HTML list:
$results = '<ul><li>first</li><li>second</li></ul>';
die($results);
}
Your on your own for formatting the div or HTML object with the class "search_results" defined on it.
Also, I would advise adding a timer, so that each time the "keyup" function is hit, it records the time and make a minimum of _ amount of time before the next call to the file is allowed. That way the PHP file doesn't get 5 calls when someone writes 1 word.

Related

AJAX stacks response from PHP [duplicate]

This question already has answers here:
Jquery: How to clear an element before appending new content?
(4 answers)
Closed 2 years ago.
I've recently started using and learning JS and jquery. I'm sending a user email from a form to my PHP page to check if any user exists in DB via ajax, then I get a response from my PHP file if the user exists or not and display the text in a div. It's working fine, but because the page doesn't refresh when the button for sending form data is pressed, ajax just stacks the response from PHP.
I probably need to clear the response every time the button is clicked first and then append the response but I can't find the right command for it :/
JS
function sendnewpass() {
var email = document.getElementById("useremail").value;
$.ajax({
type : "POST",
url : "login.php", //my php page
data : { passemail : email }, //passing the email
success: function(res){ //to do if successful
$("#emailsentmsg").append(res); //the the div that i put the response in
}
});
}
Use empty() like:
$("#emailsentmsg").empty().append(res);
Use the following:
$("#emailsentmsg").html("");
$("#emailsentmsg").append(res);
Or shorter (thanks #Ivar):
$("#emailsentmsg").html(res);

None live search Data using Ajax?

Hello I am currently working on a project and have managed to connect a very big size database to a website and use ajax live search to search for data from the database. However I have been looking everywhere to find a none live version of the ajax live search. The current one displays all the data from the database on the webpage which is fine if i have small data in the database but I want the page to only show data when user searches and enters or just when searches. Same functions as what the current ajax live search does just without having to display data on the webpage without user searching first. This is the javascript code from ajax live search:
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
I am wondering what change i can make to make it so when i visit the page no data is being displayed unless i search using the searchbox ?
To avoid loading data before a search is made, you need to remove the function call at the beginning of your script:
$(document).ready(function(){
load_data(); // this line needs to be removed
...
}
When you explicitly call a function, it gets executed. Being wrapped in $(document).ready() it's instructing the browser to run the function when the page loads.
If you wish to remove the data once the search box is cleared, you need to modify your event handler like so:
if (search != '') {
load_data(search);
} else {
// this is where "load_data();" used to be
$('#result').html('');
}
This replaces any content that might have been appended to the displaying element in a previous search.

How to serialize dynamic form data to keep maximum UI flexibility?

Due to the nature of my current project, I often find myself having to create HTML <form> elements which must support dynamic add/remove functionality of items for posting collections to the server.
My issue is that I find myself constrained by the name attribute of the form elements because I have to keep track of indices, ex.: Room[1].Tourists[0].Name. This is giving me hard times when I would like, for example, to remove an existing input element from the beginning.
I am currently building these dynamic forms with react.js which is enabling great flexibility, but I was wondering if there was some way that I could collect form data on submit event and just serialize it to match the expected model in the controller's action and post it?
Okay so you just want to solution about this i think you were stuck somewhere in your code that's why i am asking about the sample code no worry back to this try this:
<script type="text/javascript">
$(document).ready(function () {
$("#btn_submit").on('click', function () {
$.ajax({
type: "POST",
url: "Give URL here",
async: false,
data: $("#FormID").serialize(),
success: function (result) {
//Do what you want
},
error: function (response) {
//Do what you want
}
});
});
});
</script>

How can I use jQuery to run MySQL queries?

Is it possible to run a MySQL query using jQuery? I'm trying to emulate the functionality of voting on SE sites.
The vote counter on SE automatically updates without the need to reload the page (which is what I currently have, a hidden form that re-submits to the current page but runs a small block on PHP that updates the score of a question in the database). I'm assuming that is being done using Javascript/jQuery seeing as it is dynamic.
How can I do this? Is there a library which makes it easy and simple (like PHP)?
You can use ajax to call a server page (PHP / ASP /ASP.NET/JSP ) and in that server page you can execute a query.
http://api.jquery.com/jQuery.ajax/
HTML
<input type='button' id='btnVote' value='Vote' />
Javascript
This code will be excuted when user clicks on the button with the id "btnVote". The below script is making use of the "ajax" function written in the jquery library.It will send a request to the page mentioned as the value of "url" property (ajaxserverpage.aspx). In this example, i am sending a querystring value 5 for the key called "answer".
$("#btnVote").click(function(){
$.ajax({
url: "ajaxserverpage.aspx?answer=5",
success: function(data){
alert(data)
}
});
});
and in your aspx page, you can read the querystring (in this example, answer=5) and
build a query and execute it againist a database. You can return data back by writing a Response.Write (in asp & asp.net )/ echo in PHP. Whatever you are returning will be coming back to the variable data. If your query execution was successful, you may return a message like "Vote captured" or whatever appropriate for your application. If there was an error caught in your try-catch block, Return a message for that.
Make sure you properly sanitize the input before building your query. I usually group my functionalities and put those into a single file. Ex : MY Ajax page which handles user related stuff will have methods for ValidateUser, RegisterUser etc...
EDIT : As per your comment,
jQuery support post also. Here is the format
$.post(url, function(data) {
alert("Do whatever you want if the call completed successfully")
);
which is equivalent to
$.ajax({
type: 'POST',
url: url,
success: function(data)
{
alert("Do whatever you want if the call completed successfully")
}
});
This should be a good reading : http://en.wikipedia.org/wiki/Same_origin_policy
It's just a few lines in your favorite language.
Javascript
$.post('script.php', { id: 12345 }, function(data) {
// Increment vote count, etc
});
PHP (simplified)
$id = intval($_POST['id']);
mysql_query("UPDATE votes SET num = num + 1 WHERE id = $id");
There are many different ways to accomplish this.

how to use JSON for an error class

Hey all. I was fortunate enough to have Paolo help me with a piece of jquery code that would show the end user an error message if data was saved or not saved to a database. I am looking at the code and my imagination is running wild because I am wondering if I could use just that one piece of code and import the selector type into it and then include that whole json script into my document. This would save me from having to include the json script into 10 different documents. Hope I'm making sense here.
$('#add_customer_form').submit(function() { // handle form submit
The "add_customer_form" id is what I would like to change on a per page basis. If I could successfully do this, then I could make a class of some sort that would just use the rest of this json script and include it where I needed it. I'm sure someone has already thought of this so I was wondering if someone could give me some pointers.
Thanks!
Well, I hit a wall so to speak. The code below is the code that is already in my form. It is using a datastring datatype but I need json. What should I do? I want to replace the stupid alert box with the nice 100% wide green div where my server says all is ok.
$.ajax({
type: "POST",
url: "body.php?action=admCustomer",
data: dataString,
success: function(){
$('#contact input[type=text]').val('');
alert( "Success! Data Saved");
}
});
Here is the code I used in the last question, minus the comments:
$(function() {
$('#add_customer_form').submit(function() {
var data = $(this).serialize();
var url = $(this).attr('action');
var method = $(this).attr('method');
$.ajax({
url: url,
type: method,
data: data,
dataType: 'json',
success: function(data) {
var $div = $('<div>').attr('id', 'message').html(data.message);
if(data.success == 0) {
$div.addClass('error');
} else {
$div.addClass('success');
}
$('body').append($div);
}
});
return false;
});
});
If I am right, what you are essentially asking is how you can make this piece of code work for multiple forms without having to edit the selector. This is very easy. As long as you have the above code included in every page with a form, you can change the $('#add_customer_form') part to something like $('form.json_response'). With this selector we are basically telling jQuery "any form with a class of json_response should be handled through this submit function" - The specific class I'm using is not relevant here, the point is you use a class and give it to all the forms that should have the functionality. Remember, jQuery works on sets of objects. The way I originally had it the set happened to be 1 element, but every jQuery function is meant to act upon as many elements as it matches. This way, whenever you create a form you want to handle through AJAX (and you know the server will return a JSON response with a success indicator), you can simply add whatever class you choose and the jQuery code will take over and handle it for you.
There is also a cleaner plugin that sort of does this, but the above is fine too.
Based on your question, I think what you want is a jQuery selector that will select the right form on each of your pages. If you gave them all a consistent class you could use the same code on each page:
HTML
<form id="some_form_name" class="AJAX_form"> ... </form>
Selector:
$('form.AJAX_form")

Categories