Ajax request doesn't auto trigger on form change - javascript

<form>
<select name="select-1">
<option value="option-1">Option 1</value>
<option value="option-2">Option 2</value>
</select>
<button type="submit">Submit</button>
</form>
I have a form that when the button is clicked, it populates a div with html content from an Ajax request without any page reload ( its done in the backend, cant say much more because its not my area of expertise ). When the submit button is clicked, it works as expected, but the behaviour I want is for the Ajax request to auto-trigger when the form has an option selected, without the need to press the button.
$(document).on(
"change",
"select[name=select-1]",
function(e) {
if ($(this).val()) {
$(document)
.find("form")
.submit();
}
}
);
The problem here is that the form submits and reloads the page, not triggering the Ajax request. I have also tried to trigger a click event on the button itself:
$(document).on(
"change",
"select[name=select-1]",
function(e) {
if ($(this).val()) {
$(document)
.find("button")
.click();
}
}
);
.. but nothing happens.

// try something like this, as suggested by #Anjana. try to submit form data
// using ajax.
$(document).on(
"change",
"select[name=select-1]",
function(e) {
if ($(this).val()) {
var formData = new FormData();
formData.append("select-1", $(this).val());
$.ajax({
url: {your url},
method: "post",
data: formData,
success: function(data) {
div.innerHTML = data;
}
});
}
}
);

In my opinion, if you are using AJAX, you should trouble with form. You only need something to trigger the call. That can simply be a button.
<select id="menu" name="select-1">
<option value="option-1">Option 1</option>
<option value="option-2">Option 2</option>
</select>
<button type="submit">Submit</button>
Select the value that the user has selected in the select menu with:
const selection = $( "#menu option:selected" ).text();
Then use the $.ajax() function provided by jQuery:
$(document).ready(function() {
$('#submit').click(function() {
$.ajax({
type: "POST",
url: "<CHANGE HERE>",
data: { selection: selection },
dataType: "json"
});
});
});

You have used button type ="submit", which makes the page reload. So remove type submit from your button and use ajax or use e.prevent default() like
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
url: url, //type your url,
method: "post",
data: data,
success: function(data) {
},
error: function(data){
}
});
After that on change when you submit the form on change event as you are doing, it will trigger the Ajax request and work as you expect.
Learn More about Ajax here

First of all, the jQuery code you are using is not AJAX, you can learn more about jQuery and AJAX from their documentation here:
http://api.jquery.com/jquery.ajax/
Here is the solution to your problem:
<!--HTML CODE-->
<form>
<select name="select-1">
<option value="option-1">Option 1</value>
<option value="option-2">Option 2</value>
</select>
<button type="submit">Submit</button>
</form>
Here's the jQuery code that actually uses AJAX.
A selector is used to get the <select></select> and then we set an event listener to listen when the object is changed.
UPDATE: This now allow you to attach event listener to dynamically created elements
$(document).ready(function() {
$(body).on('change', "select[name=select-1]", function() {
$.ajax({
url: "https://example.com",
method: 'GET',
data: {"id": 123, "value": $('select[name=select-1]').val()}
})
.done(function (){
alert("success");
})
.fail(function (){
alert("error" + $('select[name=select-1]').val());
});
})
});
You can change the url in the AJAX, as well as method with GET or POST, and the data to be sent to the URL.
After that, if the AJAX request is successful, the code in the .done() section will be executed.
Similarly, if the request fails, the code in fail() will be executed.

Related

Too many ajax calls when form selections change

My webpage has two main sections: (1) search criteria (selection boxes in a form) used to access database information, and (2) a div in which the results are displayed. When the page loads initially, default values in the form are serialized and sent via ajax to php and the results are rendered. This results section is paginated to display all the results by clicking next, previous, etc. This all works perfectly.
Here’s the problem: each time the user makes a change to the criteria and the form’s data is serialized and sent via ajax, another layer of results is added somehow. When paginating through the results, it processes page 2 for each of the “layers” but only the last one that arrives from the server is displayed on the webpage. So, every time another change is made, another layer is added. Since ajax is asynchronous, the results displayed may or may not be the correct “layer.”
HTML:
<form id='submitCriteria' action='' method='post'>
<select id='selLevel' class='selectpicker' name='levels'>
<option title='Levels' value='No Preference'
selected = 'selected'>No Preference</option>
<option title='Levels:<br> 1+' value=1 >1+ </option>
<option title='Levels:<br> 2+' value=2 >2+ </option>
<option title='Levels:<br> 3+' value=3 >3+ </option>
</select>
</form>
<!-- Pagination: -->
<div id="spinnerDet" class="spinnerA">
</div>
<div id="paginationdiv">
<div id="pagination_container">
<div class="pagination">
<ul><li class="inactive">Previous</li>
<li class="pagerange">
<span class="total" a=" 58">
Page 1 of 58 </span></li>
<li p="2" class="active">Next</li>
</ul>
</div>
<!-- Output from server: -->
<table>
<tr><td>Levels</td><td>3</td></tr>
</table>
</div>
</div>
javascript/jQuery:
$("#submitCriteria").change(function(e) {
e.preventDefault();
e.stopPropagation();
$.ajax({
type: 'post',
data: $("#submitCriteria").serialize(),
url: "/load_plans.php",
success: function(data) {
paginateDetails (data)
},
});
return false;
});
function paginateDetails (data) {
selDetails = JSON.parse(data);
var levels = selDetails.levels;
var totalsline = "Number of levels: " + levels;
$('#numResults').removeClass('spinnerA');
$('#numResults').addClass('stop-spin');
$('#numResults').html(totalsline);
loadData(1); //initial output based on default values
// Pagination buttons event:
$('#paginationdiv').on('click touchend',
'#pagination_container .pagination li.active', function (e) {
e.stopPropagation();
e.preventDefault();
var page = $(this).attr('p');
loadData(page);
});
function loadData(page) {
$.ajax({
type: "POST",
data: eval("'page=' + page + '&levels=' + levels"),
url: "loadDetails.php",
success: function (msg) {
$("#pagination_container").ajaxComplete(function (event, request, settings) {
$("#pagination_container").html(msg);
});
}
});
}
}
How do I eliminate another “layer” when selections in the form are changed/updated?
I think the problem is with the structure of your code, in this case you shouldn't be nesting the functions. Also you are repeatedly attaching click event to #paginationdiv (does it get removed and reatached when you reload data? You should use class instead of div in that case).
Without trying the code, i believe your problem might be caused by your loadData function - in your success callback you don't need to hook ajax complete again, success is called when your request is complete and successfull. I believe that part of your code was triggering twice ( on success and when ajaxComplete fired)
Your refactored code should look something like this:
$("#submitCriteria").change(function(e) {
e.preventDefault();
e.stopPropagation();
$.ajax({
type: 'post',
data: $("#submitCriteria").serialize(),
url: "/load_plans.php",
success: function(data) {
paginateDetails (data)
},
});
return false;
});
function loadData(page) {
$.ajax({
type: "POST",
data: eval("'page=' + page + '&levels=' + levels"),
url: "loadDetails.php",
success: function (msg) {
//$("#pagination_container").ajaxComplete(function (event, request, settings) {
$("#pagination_container").html(msg);
//});
}
});
}
function paginateDetails (data) {
selDetails = JSON.parse(data);
var levels = selDetails.levels;
var totalsline = "Number of levels: " + levels;
$('#numResults').removeClass('spinnerA');
$('#numResults').addClass('stop-spin');
$('#numResults').html(totalsline);
loadData(1); //initial output based on default values
// remove previous click handlers
$('#paginationdiv').off()
// Pagination buttons event:
$('#paginationdiv').on('click touchend',
'#pagination_container .pagination li.active', function (e) {
e.stopPropagation();
e.preventDefault();
var page = $(this).attr('p');
loadData(page);
});
}

Loading data in select with Ajax / jQuery on click resets to the first element

Load data into a select with ajax and jQuery.
When I click on any item loaded the selection returns to the first item. Here is the code I use:
HTML:
<div class="selector-asesor-independiente">
<label class="fl ml4p sitecolor">Asesor Independiente
<select name="pol_drectivo" id="pol_drectivo" class="w100p"></select>
</label>
</div>
Javascript:
$(document).ready(function(){
$('.selector-asesor-independiente select').click(function() {
$.ajax({
type: "POST",
url: "ajax_cargaAsesorIndependiente.php",
success: function(response)
{
$('.selector-asesor-independiente select').html(response).fadeIn();
}
});
});
});
I try to change the event from .click to .change but nothing happens.
What am I doing wrong?
It is recommended to call the ajax on document.ready() method or window.load. Not on the click of the same input.
$(document).ready(function(){
//Your ajax call here
});
If this doesn't help, please post a sample of the response you are getting.
Updated code:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "ajax_cargaAsesorIndependiente.php",
success: function(response) {
$('.selector-asesor-independiente select').html(response).fadeIn();
}
});
});

update session and refresh page with ajax/jquery

I need help with a script that according to 2 parameters updated me a $ _SESSION variable and then refresh the page. One of these parameters comes from a select and the other according to a select class "active".
Here's my code:
<div class="simple-drop-down">
<select id="select-order">
<option>Price</option>
<option>Category</option>
<option>A - Z</option>
</select>
And my jquery function like this:
function order_visual() {
var type_order = $('#loader-wrapper').val();
var arrow_order = $( "#select-arrow" ).hasClass( "active" );
$.ajax({
url: "visual.php?order="+type_order="&"+arrow_order,
type: "post",
data: {},
success: function(data){
location.reload();
}
});
});
And then the PHP is a simple script that manages the $_SESSION.

One submit button for multiple forms. Master save strategy,

Picture below shows simplification of the html page layout I am working with. It has 3 forms, every form has it's own submit button and can be submitted individually. At the top of the page "Master Save" is located. This button should save all 3 forms.
Every form have submit() function overloaded and they look like this:
form1.submit(function () {
Form1SubmitOverloaded(this);
return false;
});
Form1SubmitOverloaded = function (form) {
$.post(form.action, $(form).serialize(), function (data) {
//DOM manipulation, etc/
}).fail(function () {
//error parsing etc.
});
return false;
};
After pressing "Master Save" I want to submit forms in order 1 > 2 > 3. But I want Form 2 to wait until form 1 has ended.
Form1 submitted >> Form2 submitted >> Form3 submitted.
$('#masterSave').click(function () {
$('#form1').submit();
$('#form2').submit(); // wait until form1 ended
$('#form3').submit(); // waint until form2 ended
return false;
});
Please provide method to order submits in 'click' function as presented.
Thanks.
.post() method doesn't look to have a synch property. But .ajax() has.
I suggest you use the .ajax() method instead of the .post() shortcut method. That way you could force ajax to be synchronious
$.ajax({
[...]
async : false
}
you can use something like this
Form1SubmitOverloaded();
$.ajax({
type: "POST",
url: test1.php,
data: $( "#form1" ).serialize(),
success: function(){
Form2SubmitOverloaded();
$.ajax({
type: "POST",
url: test2.php,
data: $( "#form2" ).serialize(),
success: function(){
Form3SubmitOverloaded();
$.ajax({
type: "POST",
url: test2.php,
data: $( "#form2" ).serialize(),
success: function(){
alert("All submit successfully");
}
});
}
});
}
});

check if button was clicked in the controller

I have the following button and when clicked it's invoking a function,
Is there a way to know in the controller that this button was clicked ?
$("#RemoveFile").on("click", RemoveFile);
<button class="btn" style="height: 25px" type="button" id="RemoveFile"><p >Remove File</p></button>
As Edurado Says this the implementation which you asked to him
First set hidden field in html page (razor view/ aspx page)
<input type="hidden" id="StakeholderId" name="stakeholderId" />
Then add script like below
$( "#buttonID" ).click(function() {
$( "StakeholderId" ).val(true);
});
And get the value and posting the value to controller like below
var hidden= $('StakeholderId').val();
$.ajax({
type: "post",
url: "Controller/Method",
data: {
hiddenField1: hidden,
hiddenField2: "hiddenValue2",
},
success: function() {
alert("yay")
},
error: function(e) {
console.log(e);
}
});
Hope this helps....
When you click in the button, add an onclick event to this very button and save the clicked status in a hidden field. Then, whenever you send data to the controller, send this hidden field value, stating whether the button was clicked.
UPDATED:
Here is the HTML
<input id="hdnRemoveClicked" type="hidden" value="false" />
And here is the javascript which adds the click event in the button with ID="RemoveFile", and set the hidden field value as true, to show it is clicked.
$( "#RemoveFile" ).click(function() {
$( "hdnRemoveClicked" ).val(true);
// do other things, if needed
});
The only way I know of to so this in MVC is to make an Ajax call to the server via an anonymous function in the JQuery component. Example:
$("#RemoveFile").on("click", "RemoveFile", function () {
// tell server
var jqxhr1 = $.ajax({ type: 'POST', url: "/myControllerUrl",
data: { buttonID: "RemoveFile" } });
$.when(jqxhr1).done(function (response, textStatus, jqXHR) {
if (textStatus != "success") {
alert("Error, please try later");
return false;
}
// update the user interface
});
});
Make an ajax call to a method in Controller where a session keeps track if button was clicked.

Categories

Resources