None live search Data using Ajax? - javascript

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.

Related

How to add php file inside the confirm() function from JS

So, I want delete records from database using confirm() function, inside this alert should been shown what will be deleted when "OK" button will be clicked. To sum up, I just want to put php file inside the confirm().
function deleteGame() {
if(confirm('Do you want delete this?')){
$(".deleteButtton").load('deleteGame.php?id=' + $(".deleteButtton").data("id"));
}
}
Hmmm, I guess you must try AJAX Request for deleting record, check the following code for reference.
if (confirm("Do you want this to be deleted?")){
//HERE YOU CAN SHOW SOME PROGRESS WHILE THE JS IS REQUESTING PHP TO DELETE FILE
$.get(
"deleteGame.php",
{
id: $(".deleteButtton").data("id")
},
function (result){
/*ASSUMING THAT YOUR PHP FILE WILL RETURN "deleted" AFTER DELETING RECORD.*/
if (result === "deleted"){
alert('DELETED!); //SOME ACTION AFTER DELETING.
}else{
alert('ERROR'); //SOME ACTION FOR ERROR
}
}
);
}
I WOULD SUGGEST USING POST METHOD INSTEAD OF GET METHOD FOR SECURITY ISSUES.
Whenever you want to run a php function similar to deletion of a db record you have pretty much 2 options.
Open a new page in your browser or redirect a user to a new page.
Open a new page "silently" in a background without user knowing it.
The first option is ok, if you dont mind showing user a different page. For example if you wanted to show a page that would have text in it "Thank you for deleting this record". Achieving this would be really simple, you could just use javascript redirect like this:
if(confirm('Do you want delete this?')){
window.location.href = 'deleteGame.php?id=' + $(".deleteButtton").data("id");
}
However in some cases you want to run the php function without leaving the current page. In cases like this you should use AJAX. My simplification: Using AJAX you can open the php file in the background, run the function and once its done you can run javascript to inform a user the operation was successful.
To achieve this you would need to add the AJAX call like this:
if(confirm('Do you want delete this?')){
$.ajax({
url: "deleteGame.php",
method: "POST",
data: { id: $(".deleteButtton").data("id")},
success: function (result) {
alert("The operation was successful")
}
});
}
And in your deleteGame.php file you would need to listen to incoming data:
$id = $_POST['id'];
//Your own script to delete the record. You can access the record id by $id

How to pass a url variable into an Ajax post script to preload a form input in search field?

I have a webpage that has a dynamic search field that will query a database as you type in the search string (much like a google search with suggestions as you type). This part works via AJAX.
In the results, there are multiple rows of data that are displayed below as data is entered into the search field. What I decided to do is create an edit link on the right side of each row (with pencil icon) that is returned by ajax so I can click to another page for editing the data. Something like this...
<a href="edit.php?id=12&search=Goodyear"><i class="fa fa-pencil" aria-
hidden="true"></i></a>
So lets say that I searched for "Goodyear" in the example search and on row 12, I click the link that takes me to another page. I was wanting to use $_GET["search"] to turn around and create a BACK link to the original AJAX page. I know how to get this far, however, I need help customizing the ajax to reload the original search (which in this example is "Goodyear") when the link is clicked back to the search page. The link on the EDIT page would look something like:
Back to Search Page
But here is the issue. When the user returns, I need the search bar prefilled and the search results listed below. In other words, I want the page to be just like it was when they left prior to going to the edit page. I want AJAX to search the search again on page load just because it visited this url /search.php?search=Goodyear Making the url in the link on the edit page is not a problem for me. But it is when it is clicked to return to original search page.
Here is the AJAX code that does all the heavy lifting on the search.php page.
<script>
$(document).ready(function () {
load_data();
function load_data(query) {
$.ajax({
url: "search.php",
method: "POST",
data: { query: query },
success: function (data) {
$('#brand').html(data);
}
});
}
$('#search_text').keyup(function () {
var search = $(this).val();
if (search != '') {
load_data(search);
}
else {
load_data();
}
});
});
</script>
I know that this search happens on a keyup event and the div called #brand displays the resulting rows of data below the search bar. It actually works well just on the search alone, but leaving the page and clicking back with a url (search.php?search="goodyear") like I mentioned is not doing what I need it to.
When I try to modify it, the search results stop showing. .
I have tried to customize this code to process the url using GET variable within this code that uses POST in the AJAX but I have been been unsuccessful so far. Any ideas on what I need to do?
I found the original page I originally used to make my search page.. here it if anyone wants to look: http://www.webslesson.info/2016/03/ajax-live-data-search-using-jquery-php-mysql.html
This may not be the perfect answer but it does work pretty nicely. Although the only thing it does not do is show the text in the search field when you return to the page. If anyone know how, give the answer... but this is what I did...
I found a nice piece of code that strips out the value of the parameter in the url and then throws it into an array variable. I found it on http://www.designchemical.com/blog/index.php/jquery/8-useful-jquery-snippets-for-urls-querystrings/. Here is the code.
var vars = [], hash;
var q = document.URL.split('?')[1];
if(q != undefined){
q = q.split('&');
for(var i = 0; i < q.length; i++){
hash = q[i].split('=');
vars.push(hash[1]);
vars[hash[0]] = hash[1];
}
}
load_data(vars['search']);
search is the parameter in the url and if it says search.php?search=255 then it returns 255. So I threw that into the load_data argument value and it does the search. The only drawback so far is I haven't figured out how to make the value show in the search bar. I'll keep plugging.
UPDATE: I figured out the text in search box issue with this code:
$('input[name="search_text"]').val(vars['search']);
It put the search parameter back into the search input field like I wanted! One more note, be sure to put the above code above the load_data(vars['search']); may not matter but that is what I did to make it work!
This is what it looked like:
var vars = [], hash;
var q = document.URL.split('?')[1];
if(q != undefined){
q = q.split('&');
for(var i = 0; i < q.length; i++){
hash = q[i].split('=');
vars.push(hash[1]);
vars[hash[0]] = hash[1];
}
}
$('input[name="search_text"]').val(vars['search']);
load_data(vars['search']);

document.getElementById(..) gives null even though element is present

I have the following program in which a user can enter any name in a search box after which I redirect the user to a page called usernameSearchResults.php where I print a list of the usernames obtained in the form of an array from usernamesearch.php. Here is the javascript:
$(window).on('load', function() {
$(".searchBarForm").submit(function(e){
e.preventDefault();
var search=document.getElementsByClassName("search")[0].value;
$.ajax
({
type: 'POST',
url: 'usernamesearch.php',
data:
{
search:search
},
success: function (response)
{
window.location.href="usernameSearchResults.php";
response = JSON.parse(response);
var array_length = Object.keys(response).length;//getting array length
for(var i=0;i<array_length;i++){
if(i==0){
document.getElementById("searchResults").innerHTML=""+response[0].username+"<br>";//i=0
}else{
document.getElementById("searchResults").innerHTML+=""+response[i].username+"<br>";
}
}
window.stop();//stops page from refreshing any further(put here to fix a bug that was occuring)
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
return false;
})
});
This is usernameSearchResults.php(inside tags):
<h1>Username Search Results</h1>
<p id="searchResults"></p>
But the problem is that whenever I go to any other page say index.php and enter the username to be searched, the page redirected to is indeed usernameSearchResults.php but the page is blank and error in the console shown says document.getElementById("searchResults") is null.But if I stay at the page usernameSearchResults.php and refresh it and then search any name again, then the results are correctly obtained. What is the problem here?
I would say that the user is being redirected to usernameSearchResults.php but the JavaScript code is still being executed from the current page, which have no element with id "searchResults" defined.
As #Kashkain said, one way to achieve what you want is to pass your response variable in your redirection url and process it then into your other page.
I think the problem here is that the new document could very well still not have been loaded when you call getElementById.
You could add a listener on your target element which would trigger on the load event. In this event's handler you could execute the operations that are now giving you an error.
I have never done or tried this, but maybe something like this would work:
$('#searchResults').on('load', function() {
//execute code here
});
Or you could add a form to the page with action="target_url" method="post" and send your response data through post by doing form.submit, and place the problematic code into usernameSearchResults.php, which will need to read data from POST - this way you can send your ajax data to the new page

HTML search form allow input text immediately [duplicate]

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.

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