Ajax Search as user types - javascript

I have a search feature that I am trying to implement. I would like the user to be able to type their "Search" and ajax fires as the user types to assist with finding their "Search".
I would like the user to be able to type their "Search" and ajax fires as the user types to assist with finding their "Search".
This is what I have; This is working but requires the user to hit search.
jQuery(document).ready(function($) {
// Let us trigger the search if the user clicks on the search button.
$('.btnSearch').click(function(){
makeAjaxRequest();
});
// Let us trigger the search if the user submit the form by an enter.
$('form').submit(function(e){
e.preventDefault();
makeAjaxRequest();
return false;
});
function makeAjaxRequest() {
$.ajax({
url: 'searchAction.php',
data: {name: $('input#name').val()},
type: 'get',
success: function(response) {
$('table#resultTable tbody').html(response);
}
});
}
});

You need to bind your function to the keyup-event of the input field.
Adding the following line of code inside the $(document).ready()-function
$( "#name" ).keyup(makeAjaxRequest);
could do the trick for you.
To only perform the AJAX request on a minimum length of three chars in the input field, you can change your makeAjaxRequest() function like so:
function makeAjaxRequest() {
if($('input#name').val().length > 2) {
$.ajax({
url: 'searchAction.php',
data: {name: $('input#name').val()},
type: 'get',
success: function(response) {
$('table#resultTable tbody').html(response);
}
});
}
}

You probably don't want to do your search on keyup as that would require 5 ajax calls to be made for the user to search for the word "Hello."
Consider the Google search bar: It will automatically show search results when it thinks it knows what you want, but not on every keystroke.
I wrote a little event plugin for jQuery that does this. It's only 20 lines of code fully formatted. Copy it and change it to your liking or use it as is.. Here's an example:
<script src='//raw.githubusercontent.com/Pamblam/textChange/master/textChange.js'>
<script>
jQuery(document).ready(function($) {
$('input#name').textChange(makeAjaxRequest);
function makeAjaxRequest() {
$.ajax({
url: 'searchAction.php',
data: {name: $('input#name').val()},
type: 'get',
success: function(response) {
$('table#resultTable tbody').html(response);
}
});
}
});
</script>
$("input").keyup(function(){
$("#keyup").text("keyup: "+$(this).val());
});
$("input").textChange(function(){
$("#textchange").text("textchange: "+$(this).val());
});
b{display:block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src='//raw.githubusercontent.com/Pamblam/textChange/master/textChange.js'></script>
<b>Type a few words:</b>
<input autofocus />
<div id='keyup'>keyup: </div>
<div id='textchange'>textchange: </div>

Thats it might be posible with Jquery Ui autocomplete.
https://jqueryui.com/autocomplete/

Related

Determine ajax call finished to run another ajax call

In my project I have some select option group which load ajax data depending on previous value. Now I am having problem when I am trying to copy them to another select option group.
here is the scenario
parmanet address Present Address
Division Division
District District
Upzilla Upzilla
Union Union
All of them are select field and after select each field next select option loaded by ajax. I put a checkbox and when user click the checkbox, parmanent address data should copy to present address with all the ajax call.
Now The problem is, the jquery "val" function not working because it runs before the data loaded from ajax. If I put delay to 100 ms, it working, but It's not a proper way. Is there any better way to solve this problem??
This is my code when i change division to load ajax data to division, and other option is same as like this.
$('#divisions').change(function() {
$("#villtable").hide();
$("#villaddform").hide();
$.ajax({
type: 'post',
url: 'GetDistricts',
data: {
get_option:this.value
},
success: function(response) {
document.getElementById("districts").innerHTML=response;
}
});
});
And this is what i tried to copy data to present address group...
$.when( $('.division-prese').val(divi).trigger('change').delay( 100 ) ).then(function() {
$.when( $('.district-prese').val(dist).trigger('change').delay( 100 ) ).then(function() {
$.when( $('.upazilla-prese').val(upaz).trigger('change').delay( 100 ) ).then(function() {
$('.union-prese').val(unio).trigger('change');
});
});
});
i also tried 'done', but still not working.
General idea of extracting the logic and using it in two places, one of which performing the promise chaining.
function loadDistricts ($divisions) {
return $.ajax({
type: 'post',
url: 'GetDistricts',
data: {
get_option: $divisions.val()
},
success: function(response) {
$('#districts').html(response);
}
});
}
//... other methods
var $divisions = $('#divisions');
var $districts = $('#districts');
var $upazillas = $('#upazillas');
$divisions.change(function() {
$("#villtable").hide();
$("#villaddform").hide();
loadDistricts($divisions);
});
//... other change methods
$('.division-prese').val(divi);
loadDistricts($divisions).then(function(){
$('.district-prese').val(dist);
loadUpazillas($upazillas).then(function(){
$('.upazilla-prese').val(upaz);
//call next thing
});
});
try adding return before your call
$('#divisions').change(function() {
$("#villtable").hide();
$("#villaddform").hide();
return $.ajax({
type: 'post',
url: 'GetDistricts',
data: {
get_option:this.value
},
success: function(response) {
document.getElementById("districts").innerHTML=response;
}
});
});

When and when doesn't success: value executes in jQuery Ajax method? (Header location not changed)

I'm submitting a form using jQuery Ajax.
The data is submitted successfully but there's a little problem. When I add the commented statements in this code, the success: function(){} doesn't run (location is not changed).
Q. 1 When I remove those statements, it runs. I don't understand this logic. When does it actually executes and how does checking for xy affects this?
Here's my Ajax code:
$(document).ready(function(){
$("#button").click(function(){
**//FOLLOWING TWO LINES MAKES SUCCESS NOT RUN**
//var **xy**= $("#digits").val();
//if(xy!=""){
$.ajax({
url: "submitform.php",
type: "POST",
data: $('#signupform').serialize(),
success: function(result){
$(location).attr('href', 'login2.php');
},
error: function(){
alert(error);
}
});
// }
});
});
Here's concerned input tag:
<form id="signupform" name="form1" method="post" enctype="multipart/form-data">
<input id="digits" type="text" name="phone" maxlength="10" placeholder="Enter your phone no." required />
......
Q.2 When I write event.preventDefault(); to stop the default action of submit button, the required atrributes of input fields don't work. Why is it so? Can it be solved?
To Question 2:
If you call preventDefault for the event of the click on the submit button, then the default behaviour (initiating the submit) is prevented, so the input fields are not checked.
You have to listen on the submit event of the form instead and prevent the default behaviour of this, because the submit event is send after the input elements are checked and before the form is submitted.
$(document).ready(function() {
$("#signupform").on('submit', function(e) {
e.preventDefault();
//FOLLOWING TWO LINES MAKES SUCCESS NOT RUN**
//var **xy**= $("#digits").val();
//if(xy!=""){
$.ajax({
url: "submitform.php",
type: "POST",
data: $('#signupform').serialize(),
success: function(result) {
$(location).attr('href', 'login2.php');
},
error: function() {
alert(error);
}
});
// }
});
});
When you use jquery ajax there is two types of result:
400 - OK status which be capture by the success function
402 or 500 are internal errors and those will be capture by the error function.
Now, in your error function youre trying to print an error variable that does not exist.
Also, when you use preventDefault you have pass variable that handles de event too cancel.

How to pass form input field value to external page using jquery

I have a form where I would like to pass the value of an text input field to an external page without a form submit event. I would like to field value to become a php variable on the external page.
Here is what I have so far:
<script type="text/javascript">
jQuery(document).ready(function() {
$(function() {
cityField = $('#the_form input[id=city]');
$.ajax({
type: "POST",
url: "external.php",
data:{ city: cityfield },
success: function(data){
console.log(data);
}
});
});
});
</script>
Within the external.php page, I would like to declare the city form field value as a php variable as
$city = $_POST['city'];
To start with
jQuery(document).ready(function() {
and
$(function() {
are equivalent. The $(function() should be something like
$("input[type='button']").click(function() {
so that when you click the button, it runs the ajax request.
I cleaned up the code but the data is not being sent to external.php. It is being set but not posting. Here is my revised code
<script type="text/javascript">
$('#city').blur(function() {
var cityField = document.querySelector('#city').value;
$.ajax({
type: "post",
url: "external.php",
data: {'cityField': cityField },
dataType: "text",
success: function(data, status){
if(status=="success") {
alert("You typed: " + cityField);
}
}
});
});
I dont feel right posting an answer for a single change... But
EDIT: There are actually a few things...
<!-- For .click() -->
Click Me!
<script type="text/javascript">
// $(function() { // Trigger on page load
// $('#doStuff').click(function() { // Trigger on a click
$('#city').blur(function() { // Trigger when the focus on the field is lost (click away, tab to another field, ect)
// $('#city').change(function() { // Trigger when the fields value changes
var cityField = $('#city');
$.ajax({
type: "POST",
url: "external.php",
data:{ 'city': cityField.val() },
success: function(data){
console.log(data);
}
});
});
</script>
Changes:
You dont need jQuery(document).ready(function() {}) AND $(function(){ }). Its the same thing.
Its smart to put a var in front on your variables.
Case is important. cityField and cityfield are not the same thing
You were just sending the whole dom element to your external script. (which I assume you only wanted the contents of the input)
Also, you dont need to look for "an input, with an 'id' attribute , with a value of 'city'". Just look for #city
EDIT:
Your updated code (just putting it here so its easier to see):
<script type="text/javascript">
$('#city').blur(function() {
var cityField=$('#city').val();
$.ajax({
type:"post",
url:"autosuggest.php",
data:{'cityField':cityField },
dataType:"text",
complete:function(data, status) {
alert("You typed: "+cityField);
}
});
});
</script>
Your data will should be available in autosuggest.php as $_POST['cityField'];
Having a status check within the success function, is a little redundant, in my opinion.
It would be better to move the success:function(data,... to a complete:function(data,...

One submit button for multiple forms. Master save strategy,

Picture below shows simplification of the html page layout I am working with. It has 3 forms, every form has it's own submit button and can be submitted individually. At the top of the page "Master Save" is located. This button should save all 3 forms.
Every form have submit() function overloaded and they look like this:
form1.submit(function () {
Form1SubmitOverloaded(this);
return false;
});
Form1SubmitOverloaded = function (form) {
$.post(form.action, $(form).serialize(), function (data) {
//DOM manipulation, etc/
}).fail(function () {
//error parsing etc.
});
return false;
};
After pressing "Master Save" I want to submit forms in order 1 > 2 > 3. But I want Form 2 to wait until form 1 has ended.
Form1 submitted >> Form2 submitted >> Form3 submitted.
$('#masterSave').click(function () {
$('#form1').submit();
$('#form2').submit(); // wait until form1 ended
$('#form3').submit(); // waint until form2 ended
return false;
});
Please provide method to order submits in 'click' function as presented.
Thanks.
.post() method doesn't look to have a synch property. But .ajax() has.
I suggest you use the .ajax() method instead of the .post() shortcut method. That way you could force ajax to be synchronious
$.ajax({
[...]
async : false
}
you can use something like this
Form1SubmitOverloaded();
$.ajax({
type: "POST",
url: test1.php,
data: $( "#form1" ).serialize(),
success: function(){
Form2SubmitOverloaded();
$.ajax({
type: "POST",
url: test2.php,
data: $( "#form2" ).serialize(),
success: function(){
Form3SubmitOverloaded();
$.ajax({
type: "POST",
url: test2.php,
data: $( "#form2" ).serialize(),
success: function(){
alert("All submit successfully");
}
});
}
});
}
});

Using the jQuery validation plugin's submitHandler method properly

first a little bit of documentation from the jQuery validation plugin:
"Use submitHandler to process something and then using the default submit. Note that "form" refers to a DOM element, this way the validation isn't triggered again."
submitHandler: function(form) {
$.ajax({
type: 'POST',
url: form.action,
data: 'current_password=' + form.current_password + '&new_password=' + form.new_password,
success: function(){
alert("succes");
}
});
}
So, naturally my ingenious piece of code isn't working. I'm trying to access the 'action' attribute and the two input fields from the form object, with no luck. How am I supposed to do this?
Try this instead:
submitHandler: function(form) {
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: { current_password : form.current_password.value,
new_password: form.new_password.value }
success: function(){
alert("succes");
}
});
}
Currently instead of submitting the values of the elements it's literally calling a toString on them, so just add .value to get the values. Also we're passing data as an object here so it gets encoded, otherwise if for example the password had a & in it, the post wouldn't be correct.

Categories

Resources