How to property update bootstrap autocomplete source after Ajax call - javascript

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.

Related

How to hook into woocommerce_after_checkout_validation depending on the AJAX JSON results

I added a custom input to the WooCommerce checkout form and it receives a JSON data from an URL. If the user's input, was valid, the received JSON will will have a true value, if not, it will have a false value in it.
I already did that using the AJAX JQuery function.
What I want?
When user clicks on the Place order button, besides other potential errors, I want to add a validation error to the WooCommerce if the received JSON data is false. If the user corrected the input and received true value from URL, when clicking on the Checkout button again, I want the error to be cleared.
How can I hook into woocommerce_after_checkout_validation and add/remove validation errors on the fly with JS/JQuery? I added some comments to the code to make my problem a bit clearer.
//custom-wc-checkout.js
$(document).on("input", "#custom_input", function () {
console.log($(this).val());
var value = $(this).val();
var isValidCode = false;
function checkCode(value, callback) {
$.getJSON(
"http://localhost/special/wp-json/wp/v2/posts/" + value,
function (jsonData) {
isValidCode = jsonData.content.protected;
callback(isValidCode2);
}
);
}
checkCode(value, function (isValidCode) {
// Is it true or false
console.log(isValidCode);
$.ajax({
url: "http://localhost/special/wp-admin/admin-ajax.php",
async: false,
type: "POST",
data: {
action: "validate_e_code",
json: isValidCode,
},
dataType: "text",
success: function (response) {
console.log("success");
console.log(response);
json = data.json;
},
error: function () {
console.log("error");
},
});
});
});
PHP code:
//Ajax.php
$isValid = false;
function validate_e_code()
{
global $isValid;
$isValid = $_POST["json"];
//Update: I tried to add a custom session as CBroe advised,
//but I don't know how to use the session to tell the WooCommerce
//update the validation results depending on the session value.
WC()->session->set('the_field_name', $isValid);
echo json_encode(WC()->session->get('the_field_name'));
echo $isValid;
die();
}
//$isValid remains false, even if the input code is valid and $_POST["json"]'s value is true
//So it always displays the error
if ($isValid == false) {
add_action('woocommerce_after_checkout_validation', 'validate_json', 10, 2);
}
function validate_json($fields, $errors)
{
$errors->add('validation', 'Your code is not valid!');
}
PS I used the WordPress REST API for testing. It doesn't matter, only note that the JS code returns a true or false value, depending on what user enters in #custom_input (custom field) and then we pass the Boolean value to the validate_e_code PHP function.

Calling ajax request continually until a certain search request is found

I am trying to keep sending AJAX GET requests to a certain page that inputs from a cgi script until a specific set of keystrokes shows up.
However, my requests aren't coming up continuously, in fact they aren't even taking place when I am using a function and trying to call the function. I had to use the complete with the success, because for whatever reason, with the success I could not properly store the value retrieved.
Here is what I have:
function posts() {
$.ajax({
type: "GET",
url: 'http://checkvaluestatus.sh',
success: function(data) {
alert(data_response.responseText);
},
complete: function(data_response) {
alert(data_response.responseText);
var viewport = data_response.responseText;
var version = viewport.match(/Release:[^=]*/);
if (version != null) {
console.log(version);
} else {
posts();
}
},
error: function() {
console.log('failed');
posts(); //calling the ajax again.
}
});
Is there not a way to keep sending requests based on a condition being met and having the value still stored?
This is my AJAX call that worked to print the value:
$.ajax({
url: 'http://checkvaluestatus.sh',
type: "GET",
dataType: "json",
success: function(data) {
alert(data_response.responseText);
},
complete: function(data_response) {
alert(data_response.responseText);
var viewport = data_response.responseText;
var version = viewport.match(/Release:[^=]*/);
document.write(version);
},
});
salam,
the value you are looking for in success function is the 'data' ,not "data_response.responseText" because in "success" function data is your response text ,but in the "complete" function "data_response" is a jqXHR object contain more information.
to print your text in success function replace
alert(data_response.responseText);
by
alert(data);
for more details "jquery.ajax"

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;
}
});
});

JS AJAX typeahead result ordering / race condition

I'm encountering an issue with AJAX typeahead / live-update as-you-type views which are returning results out of order. Does anyone have any experience with methods of dealing with this?
The problem:
Type in a query, such as "search term".
Even with some debouncing, it's likely to fire off a few AJAX calls as you type, say "sea", and "search term".
The search result set for sea is larger than the one for search term, and so its AJAX request actually completes after the newer query.
The resulting problem: You type in search term, but the correct results blip across the screen for a second only to be replaced by the results for sea.
Bare-bones jQuery pseudocode:
$('body').on('keyup', '#searchBox', function(){
query = $("#searchBox").val();
$.ajax({
type: 'GET',
url: '/endpoint.php?query=' + query,
success: function (response) {
// Update view here
$("#view").html(response.text);
}
});
});
Angular pseudocode:
// HTML
<input ng-keyup = "search()" ng-model="searchBox" placeholder = "Search">
{{results}}
// JS
$scope.search = function(){
$http({
method: 'GET',
url: '/endpoint.php?query=' + $scope.searchBox
}).then(function successCallback(response) {
$scope.results = response.data;
}, function errorCallback(response) {
console.log(response);
});
}
Top stop the race condition you can keep a reference to the last AJAX request you made and then abort() it when a new key is pressed. It would also be worthwhile putting a delay before making the request so that you don't send a request for every key pressed, but for when typing ends. Try this:
var previousRequest, previousTimer;
$('body').on('keyup', '#searchBox', function() {
previousRequest && previousRequest.abort();
clearTimeout(previousTimer);
previousTimer = setTimeout(function() {
previousRequest = $.ajax({
type: 'GET',
url: '/endpoint.php',
data: {
query: $("#searchBox").val()
},
success: function (response) {
// Update view here
$("#view").html(response.text);
}
});
}, 200);
});
200ms between keystrokes is plenty, but you can shorten if you want to increase the responsiveness of the requests.

jquery and ajax request

I have js function which sends ajax request to the controller and succ. return result and append that result into desired div inside partial page. Now I want to implement pagination and I'm using $("#dataList").on("click", ".pagedList a".getPage); to listen when user click on pagination links to determine which page number is clicked
var getPage = function () {
var $a = $(this);
GetTabData(a);
return false;
}
and finally I'm sending pagenumber to the next function which sends pagenumber together with activeTab variable to the controller
function GetTabData(xdata, pageNumber) {
$.ajax({
url: ('/Home/GetTabData'),
type: 'POST',
contentType: 'application/json',
dataType: 'html',
data: JSON.stringify({ activeTab: xdata, page: pageNumber }),
success: function (result) {
$("[id^='tab-'] div").remove();
var currentTab = $("#tab-" + xdata).html(result);
},
error: function () { alert("error"); }
});
}
Something is definit. wrong here cause on controller side I'm using
Request.IsAjaxRequest()
to allow only ajax request to paginate data and I'm getting Not ajax request. Once more, If I remove pagination option completly and send just activeTab everything works.
Any thoughts?
Your GetTabData function takes 2 arguments: xdata and pageNumber but when calling it you are passing only one:
var $a = $(this);
GetTabData(a);
So you probably are getting a javascript error and the return false statement is never reached.

Categories

Resources