How to create DOM elements on $.Ajax() Success using jquery ? - javascript

i'm creating a dynamic list of checkbox on $.ajax :
function load() {
$.ajax({
type: "POST",
url: "*************",
data: "************",
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function (x, e) { alert(e.responseText); },
success: function (objTrendList) {
$.each(objTrendList, function (index, value) {
// append the checkbox panels to tool div
$('#tools').append('<input type="checkbox" id="checkbox_' +
value.LngTrendID + '" checked="checked" value="0" /> <div
style="display:inline;">' + value.StrTrendName + '</div><br />');
});
}
});
}
$(document).ready(function () {
load();
console.log($('#tools :checkbox')); // i know I don't get any thing here
because the this line is called before the ajax function
});
i know I don't get any thing with the console.log line because the this line is called before the ajax function
Question How can i load the ajax function first i though when i do $(document).ready() it will run last
Thanks

Return the ajax call and use the already built in deferred object in $.ajax :
function load() {
return $.ajax({
type: "POST",
url: "*************",
data: "************",
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function (x, e) { alert(e.responseText); },
success: function (objTrendList) {
$.each(objTrendList, function (index, value) {
// append the checkbox panels to tool div
$('#tools').append('<input type="checkbox" id="checkbox_' +
value.LngTrendID + '" checked="checked" value="0" /> <div
style="display:inline;">' + value.StrTrendName + '</div><br />');
});
}
});
}
$(document).ready(function () {
load().done(function() {
console.log($('#tools :checkbox')); // i know I don't get any thing here
});
});

The reason you don't have anything in the log is because $.ajax is asynchronous (the first 'A' in AJAX stands for 'Asynchronous'). Meaning that when you call your load() function, it fires off the $.ajax call, but does not wait for the $.ajax call to return before load() returns (this is why you must specify a success and error function so it know what to do when it actually does return).
We can look at a timeline of how your code gets executed:
load()
$.ajax()
return (null)
console.log()
(some indeterminate time later) success()
$.ajax() returns a type of object that knows when it has returned from it's call. Therefore you can call .done() on the object and execute code in that function that will wait until after the success() has run.
therefore if you return the $.ajax call you will be able to call .done() and do things with your newly-added inputs.
function load() {
return $.ajax({...});
}
$(document).ready(function () {
load().done(function(){
console.log($('#tools :checkbox'));
});
});

Related

How to put ajax request inside function and call it when necessary?

I have an ajax request:
$.ajax({
type: 'POST',
url: '/get-result.php',
dataType: 'json',
data: 'pid=' + $(this).attr("id"),
success: function(response) {
$(".reviewee-fname").append(response['fname']);
$(".reviewee-lname").append(response['lname']);
} }); };
I want to be able to put this inside a function that waits for me to trigger it with a return call. I am not exactly sure how to word it, I am new to javascript and jquery. But basically, I want to trigger this ajax call with various different button clicks and instead of having to put the ajax call inside every button click event, I want to put it in a stand alone function so if I ever update it later I dont have to change it 5 times.
Heres an example of a click event Id like to call the ajax request function with. Thanks!
$(function() {
$(".task-listing").click(function() {
//Call Ajax function here.
});
});
Callbacks are well-suited for this scenario. You can encapsulate your ajax call in a callback function.
function apiCall() {
$.ajax({
type: 'POST',
url: '/get-result.php',
dataType: 'json',
data: 'pid=' + $(this).attr("id"),
success: function(response) {
$(".reviewee-fname").append(response['fname']);
$(".reviewee-lname").append(response['lname']);
} }); };
}
You can now hook apiCall()method as a callback to button click.
$(function() {
$(".task-listing").click(apiCall);
});
By doing this you will able to achieve this.
I want to put it in a stand alone function so if I ever update it later I dont have to change it 5 times.
EDIT:
Note:
This is lead to start, you can alter this according to your requirement.
Is this not working for you? ↓↓
$(function() {
$(".task-listing").click(function() {
let pid = $(this).attr("id"); //get any other value which you want to pass in function, say url
someFunction(pid); // pass any other parameters, eg- someFunction(pid, url)
});
});
function someFunction(pid){ // someFunction(pid, url)
$.ajax({
type: 'POST',
url: '/get-result.php', // url: url
dataType: 'json',
data: 'pid=' + pid,
success: function(response) {
$(".reviewee-fname").append(response['fname']);
$(".reviewee-lname").append(response['lname']);
}
});
}

Javascript addClass or removeClass not working in subclass after ajax call

I have an ajax script that inserts a value if it is not in the database and removes the value if it is already there, and returns 1 or 0 accordingly, based on the return value it adds or removes a class in the existing button.
I have tried with find() to take the subclass value but still it is not working.
<form method="post" class="wish" action="process.php">
<input type='hidden' id='value' name='value' value='1'>
<button type="submit" class="card-fox list active" >fan</button>
</form>
This line has active I want it to be added if it is not there and remove if it is there.
below is the ajax:
$(document).ready(function (e) {
$(".wish").on('submit', (function (e) {
e.preventDefault();
$.ajax({
url: "process.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function (data) {
if (data == 1) {
$(".list", this).addClass("active");
}
if (data == 2) {
$(".list", this).removeClass("active");
}
},
error: function (e) {}
});
}));
});
the problem is that although the ajax script is being executed and everything else is working, the active class is neither adding or removing.
Use:
$(".wish").find('button').addClass("active");
$(".wish").find('button').removeClass("active");
Or:
//when form is submit, make a copy of this
let self = this;
//send ajax
//in success ajax
$(self).find('button').addClass("active");
Greetings!
The this in your ajax success function is not the form.
You can set the context of the ajax call to the for to address this.
$.ajax({
context: this, //<- this this is the form, and tells jQuery to set the this of its callbacks to the form

ASP.net/JS/JQuery/AJAX - ajax works but handler event not firing properly

I have a HTTP handler (ASHX) which I am calling from UI side using an AJAX function. The following is what needs to happen in this call:
When the section loads, it will display the status of the short code on the server in the shortcodestatus span. It will either say on or off:
<a class="btn btn-default" id="toggleshortcode">Short Code <span id="shortcodestatus"></span></a>
This is the function for getting the status of the short code and this works properly. I can manually change the status of the short code and the changes reflect properly on the div when I reload the page:
function ShortCodeStatus() {
$.ajax({
type: "GET",
url: "Handler.ashx?action=shortcodestatus",
success: function (output) {
console.log("getShortCodeStatus: " + output);
$("#shortcodestatus").empty();
if (output == "true") {
$("#shortcodestatus").text("ON");
$("#shortcodestatus").addClass("btn btn-success");
}
else {
$("#shortcodestatus").text("OFF");
$("#shortcodestatus").addClass("btn btn-danger");
}
}
});
};
This is the short code status code from the handler:
case "shortcodestatus":
{
output = ShortCodeStatus() ? "true" : "false";
}
break;
I want to be able to click on the toggleshortcode div to fire off this event through the handler. The functions for disabling and enabling the short code are working properly:
case "toggleshortcode":
{
if (ShortCodeStatus() == true)
{
DisableShortCode();
output = "false";
}
else
{
EnableShortCode();
output = "true";
}
}
break;
Here is the ajax call for the short code toggle:
$('#toggleshortcode').click(function () {
$.ajax({
type: "POST",
url: "Handler.ashx?action=toggleshortcode",
success: function (output) {
console.log("toggleshortcode: " + output);
ShortCodeStatus();
}
});
});
I'm hitting the URLs correctly and I'm getting the correct responses from each function. However the change to the short code does not seem to be happening.
For example, if the short code is off, the ShortCodeStatus function will return false and thus render the OFF button. When I click on the toggleshortcode button, the output is true (I want to turn on short code) which is correct but when the ShortCodeStatus function fires again in the success, it will still say false. The ajax functions seem correct but I can't figure out why the toggleshortcode on the handler is not firing properly.
Thank you so much for your time!
I'm seeing 2 cases that you can check.
First, in the ajax call for 'toggleshortcode', you are calling the function 'getShortCodeStatus()', and base on your example the correct name of the function is 'ShortCodeStatus()'.
Second, in the call to 'Handler.ashx?action=toggleshortcode', you are already returning the status (true or false), I suggest you make a javascript function named SetShortCodeStatus(status) , and use this inside of the success of both ajax request 'Handler.ashx?action=shortcodestatus' and 'Handler.ashx?action=toggleshortcode'.
function SetShortCodeStatus(status) {
$("#shortcodestatus").empty();
if (status == "true") {
$("#shortcodestatus").text("ON");
$("#shortcodestatus").addClass("btn btn-success");
}
else {
$("#shortcodestatus").text("OFF");
$("#shortcodestatus").addClass("btn btn-danger");
}
}
function ShortCodeStatus() {
$.ajax({
type: "GET",
url: "Handler.ashx?action=shortcodestatus",
success: function (output) {
console.log("getShortCodeStatus: " + output);
SetShortCodeStatus(output);
}
});
};
$('#toggleshortcode').click(function () {
$.ajax({
type: "POST",
url: "Handler.ashx?action=toggleshortcode",
success: function (output) {
console.log("toggleshortcode: " + output);
SetShortCodeStatus(output);
}
});
});

Chrome only : ajax freezing my javascript execution

Ajax means asynchronous, but it seems like its stopping my javascript execution or at least pausing it and resuming on response.
HTML value
<input value="foo" data-loading-text="bar" class="foo">
Extending jquery -->
$.fn.bootstrapButton= function(type){
$el = $(this);
loadingText = $el.attr("data-loading-text");
currentValue = $el.val();
if(type === "loading")
$el.attr("data-loading-text",currentValue)
.val(loadingText)
.prop("disabled", true)
else if( type === "reset")
$el.val(loadingText)
.prop("disabled", false)
.attr("data-loading-text", currentValue)
}
Function call -->
save= function (name){
$save = $(".ok")
$save.bootstrapButton("loading")
$.ajax({
type: 'POST'
url: '/server'
cache: false
dataType: 'json'
data:"ss"
success: function(response){
alert("success")
}).always(function(){
$save.bootstrapButton("reset")
})
}
I'm extending bootstrap's button coz of jquery UI's button problem. But -- when this is executing, I never see the loading text until ajax request is completed!! da faq!. Asynchronous isn't true asynchronous?
BTW, the code works without any glitch ( I can see the loading text ) with this small modification.
save= function (name){
$save = $(".ok")
$save.bootstrapButton("loading")
setTimeout(funtion(){
$.ajax({
type: 'POST'
url: '/server'
cache: false
dataType: 'json'
data:"ss"
success: function(response){
alert("success")
}).always(function(){
$save.bootstrapButton("reset")
})
},100)
}
i.e, with a 100 millisec delay, the loading text appears!, what gives?
The construction:
$.ajax({
....
}).always(function(){
$save.bootstrapButton("reset")
})
says: "Execute this Ajax command, and when it is done always run this anonymous function.
So you've explicitly said, "wait until the Ajax call is done", and it's working.
Adding the below as an option in my ajax query solved the issue.
async: true

jquery ajax call not triggering in bootstrap typehead

I trying to do a twitter bootstrap typehead using Ajax, but nothin happens.No error no output
Here is my jquery ajax code
function CallData() {
$('input.typeahead.local.remote').typeahead({
source: function (typeahead,query) {
$.ajax({
type: "GET",
url: "http://cs-api-sandbox.herokuapp.com/v1/challenges/search?keyword=r&callback=my_callback",
jsonpCallback: "my_callback",
dataType: "jsonp",
error: function (xhr, errorType, exception) {
var errorMessage = exception || xhr.statusText;
alert("Excep:: " + exception + "Status:: " + xhr.statusText);
}
});
}
});
}
function my_callback(data) {
alert('hi');
}
Here is my html code
<input type="text" id="txt" runat="server" class="span4 typeahead local remote" placeholder="Search..." />
i'm calling the ajax function CallData() on each key press but nothing happens
You need to pass the result from the ajax request to the second argument of source (which is a callback to populate the type ahead). A contrived example:
$('#mytypeahead').typeahead({
source: function(query, process){
$.ajax({
url: '/some/url?query='+query,
success: function(response){
process(response);
}
});
}
});
Try to add async: false into the $.ajax - because the mechanisms of javascript is unsynchronized.
Hope this help

Categories

Resources