How do I store drop down value in AJAX call? - javascript

I am having a form in which I have a drop down list. The drop down list is getting populated inside an AJAX call. There is a button, clicking on which sends an AJAX call and returns data to be filled as options to the drop down list.
Now, If the option is selected and the form is submitted successfully, then the selected value gets stored in the database.
But, If I select an option in the drop down and if there are some validation issues in my form, then on submit, the page shows the error and it "refreshes". This leads to the options which were populated during AJAX call to disappear since there is no ajax call again to populate the list.
So, How do I store the value during the first AJAX call such that on page refresh, the value is stored or populated.
If the list were populated manually i.e If I knew the options beforehand, I could have stored the selected value in a hidden variable but I can't do it here.
Here is my AJAX function:
$.ajax({
type: "POST",
dataType: 'json',
url: "/Controller/Action",
data: {
param: param,
},
success: function(data) {
if (data.Response == "Unsuccessful") {
console.log("Unsuccessful");
} else if (data.Response == "Successful" || data.Response == "ConditionallySuccessful") {
for (var i = 0; i < data.ExteriorColor.Data.length; i++) {
//This is the drop down list which is populated
$("#Exterior_Color").append($("<option></option>").val(data.ExteriorColor.Data[i]).html(data.ExteriorColor.Data[i]));
console.log(data.ExteriorColor.Data[i]);
}
}
},
error: function(result) {
console.log("Error while fetching data");
}
});

Try localstorage, use it after the success in ajax call.
Saving the dropdown object:
//SAVING (put after the ajax call)
var myList= $("#Exterior_Color");
// Put the object into storage
localStorage.setItem('myList', JSON.stringify(myList));
And the restore part:
//RESTORING (put after the page refresh)
// Retrieve the object from storage
var retrievedMyList = localStorage.getItem('myList');
console.log('myList: ', JSON.parse(retrievedMyList ));

Related

Ajax is not sending multiselect data to Django views

I am quite new to Django so bare with me.
I have a multiselct list in my webpage and I need to send the selected items to my views in order to make use of them.
To do so, I used ajax but when it doesn't seem to work for some reason.
This is the script:
$("#var_button").click(function(e) {
var deleted = [];
$.each($("#my-select option:selected"), function(){
deleted.push($(this).val());
});
alert("You have deleted - " + deleted);
e.preventDefault();
$.ajax({
type: "post",
url: "/description/upload-csv/" ,
data: {
'deleted' : deleted }
}); // End ajax method
});
I checked with alert if maybe the variable deleted is empty but it return the selected values so the problem is in my ajax query.
This is the part where I retrieve the data in my views.py
if request.method == 'POST':
del_var = request.POST.getlist("deleted[]")
my_class.del_var = del_var
I changed the data type to text but it doesn't do anything
I cant help you on the Django side.
$.each($('#selector'), (i, e) => {
deleted.push($(e).val());
})
but this will add the value to the "deleted" variable.

On click function that sends data with AJAX to a php file for it to be saved in the database only works once

I am trying to create a remove button in an "edit form" code I've been working in. The button 1) gets the ID of the its div parent and then 2) gets the value of the inputs inside of named parent in order to 3) send them with an AJAX call to a PHP file that works on 4) inserting that information inside a table in the database.
At first, the code works as it should. It inserts the information into the database and retrieves it while modifying an existing div. But it only works once. When other button with the same class (and therefore the same function) is clicked, the success:function works just fine and shows the corresponding data, but does not save the data into the database as the previous button did. If I reload the page, again, any button works, but the data it's being saved just once.
I've tried using cache: false, but when I place it into my AJAX call, the buttons stop working completely.
$(document).on('click','.removeQe',function(e) {
var reId = $(this).attr('id');
var box = $('#'+reId+'').parent().parent().attr('id');
var input1 = $('#'+box+'').find('.del-exam-id').val();
var input2 = $('#'+box+'').find('.del-id').val();
var input3 = $('#'+box+'').find('.del-table').val();
var input4 = $('#'+box+'').find('.del-id-form').val();
var values = {
'examID': input1,
'questionID': input2,
'Info': input3,
'idForm': input4
};
$.ajax({
url: "edit-delete.inc.php",
type: "POST",
data: values,
success: function(data)
{
$('.show-data').html(data);
$('#'+box+'').remove();
$('.countTQ').each(function(index) { $(this).find('h3').html('Question #'+(index+1)+''); });
$('.audio-box').each(function(index) { $(this).find('h3').html('Audio #'+(index+1)+''); });
}
});
});

How to detect that my select form have been change by ajax success

I have two form input ( text and select form ).
The select form change by ajax success when user search the employee data.
Now, i want the other jquery function that can automatically detect when the select form have been change by ajax success and retrieve the new value of select form to use by other function to make new data in my input text.
my Search Employee Function
function search_personal_result(formObj, urlres, responseDIV, disable_data, modal_class,result_data)
{
disable_data=disable_data||false;
modal_class=modal_class||false;
result_data=result_data||false;
var loading = '<p>Loading ...</p>';
$.ajax({
url: site_url+'/'+urlres,
beforeSend: function(){
$(responseDIV).html(loading);
},
data: $(formObj).serialize(),
type: "post",
dataType: "html",
success: function(response){
//proceed data result here
if(result_data==false){
var obj = jQuery.parseJSON(response);
$.each(obj, function (index, value) {
if(result_data==false){
for(var j in value){
//My SELECT Form Changed here
$('#VCIDSBU').val('MY NEW VALUE');
}
}
});
}
},
error: function(){
alert("Terjadi kesalahan!");
},
});
}
If the user search the employee data using search_personal_result, my select form have been successfully changes.
Now that i need is, how to make the other jQuery function that can detect that my SELECT Form have been changed by search_personal_result
I have try using
$(function () {
$('#form_create_sp').on('change','SELECT#my_select_id',function(){
alert('it changes');
});
})
It can only detect when the user manually change the select form. but not working when the select form changed by search_personal_result
Thanks for all expert here
You could always do some sort of console.log("Success"); Function based on if it sent or not.

don't perform database query request during ajax call if request was already done and data is available

I have a button in my view that when clicked triggers an ajax request for data on the database. Then I show the data in my page. I want to be able to hide the data if the button is clicked again and show it if it's clicked a second time and so on. I don't want to perform a new DB query everytime I click it.
so for example my request is like this:
$.ajax({
url: '../route/button,
type: 'get',
data: {_method: 'get', _token: token},
success: function (data) {
// bla bla get data from DB and insert in div
});
so once I clicked I have the data, then I click the button again and I want to toggle(); the div and data disappears from page but then if I click again I want to just toggle the div again and show the data that's already there without performing the DB query again.
Any clue?
You'll have to save the data from the ajax request. Then each time the button is clicked check to see if you have data saved. See this fiddle for an example.
;(function() {
var data = null,
$output = $('#output');
$output.hide();
$('#button').on('click', function() {
if (data === null) {
// ajax request
data = {
foo: 'bar'
};
console.log('fetching data');
// populate table with data
}
$output.toggle();
});
})();

Binding Repeater with entity framework and Jquery/Ajax

I want to bind repeater with entity framework, that call a procedure in database(Speed purposes), i create an ajax web method to be called from jquery code to sent parameters. so it will decide what data to display.
Below is the ajax call that will sent the parameter to showResult web method, i use the ajax code to handle all data within one page, because i have drop down lists to handle user selections(every selection reflect a query in database).
$.ajax({
url: "WebService.asmx/showResult",
type: "post",
data: JSON.stringify({
"dateFrom": $('#txtDateFrom').val(),
"dateTo": $('#txtDateTo').val(),
"ddlType": $("#ddlType").children("option").filter(":selected").val(),
"ddlTer": $("#ddlTer").children("option").filter(":selected").val()
}), // parameters
beforeSend: function () {
$('#loader').html('<img src="Images/loading.gif" />');
},
contentType: "application/json; charset=utf-8",
success: function (result) {
$('#loader').html('');
//To delete the whole tr except the first one.
$("#tblUsers").find("tr:gt(0)").remove();
$('#tblUsers').append(JSON.stringify(result));
},
error: function () {
alert('error');
}
});
also, below is the web method showResult code that will call the proc with parameters:
public string showResult(DateTime dateFrom, DateTime dateTo)
{
string result = " ";
var sp = db.select_alltypes(dateFrom, dateTo).ToList();
foreach (var u in sp)
{
result += "<tr>";
result += "<td>"+u.depno+"</td>";
result += "</tr>";
result += "</table>";
}
return result;
}
I used to return a table and to append it to the table in .aspx page but i stop, because I want to show 3 tables in the page every table data will present an execution of procedure so, I don't know how to handle this, instead of tables i use 3 repeaters.
so i want to a way to change the DataSource of the repeater immediately whenever the user press a button.
Note: If any one have an idea to present three tables instead of using
repeaters, please provide it here.

Categories

Resources