How can I find ID/Class of the current form within the ajax success function? Since there are multiple forms with the same Class, I cant simply search for the class, but need exactly the form that was submitted.
I have following script:
$('#fAddOs,#fAddFs,.addJ').submit(function(){
//$(this) = form
$.ajax({
type:'POST',
url:'admin.inc.php',
data:data,
dataType:'html',
success:
function(response){
//Get form
}
});
});
If I call $(this) within the AJAX function (see my comment in the code above), I get:
[Object { url="admin.inc.php", isLocal=false, global=true, mehr...}]
outside the ajax call, save the form to a variable that you can use inside the ajax callback.
$('#fAddOs,#fAddFs,.addJ').submit(function(){
var form = $(this);
$.ajax({
type:'POST',
url:'admin.inc.php',
data:data,
dataType:'html',
success:
function(response){
// use the form variable here...
console.log(form.attr('id'));
}
});
});
With the selector you're using, you are grabbing multiple elements. Inside the submit, the current form being worked with can be accessed using this. Or to use it as a jQuery object $(this).
In the function:
var id = $(this).attr("id");
Or to grab the class name
var class = $(this).attr("class");
UPDATE
Before the ajax call, create a var:
var form = $(this);
then use form in the ajax function
Try this within the submit function:
var id = this.id;
Related
Is it possible to pass an array that is populated via checkboxes to another page via AJAX POST and navigate to that page?
The current scenario is I have a table with checkboxes that allows the user to select the checkboxes to pay for multiple items. The issue is passing that multiple ids to the payment page. Are there any suggestions as to how I can do it?
This is what I have so far:
function pay(input){
var id = input;
$.ajax({
method: "POST",
url: "<?php echo site_url($this->data['controller'].'/Pay'); ?>",
data:'id='+id,
beforeSend: function () {
$('.loading').show();
},
success: function(data){
//what do i fill here
}
});
}
Or is there an alternate method of doing this?
I will break this question down into 2 questions:
Is it possible to pass an array that is populated via checkboxes to
another page?
Why yes use square brackets in the input name to make it an array.
<input type="checkbox" name="id[]" value="2">
<input type="checkbox" name="id[]" value="6">
in PHP you can access the selected item ids like this:
$selectedItemIDs = $_POST['id'];
// $selectedItemIDs is now [2, 6] if both checkboxes were selected.
Can I pass an array to another page via AJAX POST and navigate to that
page?
IIRC this is not possible without using a dirty workaround. JavaScript and jQuery do not provide this functionality.
To find the workaround you have to realize that what you are trying to do is simply navigate to a different page, with POST parameters.
Don't forms do exactly that? Yes, they do!
The dirty workaround i was talking about is of course a hidden form where you fill all needed information with JS / jQuery and submit it. Here is a stackOverflow post about this
In your situation though, I would just use the form that you already have (with the multiple checkboxes), since you can easily pass an array of checkbox-values with a form.
The data parameter is not a string when making a POST request. Save all of your form data to a variable and assign that variable to the "data" element of the POST call. You can do this like so:
var myform = $('form').serialize(); // This will save all the form's data to the variable myform
and then
data: myform, // This will send what myform contains via POST
Inside "success" you get to parse the information from the POST response.
After that you can redirect using:
window.location.href = 'http://yourlink.here'; //this will redirect you to another page
Through an array you can post it to ajax
var check_box_array = [];
$("input:checkbox[name=type]:checked").each(function(){
check_box_array.push($(this).val());
});
and then
$.ajax({
method: "POST",
url: "<?php echo site_url($this->data['controller'].'/Pay'); ?>",
data:{check_box_data:check_box_array},
beforeSend: function () {
$('.loading').show();
},
success: function(data){
//what do i fill here
}
});
I have an application that after performing a search, returns me multiple "fieldsets" with some hidden inputs (via AJAX!).
I want to use these inputs to send information to the server (again) via AJAX.
The names of these inputs are automatically listed with a prefix:
"video_url_1", "video_url_2", etc.
When the user clicks the button, the value of "video_url_1" or "video_url_2" will be sent via AJAX depending on the button to which it has clicked. To solve this I got the name of the button that was clicked and then I cut the name so that I only have one number, this number I put in a variable and then use it in the "data" section of AJAX.
I did the test by sending a locally stored input and it worked but when trying to send the inputs that were previously obtained by an ajax, it does not work.
What can be wrong? This is my code:
$(document).ajaxComplete(function(){
$('a.report_video').click(function() {
var idbutton = $(this).attr('id');
var idreport = idbutton.replace('report_video_', '');
//I'm still not using these variables, can they be used to pass the input data to ajax?
var videourl = $("#video_url_" + idreport).val();
var videoid = $("#video_id_" + idreport).val();
var videoserver = $("#server").val();
///////////
$.ajax({
type : 'POST',
url : 'https://example.com/script/script.php',
data : $($("#video_url_" + idreport)).serialize(), //It doesn't work
//For example, data: $("#server").serialize()
//Work fine, this input is stored locally.
beforeSend: function(){
$('#video_report_' + idreport).html('<img src="'+pluginUrl+'./assets/img/loading.svg" />');
}
}).done(function(data) {
$('#video_report_' + idreport).html(data);
});
return false;
});
});
Edit:
I just did some tests as suggested by Kevin B and I see that the problem I have is in the syntax when trying to send two dynamic ID's by Ajax.
The problem is that I do not know how to write them correctly, I know that is the problem because when I tried to send them separately they did work...
data : $($("#video_id_" + idreport), $("#video_url_" + idreport)).serialize(),
I'm not sure I completely understand your problem, but this might help.
You call your second AJAX call in the .success() method of the first AJAX call. Essentially chaining the responses.
$('#btn').click(function() {
$.ajax({
type: "POST",
url: 'someURL',
data: someData
}).done(function(firstCallData) {
// This OPTIONAL method fires when the AJAC call succeeded
// You can also put another AJAX call in here with the data returned from the first call
$.ajax({
type: "POST",
url: 'someURL',
data: firstCallData
}).done(function(data) {
// Do something with second AJAX call with data
}).fail(function(data) {
// Second AJAX call failed, handle error
});
}).fail(function(data) {
// This OPTIONAL method fires when the first response failed
}).always(function(data) {
// This OPTIONAL method fires regardless if the first call succeeded or failed.
});
});
This question already has answers here:
Using selectors and $(this) in Jquery Ajax
(2 answers)
Closed 7 years ago.
Hi I am using jquery to make an ajax request to the database to add and remove favourites from the database. This works fine however I want to replace part of the href in the anchor link so that a user can add/remove again if required without refreshing the page e.g. the link is built as so http://article.local/favourite/delete/uniqueid therefore I need to replace the 'delete' with add and vise versa for the add favourite button. However I can't use the class name otherwise this will apply to all of the classes rather than the one clicked at that time.
$( ".remove-favourite" ).click(function(e) {
e.preventDefault();
var favform = $(this).parent('.fav-form-contents');
$(favform).append("<img src='/images/loading.gif' class='form-loader' class='loading-icon'/>");
$.ajax({
type : "POST",
cache : false,
url : $(this).attr('href'),
data : $(this).serialize(),
success : function(data) {
$('.loading-icon').hide();
$(this).attr('href').replace(/delete/, 'add');
$(this).removeClass('remove-favourite').addClass('add-favourite');
}
})
}); // end click function
However the error message I get back is as follows:
Uncaught TypeError: Cannot read property 'replace' of undefined
This suggests that it has lost the current item, any ideas as to what I am doing wrong??
You need to preserve $(this) in a variable for the callback like
var $link = $(this);
$.ajax({
type : "POST",
cache : false,
url : $(this).attr('href'),
data : $(this).serialize(),
success : function(data) {
$('.loading-icon').hide();
$link.attr('href').replace(/delete/, 'add');
$link.removeClass('remove-favourite').addClass('add-favourite');
}
})
this itself will have changed because the execution context of the success callback in $.ajax is different then when you called $.ajax.
make this as global means with in function
like var _this = $(this) use in ajax suuceess
this inside ajax is related to xhr object.
Use context option of ajax,
This object will be the context of all Ajax-related callbacks. By default, the context is an object that represents the Ajax settings
$.ajax({
context:this,
....
I have been working on this for a while and posted several related topics about it, but this is slightly different question. I have the following AJAX code with some html forms below it with in #container and .myselect is the class of a drop-down box. When I change the value in the box I want to be able to then use that value on other fields below the select. The AJAX code kinda works in that the alert shows the right value when changed but as you can see I have tried lots of success functions but no luck. The closest is
$('#reloadtest').html(data); which will show the value in my PHP and every time I change the value from then on it will change alot, but it reloads the page within the container.
Basically I want to know how I can reload the data but not the whole html/page so I can use the value of the drop down in my PHP.
$(document).ready(function(){
$('#container').on( 'change', '.myselect', function() {
var orderidVal = $(this).val();
alert(orderidVal);
$.ajax({
type: "POST",
data: { orderidType : orderidVal },
success: function(data) {
//$('#container').reload('#container', function() {});
//$('#quoteselect').reload('#quoteselect', function() {});
//$('#container').load('orders.php #container', function() {});
//$('#quoteselect').load('orders.php #quoteselect', function() {});
//$('#testreload').reload('#testreload', function() {});
//location.href = "test2.php"
$('#reloadtest').html(data); //this allows me to use the variable but reloads the whole page within the page
}
})
});
});
If you are doing an ajax-request you have to allocate an URL where to send the request.
If you don't Request anything jQuery reloads the page. As you can see here in the jquery-api-docu the URL is the very first and most important parameter of the request.
$.ajax({
url: "/url/to/the/php/script.php",
success: function(data){
//do something ... with data parameter
}
});
would be the simple way of using ajax-request with javascript.
use two divs - one in which you can put ajax response and in other the remaining HTML code
it reloads your page because you have not specified what page to request.
use the code below and replace /path/to/script to your actual script path
$(document).ready(function(){
$('#container').on( 'change', '.myselect', function() {
var orderidVal = $(this).val();
alert(orderidVal);
$.ajax({
cache: false,
async: true,
type: "POST",
url: '/path/to/script',
data: { 'orderidType' : orderidVal },
success: function(data) {
$('#reloadtest').html(data);
}
});
});
});
I have an AJAX call which dynamically generates a HTML form. This form contains a number of elements including inputs, selects, textareas, checkboxes as well as etc.
I need to write some javascript (jquery available) to get all the fields in this form and submit them to an AJAX script. I won't know how many or what fields are there (only a basic idea) as it all depends on what the user does.
Any ideas how to do this? Lets say my form name is 'ajaxform'
As everyone said, use jQuery serialize. One other note is to override your form submit (if needed) via jQuery live method:
//Override form submit
$("form").live("submit", function (event) {
event.preventDefault();
var form = $(this);
$.ajax({
url: form.attr('action'), // Get the action URL to send AJAX to
type: "POST",
data: form.serialize(), // get all form variables
success: function(result){
// ... do your AJAX post result
}
});
});
var string_ready_to_be_posted = $("#formId").serialize();
http://api.jquery.com/serialize/
You can use jQuery's .serialize():
var data = $('#ajaxform').serialize();
var action = $('#ajaxform').attr('action');
$.post(action, data, function(data) {
...
});
var string_ready_to_be_posted = $('form[name="ajaxform"]').serialize();
As addon for using NAME-selector instead of ID