I am trying get get TypeAhead functionality on a search textbox. I have 2 radio buttons on the form if one of them is selected I need the type-ahead functionality to add the ist of masters to the search box.
//html
<li> #Html.TextBox("SearchTitle") </li>
//JavaScript
if ($('input[name=SearchType]:checked').val() == "m") {
var availableMasters = ["ActionScript",
"AppleScript",
"Asp"];
$.ajax({
cache: false,
type: "GET",
url: "#(Url.Action("Get", "Masters"))",
success: function (data) {
availableMasters = data.list;
},
error: function () {
alert('No Master Available.');
}
});
$("#SearchTitle").autocomplete({
source: availableMasters
});
}
My issue is that the form is binding the availableMasters before the ajax call, so the search textbox always has the static text array that I am adding at the begining with 3 fields. I am getting the correct list of masters in the (data.list) but it never shows up in the textbox.
Is there a way to bind the list once the ajax call get the list of masters?
Thanks for the concerns...
wrap it in a function, say init, and call that function on the success of your ajax call.
function initSearch(){
$("#SearchTitle").autocomplete({
source: availableMasters
});
}
if ($('input[name=SearchType]:checked').val() == "m") {
var availableMasters = ["ActionScript",
"AppleScript",
"Asp"];
$.ajax({
cache: false,
type: "GET",
url: "#(Url.Action("Get", "Masters"))",
success: function (data) {
availableMasters = data.list;
initSearch();
},
error: function () {
alert('No Master Available.');
}
});
}
Related
I am currently implementing the autocomplete bootstrap control from here. I only want to populate the source when characters are more than 2. I'm wondering how do I populate my type ahead source after a successful ajax call.
https://github.com/bassjobsen/Bootstrap-3-Typeahead.
var $input = $(".typeahead");
$input.keyup(function () {
var count = $input[0].value.length;
if (count >= 3) {
$.ajax({
type: "GET",
url: '/Home/GetProducts',
data: {
characters: $input[0].value
},
success: function (response) {
$input.typeahead({
source: response,
autoSelect: true
});
}
});
}
});
When I put a breakpoint at response, this is the result
So my ajax query works, but the type ahead doesn't populate with the results and aren't searchable.
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;
}
});
});
ajax/javascript problem:
I have an app which consist of multiple forms. What i want to achieve is to make a generic js function to submit forms to their respective controllers by getting form id.. I m successfully getting form ids in form_id variable but m unable to use them. I tried replacing $('patient_form') with form _id and got following error: TypeError: form_id.on is not a function
Here is the following code for better understanding of the problem:
$(function () {
var form = document.getElementsByTagName("form");
var form_id = "'#" + form[0].id + "'";
form_id.on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'Controllers/c_insertPatient.php',
data: $('#patient_form').serialize(),
success: function (result) {
alert(result);
}
});
});
});
The way you have it form_id is a string.
Try:
var form_id = $("#" + form[0].id);
$.ajax is a jquery function. If you want to use jquery (which in this case I think you should), then do it as follows:
$('form').on('submit', function () {
$(this).preventDefaults();
$.ajax({
type: 'post',
url: 'Controllers/c_insertPatient.php',
data: $('#patient_form').serialize(),
success: function (result) {
alert(result);
}
});
});
In addition to the other answers, you want to keep your form ID dynamic, right, so you can insert whatever values you want?
$(function () {
var form = document.getElementsByTagName("form");
// note you have to convert to jQuery object
var form_id = $("#" + form[i].id); // i, so you can put in the id for any form
form_id.on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'Controllers/c_insertPatient.php',
data: $(this).serialize(), // again, keep generic so this applies to any form
success: function (result) {
alert(result);
}
});
});
});
You should set the event listener to the element, not the string of the id of the element. Also I presume you have jQuery because you are using $. Set an id on the form in the HTML. Then:
$(function () {
var form = $('#theFormId');
form.submit(function(event) {
$.post('Controllers/c_insertPatient.php', form.serialize(), function() {
alert('success');
});
event.preventDefault();
});
});
I have two buttons on the form I'm getting, this first piece of coce allow me to know which was the button clicked by getting the id of it.
var button;
var form = $('.register_ajax');
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
});
and this other send the form data through AJAX using the info already obtained from the button using the script above.
form.bind('submit',function () {
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
cache: false,
dataType: 'json',
data: form.serialize() + '&' + encodeURI(button.attr('name')) + '=' + encodeURI(button.attr('value')) ,
beforeSend: function() {
//$("#validation-errors").hide().empty();
},
success: function(data) {
if(data.message == 0){
$("#fave").attr('src','interactions/favorite.png');
$("#favorite").attr('value',1);
console.log(data.errors);
}
if(data.message == 1)
{
$("#fave").attr('src','interactions/favorite_active.png');
$("#favorite").attr('value',0);
}
if(data.message == "plus")
{
$("#vote_up").attr('class','options options-hover');
$("#vote_down").attr('class','options');
console.log(data.message);
}
if(data.message == "sub")
{
$("#vote_down").attr('class','options options-hover');
$("#vote_up").attr('class','options');
console.log("sub");
}
},
error: function(xhr, textStatus, thrownError) {
console.log(data.message);
}
});
return false;
});
The problem is that the data is not being passed to the ajax function, the button info is being saved on the button var, but it's not being obtained at time on the ajax call to work with it (or at least that is what I think). I'd like to know what can I do to make this work, any help appreciated.
1st edit: If I get the button data directly like button = $('#vote_up'); it doesn't work either, it only works if I get the button directly like this but without using the function.
2nd edit: I found the solution, I posted below.
var button is in the scope of the .on('event', function(){})
You need to declare the variable in the shared scope, then you can modify the value inside the event callback, i.e.
var button,
form = $('.register_ajax');
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
});
You are being victim of a clousure. Just as adam_bear said you need to declare the variable outside of the function where you are setting it, but you are going to keep hitting these kind of walls constantly unless you dedicate some hours to learn the Good Parts :D, javascript is full of these type of things, here is a good book for you and you can also learn more from the author at http://www.crockford.com/.
I Found the solution, I just changed a little bit the click function like this:
var button;
var form = $('.register_ajax');
var data = form.serializeArray();
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
data.push({name: encodeURI($(this).attr('name')), value: encodeURI($(this).attr('value'))});
form.submit();
});
using e.preventDefault(); and form.submit(); to send the form. also I changed the data.serialize to serializeArray(); because it's more effective to push data into the serializeArray(). in the second script I just changed the data.serialize() and used the data variable that I already filled with the serializeArray() and the data.push():
form.bind('submit',function () {
alert(button);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
cache: false,
dataType: 'json',
data: data,
//here goes the rest of the code
//...
});
return false;
});
it worked for me, it solved the problem between the click and submit event that wasn't allowing me to send the function through ajax.
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");
}
});
}
});
}
});