Use geocomplete function after ajax event - javascript

I have a button that adds an input box where you can type an address. For the address, I'm using the geocomplete plugin. In all input boxes that were not generated with ajax the geocomplete works. If the input was generated by ajax, it doesnt.
This is my code to generate the input box:
$('.add-drop').on('click', function(){
$.ajax({
url : '/ajax/get-location-input',
success : function(data){
$('#additional-drop').append(data);
}
});
});
This is my geocomplete code:
$(".get-location").geocomplete({
details : "form",
types : ["geocode", "establishment"]
}).bind("geocode:result", function(event, result){
console.log(result);
});
The problem is not with the class. I was trying to do something like $(".get-location").on("geocomplete"... but it wasn't working. Any idea? Thanks

AJAX is Asynchronous (Asynchronous JavaScript and XML) That means it might execute after the main code has been finished processing
$.ajax({
url: '/ajax/get-location-input',
success:function(data){
alert(data);
}
});
alert('Hi ');
In this case, Hi will alert first, then data. In your case, the inputs might not even be generated yet and so the geolocation code won't see them
The correct code:
$.ajax({
url: '$('#additional-drop').append(data);',
success:function(data){
$('#additional-drop').append(data);
$(".get-location").geocomplete({
details: "form",
types: ["geocode", "establishment"]
});
}
});
Will make the code run after the data has been fetched from the server
This is me recommended way to do this:
(function () {
$.fn.addGeolocation = function () { this.geocomplete({ details: "form", types: ["geocode", "establishment"] }).bind("geocode:result", function(e, a){ console.log(a); }); }
$.get('/ajax/get-location-input', function (a) {
$('#additional-drop').append(data);
$(".get-location").addGeolocation();
});
/* You may or may not need this */
window.onload = function () { $(".get-location").addGeolocation(); }
}());

Related

AJAX call before document.ready

I have a requirment where in AJAX call has to happen before document.ready and the response from the AJAX call will be used to update some HTML elements.
So I have something like below:
var ajaxget = $.ajax({
type: 'GET',
url:'/xxx/get',
success: function(resp) {
//logic
}
});
$(document).ready(function(){
$.when(ajaxget).done(function(resp) {
//do ur logic
$(documet).trigger("yyyy");
});
});
//the above part is common across pages and placed in the <head>
//below one goes into multiple places based on the pages
$(document).ready(function(){
$(document).on('yyyy', function() {
});
});
The issue is the trigger event "yyyy" doesn't get executed in IE and intermittently on other browsers as well. Please help!
Might be better to use then() instead of success to be sure that whatever happens in success is completed before the $.when.done
Note that success is not part of the promise chain
Try:
var ajaxget = $.ajax({
type: 'GET',
url: '/xxx/get'
}).then(function(resp) {
//logic
return resp;
});
$(document).ready(function() {
ajaxget.then(function(resp) {
//do ur logic
$(documet).trigger("yyyy");
});
});
But also note you are triggering the event before you register it also if the order shown in question is correct
This code works for me. Simply i defined "yyyy" event before triggering.
$(document).ready(function () {
$(document).on("yyyy", function () {
console.log('triggered');
});
$.ajax({
type:'GET',
url:'some.jsp',//your url
success:function(resp){
//logic
$(document).trigger("yyyy");
console.log(resp);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

wordpress function is not being executed

I have this button
<button class="button1" id="myid1">Activate</button>
when user click this button then this jquery executes and we are getting alert also.
jQuery(document).ready(function($) {
$(\'#myid1\').click(function(e){
e.preventDefault();
var $el = $(this).parents().eq(1);
remove_element($el);
var data1 = {
action: \'enable_function1\',
};
$.post(ajaxurl, data1, function(response) {
alert(\'Congratulations,Activated' \');
}); });
});
here is my WordPress function
function enable_function1() {
add_filter('mod_rewrite_rules', 'someotherfunction');
}
but nothing is being written by mod_rewrite_rules
in your wordpress backend you need to do this. The action is not the name of the function, it's used by wordpress to identify which function to execute
function your_function() {
add_filter('mod_rewrite_rules', 'someotherfunction');
}
add_action("wp_ajax_enable_function1", "your_function");
add_action("wp_ajax_nopriv_enable_function1", "your_function");
check this for more details :
https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)

Search on keyup and document ready using Ajax

I am trying to make search function based on Ajax/Jquery.
My web app shows the data of service requests from the database. I want to make searchbar for my app as follows:
show all service request on the table initially.
If something is typed on the searchbar, it searches data and load those data to the table.
Finally if user deletes anyword from searchbar it will show all data as stated on No.1
I managed doing second and third function but I am having issues with the first one.
$(document).ready(function(){
$('#search_text').keyup(function(){
var txt = $(this).val();
if(txt != '') {
$.ajax({
url:"ajax/fetchRequests.php",
method:"post",
data:{search:txt},
dataType:"text",
success:function(data) {
$('#result').html(data);
}
});
}
else if(txt == '') {
$.get("ajax/readRequests.php", {}, function (data, status) {
$("#result").html(data);
});
}
});
});
Here is another script that i have worked on trying:
$(document).ready(function(){
var txt = $('#search_text').val();
if(txt != ''){
$.ajax({
url:"ajax/fetchRequests.php",
method:"post",
data:{search:txt},
dataType:"text",
success:function(data) {
$('#result').html(data);
}
});
}
else if(txt == '') {
$.get("ajax/readRequests.php", {}, function (data, status) {
$("#result").html(data);
});
}
});
All my features are working except for the search functions. Any tips or critics are welcome, thank you very much in advance.
I suggest you do two things, 1) use the suggested .on() and 2) use only one ajax function to simplify things. The idea is to funnel your calls through one function so that you know if something fails, it's not because you messed up the ajax part of the script:
// Create a generic ajax function so you can easily re-use it
function fetchResults($,path,method,data,func)
{
$.ajax({
url: path,
type: method,
data: data,
success:function(response) {
func(response);
}
});
}
// Create a simple function to return your proper path
function getDefaultPath(type)
{
return 'ajax/'+type+'Requests.php';
}
$(document).ready(function(){
// When the document is ready, run the read ajax
fetchResults($, getDefaultPath('read'), 'post', false, function(response) {
$('#result').html(response);
});
// On keyup
$(this).on('keyup','#search_text',function(){
// Get the value either way
var getText = $(this).val();
// If empty, use "read" else use "fetch"
var setPath = (!getText)? 'read' : 'fetch';
// Choose method, though I think post would be better to use in both instances...
var type = (!getText)? 'post' : 'get';
// Run the keyup function, this time with dynamic arguments
fetchResults($, getDefaultPath(setPath), type, { search: getText },function(response) {
$('#result').html(response);
});
});
});
To get initial results hook onto jQuery's document ready event.
var xhr;
var searchTypingTimer;
$(document).ready(function(){
// initial load of results
fetchResults([put your own params here]);
// apply on change event
$('#search_text').on('input', function() {
clearTimeout(typingTimer);
searchTypingTimer = setTimeout(fetchResults, 300);
});
});
function fetchResults($,path,method,data,func)
{
if (xhr && xhr.readyState != 4){
xhr.abort();
}
xhr = $.ajax({
url: path,
type: method,
data: data,
success:function(response) {
func(response);
}
});
}
As Rasclatt mentions you should use jQuery's on method to catch any changes.
Secondly I'd recommend disposing of previous requests when you make new ones, since if you are sending a new one on each character change then for one word many requests will be made. They won't necessarily arrive back in the order you send them. So for example as you type 'search term', the result for 'search ter' may arrive after and replace 'search term'. (welcome to async).
Thirdly since you will send many requests in quick succession I'd only call your fetchResults function after a short time out, so for example if a user types a five character word it doesn't fire until 300ms after the last character is typed. This will prevent 4 unnecessary requests that would just be ignored but put strain on your backend.

'book' textfield does not trigger event in sencha

I have this code Ext.get('book').setValue('1');
Note: Loads the page and book value is set to 1. Not after page load
and book value change to 1.
It sets the book to value 1. But it does not trigger a change event. Is there a way to trigger the change event after page loads?
Edit:
In html script,
<script..>
$(document).ready(function () {
$("book").on("blur", function() {
//calls other function
}); // not called as blur is not invoked
});
</script>
<input id="book" type="book" value="" /><br />
In extjs,
var panel = Ext.create('Ext.grid.Panel', {
id: 'panel',
columns: [
var bookid = "new book";
Ext.Ajax.request({
params: { bookid: bookid},
function: function (response) {
Ext.get('book').setValue(bookid);
// after setValue, book will receive a change event(e.g .blur in html) and changes other functions
}
});
]
});
Your ajax request seems to be malformed, the function: function statement would be the place where you put normally success: function like in the following statement:
Ext.Ajax.request({
url: 'insert-your-http-endpoint-here',
params: {
bookid: bookid
},
success: function(response){
debugger; // -> setting this statement will show that you enter the success statement
Ext.get('book').setValue(bookid);
},
failure: function(response, opts) {
// something went wrong with your request
console.log('server-side failure with status code ' + response.status);
}
});
more info about how to use ExtJS or the specific function, you could find in the documentation (check if you have the correct version, ofcourse) which can be found here
From the above code, you don't need the debugger statement, but it could help if you want to check if you actually get into this code block or not, and what happens when you try to set the value.
Also, don't forget to check your console output when something is not working, maybe there was a problem that would be clearly indicated in the console log

Binding two JQuery and ajax functions

I have the follwoing JQuery/AJAX code:
<script>
$('.warning-dialog').click(function () {
alert($(this).data("id"));
});
$(function () {
//twitter bootstrap script
$("button#delete").click(function () {
$.ajax({
type: "GET",
url: "deleteArticleType.php",
data: { 'typeID': $('.warning-dialog').data("id") },
success: function (msg) {
$("#thanks").html(msg)
$("#form-content").modal('hide');
},
error: function () {
alert("failure");
}
});
});
});
</script>
The first function gets the data-id of a button . The second function calls a PHP page and with the method GET should get the value from the first function.
I tried the code above but it didn't work.
My question is why and how can I fix it?
If these are two separate events, disconnected in time and you want to store the value from the first click and then use it in the second click, then you will have to store it somewhere. There are several options, the simplest being a variable.
$(function () {
var lastClickId;
$('.warning-dialog').click(function () {
lastClickId = $(this).data("id");
});
//twitter bootstrap script
// FIXME: you need to add logic here for what to do if lastClickId isn't set yet
// or create a default behavior in that case
$("button#delete").click(function () {
$.ajax({
type: "GET",
url: "deleteArticleType.php",
data: { 'typeID': lastClickId },
success: function (msg) {
$("#thanks").html(msg)
$("#form-content").modal('hide');
},
error: function () {
alert("failure");
}
});
});
});
Since it looks like you are requiring the first click to happen before the second click can have something to operate on, then you should probably either modify the UI to use different types of controls or you will need to add some error handling if the user doesn't click in the right order.
Actually it should have worked using $('.warning-dialog').data("id")
If your page contains only a single class warning-dialog, you approach will be worked. It seems you're referring this class to many elements.

Categories

Resources