Sending a POST request with Ajax on button click - javascript

I have a normal button, which triggers a basic function that prints the value of an element in my HTML to the console.
Now, instead of printing the value of that element i want to send it to my Django view with a POST request.
Here is the function:
$(document).on('click','.btnClick', function() {
var myvalue = $(this).data("myid");
console.log(myvalue);
});
Here, instead of printing that value, i want to send myvalue with a post request using Ajax.
I know how to do a POST request, the only difference is that this time, instead of using a form, i'm using a single button to trigger the request, and i'm not really used to that.
Here is how i would do it with a form:
$(document).ready(function () {
$("#myform").submit(function (event) {
$.ajax({
type: "POST",
url: "/myurl/",
data: {
'myvalue': $('id').val()
},
});
return false;
});
});
So, basically i just need to know how to integrate this piece of code inside the first function, so that the Ajax call is triggered not by the form (as it is in the second code) but from a button.

Just put your jquery ajax function inside into the click event function.
$(document).on('click','.btnClick', function() {
var myvalue = $(this).data("myid");
$.ajax({
type: "POST",
url: "/myurl/",
data: {
'myvalue': myvalue
},
});
});
Hope this will help.

Related

Saving Variable in AJAX success call to pass in Another AJAX success call

Creating a 'refresh' button via jQuery, AJAX and PHP.
This particular one I'm having control two DOM instances (divs) - #sold-container, and also #totalorderswidget.
$(document).ready(function() {
$(function() {
$('#orderfeed').on('click', function() {
var orders;
$.ajax({
type: 'POST',
url: 'liveorderwidget.php',
beforeSend: function() {
$('#sold-container').html('<div class="page-loader"></div>');
$.ajax({
url: "totalorderswidget.php",
beforeSend: function() {
$('#totalorderswidget').html('<div class="page-loader"></div>');
},
success: function(orderdata) {
// $('#totalorderswidget').html(orderdata);
orders = orderdata;
}
});
},
success: function(solddata) {
$('#sold-container').html(solddata);
$('#totalorderswidget').html(orders);
}
})
});
});
});
I didn't like how each DIV was updating and showing my page-loader CSS at different times, so I thought I'd try and grab the data to pass and display them both at the same time (get data from the first ajax call, display both on the second).
This is working as two normal AJAX calls, and each appends the success html to each id on it's own. (uncommenting // $('#totalorderswidget').html(orderdata); works),
but initializing a variable like var orders; outside the functions and trying to put the data in the success call (orders = orderdata;) does not work.
Doing a console.log on the first AJAX success call (orderdata) brings back the expected response, but trying to use it in the second AJAX call ($('#totalorderswidget').html(orders);) does not work and a console.log brings back undefined for the order variable.
What must I change in order to grab data from the first success call function and bring this data into the second/final ajax success call?

Same ajax call but changed data from same UI on multiple button click

$("#myButton").click(function (e) {
dataString = $("#myform").serialize();
$("#ajaxResponse").empty();
var $body = $('body');
$body.addClass('loading');
var html = '';
$.ajax({
type: "POST",
url: "hotelservlet",
// data : { name : name, id : 'foo' },
data: dataString,
datatype: "json",
beforeSend: function () {
$body.addClass('loading');
},
success: function (data) {
}
I have a web form which takes some input and get response on an AJAX call made on click of submit button and I also have two other buttons next and previous I want same AJAX call to be made on both the other buttons but with some changes made to the input.
I am using jQuery serialize method to make AJAX call. Please tell me how to change the inputs for ajax call of next and previous.
You can move the ajax call to a new method with input as the parameter. Then you can make differnt client click events for these three button. In the click event call the method for ajax call with corresponding parameter.

Calling a javascript function from a link generated from a ajax call

I have a javascript function.
I'm making a AJAX call, and in that recieved content there is a link that I want to call the javascript function with.
MyJavascriptFunction(bla){
alert (bla);
}
Result from ajax = "Click
Do I have to do anything special with the result from AJAX to get this to work or should it just work.
I have tried it like this but with no success with clicking the link.
The AJAX call:
function doSearch() {
var form = $('form');
$.ajax({
url: "doSearch.php",
type: "GET",
data: form.serialize(),
success: function(result){
document.getElementById("result").innerHTML=result;
}
});
}
In the php I'm printing out
Click
First of all, try it. But yes you have to do something with the AJAX result. It has to be put somewhere in the DOM or the user won't be able to click on it.
Plus, make sure that the javascript function is a top level. I would suggest you use event handlers instead though.
Change your <a> tag to:
Click
You are mixing jQuery and DOM. that is not pretty
try this - assuming you do not have more than one link in the html
success: function(result){
$("#result").html(result).find("a").on("click",function() {
MyJavascriptFunction(bla);
return false;
};
}

How can one trigger a function onchange of a div?

Here's a question which has proved very difficult to find an answer online for.
Let's say a user runs an ajax function onclick to fill the contents of a div.
But, what if the ajax output is php, and for that onclick, i want other divs on the page to change in a manner that is dependent on the contents of div1?
This means I need to wait for div1 to actually change so i can use the ajax output of the php calculations to adjust div2 accordingly.
After some testing i've found out that i cant add a call to a second ajax function at the end of the first because it seems to run before the div content from the first ajax call actually changes.
So how can i trigger an ajax call onchange of the contents of a div?
All ajax calls take a callback to run when the call completes, put your logic in there.
You could use Jquery
$('#div1').change(function(){
doAjax( $(this).html() );
});
Or in the callback of the ajax
$.ajax({
url: 'http://yoururl.com',
type: 'post',
data: { key: value },
success: function( data ){
doAjax( data );
}
});
If you are aware of jquery, this is what you should try:
$.ajax({
traditional: true,
type: "post",
url: '<your_url>',
beforeSend: function () {
//your logic to perform operation before ajax request
},
data: {
//data to send
},
success: function(response) {
//your logic to perform operation after ajax request
//here make another ajax request
}
});

jQuery form processing, how can I reassign a function on callback?

$(function(){
$(".mailbutton").click(function() {
var email = $(".mailingfield").val();
$.post("/PHP_scripts/mailinglist.php", { email: email }, function(data) {
var content = $(data).find("#mailinglistform");
$("#box").empty().append(content);
});
});
});
I'm using this to process an email address. If it fails in the PHP script the form is sent back in the '.mailinglistform' with a fresh form and some text explaining the error. The problem I have is that even though the button has the '.mailbutton' class in the callback form, the button doesn't do anything on click.
Is this because the jQuery only recognises it first time round? If so, is there a way to "reload" the 'mailbutton' .click function on callback?
Thanks!
You're right that because you're only re-rendering a portion of the page, the previous jQuery you wrote does not register with the "new" mailbutton class that you've re-rendered. To get around this, you should use .on(), e.g.:
$(".wrapper").on('click', '.mailbutton', function() {
var email = $(".mailingfield").val();
$.post("/PHP_scripts/mailinglist.php", { email: email }, function(data) {
var content = $(data).find("#mailinglistform");
$("#box").empty().append(content);
});
});
In this case, wrapper needs to be a class element that's outside of the re-rendered section (e.g. the 'content' class, maybe a class around your form, etc) of the page, and one that is constantly present (i.e. not re-rendered in the ajax call). This will attach an onclick handler to any .mailbutton classes that are children of the wrapper class, whether they are present when the page is rendered, or if they are added to the DOM later.
Use on to bind click event. When control is render again in the callback function its events are removed. Using on instead of click could rebind the events automatically.
$(function(){
$(".mailbutton").on("click", function() {
var email = $(".mailingfield").val();
$.post("/PHP_scripts/mailinglist.php", { email: email }, function(data) {
var content = $(data).find("#mailinglistform");
$("#box").empty().append(content);
});
});
});
For this you can use AJAX with JQuery. OR you can alos user load().
$(".mailbutton").click(function() {
$.ajax({
url: 'api.php', // Put your calling page path here
data: "",
dataType: 'json',
success: function(data)
{
//do whatever you want to do on success
}
});
});

Categories

Resources