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

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

Related

Ajax success and laravel

I'm currently working on a project using Laravel platform.
I'm trying to delete data from a model asynchronously using ajax. And when all is done my data should be removed from the table. My code runs perfectly, data are being removed from my database , yet "tr" elements arent really faded or removed. Here is my code :
ajax sucess not really working.
$(document).on('click', '.btn-remove-interview' , function() {
var id = $(this).attr('data-interview-id');
$.ajax({
url: './manage/interviews/destroy/'+id ,
type: 'post',
dataType: 'json',
data: id,
success: function (data) {
$(this).parents("tr").remove();
}
});
});
Use
$(this).closest('tr').remove();
Instead of
$(this).parents("tr").remove();
The problem is that the success function callback within your ajax request no long refers to the button when you use this. You need to get an explicit variable to the button if you want to use it.
$(document).on('click', '.btn-remove-interview' , function() {
// Get this button as a variable so we can use it later
var el = $(this);
var id = $(this).attr('data-interview-id');
$.ajax({
url: './manage/interviews/destroy/'+id ,
type: 'post',
dataType: 'json',
data: id,
success: function (data) {
$(el).parents("tr").remove();
}
});
});
Solution was by removing dataType json . My function doesnt return any data .

How do I pass value from a javascript function to C# Code behind?

I have a dynamic button which have unique id's, I'm getting the id of the clicked button like so:
$("button").click(function() {
//I want to pass this.id to my btnDetails_Click event in C# or to a variable Property(for efficiency)
});
How do I do this? Sorry noob in javascript.
I won't code precisely for you, but maybe what I will include could help and point you to right direction in your own conclusion.
Okay, let us say that the page you are using is called Page.aspx, and the method is called Done
var values = {"0,","1","2"};
var theids = JSON.stringify(values);
// Make an ajax call
$.ajax({
type: "POST",
url: "Page.aspx/Done",
contentType: "application/json; charset=utf-8",
data: {ids: theids },
dataType: "json",
success: function (result) {
alert('Alright, man!');
},
error: function (result) {
alert('Whoops :(');
}
});

Design to block asynchronous javascript

var flow;
$.ajax({
url: "qa/version.json",
dataType: "json",
success: function( response ){
flow = response.Version;
}
});
$(".flow").append(flow);
Due to the nature of JS asynchronous design, the append would will be execute before it is being assigned a value in ajax call. What is the best way to tell the script to wait until flow gets assigned in ajax call, then do the append? I do not want to put append right below the success, I would like to keep them separate.
The "best way" is to perform the action in response to the asynchronous action:
$.ajax({
url: "qa/version.json",
dataType: "json",
success: function(response){
$(".flow").append(response.Version);
}
});
If you want to "keep them separate" then you can define a function to call in the response:
var appendFlow = function (flow) {
$(".flow").append(flow);
};
$.ajax({
url: "qa/version.json",
dataType: "json",
success: function(response){
appendFlow(response.Version);
}
});
Separating the code into its own function is simply a matter of organizing your code into re-usable components. Either way, by design the response can't be processed until it's received, so you'd perform your actions in response to the asynchronous call.
Anything wrong with:
$.ajax({
url: "qa/version.json",
dataType: "json",
success: function( response ){
flow = response.Version;
$(".flow").append(flow);
}
});
I have no idea why you don't want to put your success handler in the spot for a success handler, but here's an alternative that may help you.
jQuery returns a Deferred instance when you make AJAX requests. You can use its .done() method to set up a callback later.
var dfd = $.ajax( /* your code here, without the success handler */);
// later on...
dfd.done(function (response) {
$('.flow').append(response.Version);
});
See also:
https://api.jquery.com/deferred.done/
https://api.jquery.com/jquery.deferred/
Or:
var request = $.ajax({
url: "qa/version.json",
dataType: "json"
});
request.done(function(response){
$(".flow").append(response.Version);
});

Setting data-content and displaying popover

I'm trying to get data from a resource with jquery's ajax and then I try to use this data to populate a bootstrap popover, like this:
$('.myclass').popover({"trigger": "manual", "html":"true"});
$('.myclass').click(get_data_for_popover_and_display);
and the function for retrieving data is:
get_data_for_popover_and_display = function() {
var _data = $(this).attr('alt');
$.ajax({
type: 'GET',
url: '/myresource',
data: _data,
dataType: 'html',
success: function(data) {
$(this).attr('data-content', data);
$(this).popover('show');
}
});
}
What is happening is that the popover is NOT showing when I click, but if I hover the element later it will display the popover, but without the content (the data-content attribute). If I put an alert() inside the success callback it will display returned data.
Any idea why is happening this? Thanks!
In your success callback, this is no longer bound to the same value as in the rest of get_data_for_popover_and_display().
Don't worry! The this keyword is hairy; misinterpreting its value is a common mistake in JavaScript.
You can solve this by keeping a reference to this by assigning it to a variable:
get_data_for_popover_and_display = function() {
var el = $(this);
var _data = el.attr('alt');
$.ajax({
type: 'GET',
url: '/myresource',
data: _data,
dataType: 'html',
success: function(data) {
el.attr('data-content', data);
el.popover('show');
}
});
}
Alternatively you could write var that = this; and use $(that) everywhere. More solutions and background here.
In addition to the answer above, don't forget that according to $.ajax() documentation you can use the context parameter to achieve the same result without the extra variable declaration as such:
get_data_for_popover_and_display = function() {
$.ajax({
type: 'GET',
url: '/myresource',
data: $(this).attr('alt'),
dataType: 'html',
context: this,
success: function(data) {
$(this).attr('data-content', data);
$(this).popover('show');
}
});
}

How to call second jQuery.ajax instance on success of first and update page

I have some jQuery that is triggered on click of a link with the class 'changetag'. I'm using $.ajax() to update the database via changetag.php.
I then change the visual appearance of the link by toggling the class between on/off. The code is as follows:
$(function() {
$(".changetag").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'switch_tag=' + I;
$.ajax({
type: "POST",
url: "_js/changetag.php",
data: info,
success: function(){}
});
$("#li_"+I).toggleClass("off on");
element.toggleClass("off on");
return false;
});
});
Works perfectly. But now I want to add in a second PHP call which will pull data and update another area of the page if the above was successful.
What I'm trying to add is:
$.ajax({
url: "_js/loaddata.php",
success: function(results){
$('#listresults').empty();
$('#listresults').append(results);
}
});
But just adding it into success: function(){} doesn't seem to be working. To clarify, here is the complete code I'm testing:
$(function() {
$.ajaxSetup ({cache: false});
$(".changetag").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'switch_tag=' + I;
$.ajax({
type: "POST",
url: "_js/changetag.php",
data: info,
success: function(){
$.ajax({
url: "_js/loaddata.php",
success: function(results){
$('#listresults').empty();
$('#listresults').append(results);
}
});
}
});
$("#li_"+I).toggleClass("off on");
element.toggleClass("off on");
return false;
});
});
The PHP scripts are both called successfully and the toggle class works, but the data pulled is not written to #listresults for some reason.
Ajax calls are (by default) asynchronous. That means that this code:
$("#li_"+I).toggleClass("off on");
element.toggleClass("off on");
return false;
could be executed before the ajax call preceding it is finished. This is a common problem for programmers who are new to ajax and asynchronous code execution. Anything you want to be executed after the ajax call is done must be put into a callback, such as your success handler:
$.ajax({
type: "POST",
url: "_js/changetag.php",
data: info,
success: function(){
$("#li_"+I).toggleClass("off on");
element.toggleClass("off on");
}
});
Likewise, you could put the second ajax call in there as well:
$.ajax({
type: "POST",
url: "_js/changetag.php",
data: info,
success: function(){
$("#li_"+I).toggleClass("off on");
element.toggleClass("off on");
$.ajax({
url: "_js/loaddeals_v2.php",
success: function(results){
$('#listresults').empty();
$('#listresults').append(results);
}
});
}
});
With jQuery 1.5's Deferred Object, you can make this slicker.
function firstAjax() {
return $.ajax({
type: "POST",
url: "_js/changetag.php",
data: info,
success: function(){
$("#li_"+I).toggleClass("off on");
element.toggleClass("off on");
}
});
}
// you can simplify this second call and just use $.get()
function secondAjax() {
return $.get("_js/loaddata.php", function(results){
$('#listresults').html(results);
});
}
// do the actual ajax calls
firstAjax().success(secondAjax);
This is nice because it lets you un-nest callbacks - you can write code that executes asynchronously, but is written like synchronously-executed code.
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
https://api.jquery.com/jQuery.ajax/#jqXHR

Categories

Resources