Adding to JSON array by HTML button - javascript

I have an AJAX call, as below. This posts data from a form to JSON. I then take the values and put them back into the div called response so as to not refresh the page.
$("form").on("submit", function(event) { $targetElement = $('#response'); event.preventDefault(); // Perform ajax call // console.log("Sending data: " + $(this).serialize()); $.ajax({
url: '/OAH',
data: $('form').serialize(),
datatype: 'json',
type: 'POST',
success: function(response) {
// Success handler
var TableTing = response["table"];
$("#RearPillarNS").empty();
$("#RearPillarNS").append("Rear Pillar Assembly Part No: " + response["RearPillarNS"]);
$("#TableThing").empty();
$("#TableThing").append(TableTing);
for (key in response) {
if (key == 'myList') {
// Add the new elements from 'myList' to the form
$targetElement.empty();
select = $('<select id="mySelect" class="form-control" onchange="myFunction()"></select>');
response[key].forEach(function(item) {
select.append($('<option>').text(item));
});
$targetElement.html(select);
} else {
// Update existing controls to those of the response.
$(':input[name="' + key + '"]').val(response[key]);
}
}
return myFunction()
// End handler
}
// Proceed with normal submission or new ajax call }) });
This generates a new <select id="mySelect">
I need to now extract the value that has been selected by the newly generated select and amend my JSON array. Again, without refreshing the page.
I was thinking of doing this via a button called CreateDrawing
The JS function for this would be:
> $(function() {
$('a#CreateDrawing').bind('click', function() {
$.getJSON('/Printit',
function(data) {
//do nothing
});
return false;
});
});
This is because I will be using the data from the JSON array in a Python function, via Flask that'll be using the value from the select.
My question is, what is the best way (if someone could do a working example too that'd help me A LOT) to get the value from the select as above, and bring into Python Flask/JSON.

Related

Why Dropdown list data is refilling with same values, initially I'm loading the data using page_load and next calling ajax method in asp.net c#

Initially I'm loading the ddl data using page_load and next I'm using the AJAX method and fetching the dependency data using Web Method so when I'm selecting the dependency data using `AJAX' the data is coming but the ddl is filling with previous loaded dll data I'm not sure what is the issue.
Here is my code and examples :-
Initially I'm loading the ddl data using page_load event
if (!IsPostBack)
{
firstexpdate = GetExpDates("nifty", "ce");
firststrikeprice = GetStrikePrice("nifty", firstexpdate);
lotsize = GetLotSizeVal("nifty", firstexpdate);
ltpprice = GetGreeksPrice("nifty", firstexpdate, "ce");
}
Like below I'm getting the ddl data.
And here "NIFTY" textbox is autocomplete textbox if I enter minLength: 3 this logic will execute and once enter the acc the autocomplete logic will fire and able to fetching the data from WebMethod and next I'm calling the AJAX method(because once we select the autocomplete textbox data the next ce,date,13500 ... controls data should fill autometically) for auto filling the data.
Here is how I calling the AJAX method logic
$(document).ready(function () {
//Initially I'm calling this function
autocomplete();
//Page load even I written because I used all control under the `updatepanel`
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
autocomplete();
}
});
function autocomplete() {
$("#search").autocomplete({
source: function (request, response) {
// my source logic is here and able to fetching the data successfully
//once I fetch all the symbols and next I'm calling this method
doSearch(suburbs); //Calling the Symbol Display Method{in this suburbs I'm filling the response data}
},
minLength: 3 //This is the Char length of inputTextBox
});
}
function doSearch(suburbs) {
//And here I written all my required logic and next I'm calling this method for auto fill data
//Like how I explained above query
var smbltext = $(this).text(); //Here will come `ACC` Symbol in autocomplete textbox
AutoFillUsingSymbol(smbltext); // Filling the dependency fields data
}
//This is the full logic of auto filling the controls once we select the`autocomplete`textbox data
function AutoFillUsingSymbol(symbol) {
if (symbol != '') {
var paramsmbl = { entredsmbl: symbol, selectedinstrument: $('#AutoTradeTop_Instrument option:selected').text()};
//alert(paramsmbl.entredsmbl);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "AutoTrade.aspx/AutoFillData",
data: JSON.stringify(paramsmbl),
dataType: "json",
dataFilter: function (data) {
return data;
},
success: function (data) {
//Clearing before filling the data into ddl
$('#AutoTradeTop_expdate').empty();
$('#AutoTradeTop_strikeprice').empty();
$('#autotrade_lotsizeid').html('');
$('#LTPliveAmount').html('');
var length = data.d.length;
//data.d.each(function (index, element) {
//}
$.each(data.d, function (key, value) {
//alert(value);
if (value.indexOf("-") != -1) {
//alert(value + "date found");
$("#AutoTradeTop_expdate").append($("<option></option>").val(key).html(value));
}
else {
if (!(key == length - 2 || key == length - 1)) {
//alert(value + " value found ");
$("#AutoTradeTop_strikeprice").append($("<option></option>").val(key).html(value));
}
else {
if (key == length - 2) {
//alert(value + "LotSizeVal found");
$('#autotrade_lotsizeid').html(value);
}
else if (key == length - 1) {
//alert(value + "LTP Price found");
$('#LTPliveAmount').html(value);
}
}
}
});
},
error: function ajaxError(data) {
alert(data.status + ' : ' + data.statusText);
}
});
}
}
Once this AJAX logic hit AutoFillUsingSymbol(symbol) It will go to WebMehod logic and able to fetching the required data and filling into ddl list.
before filling into ddl data I'm clearing(emptying the dropdown list data) the ddl data and refilling
$('#AutoTradeTop_expdate').empty();
$('#AutoTradeTop_strikeprice').empty();
$('#autotrade_lotsizeid').html('');
$('#LTPliveAmount').html('');
Here is the example image of auto filling data once we select acc symbol and date is loading what I selected symbol acc
But if I select any one date the dropdown list data is clearing and filling the previous symbol data `nifty' see the above first image for reference.
example image
Note :- I know if we fill or change the dropdownlist client side code, then the list of values does not persist but initially I filled the ddl data in the page_load event and next I wrote the AJAX method but why the values are not loading properly.
Suggest me what is the issue and where I did the mistake
I'm beginner in the client side code development .

jQuery: How to get input value within an ajax call?

I have a jQuery script, in which I need to load data from a CSV from an external URL.
At the same time, I need to combine the data from the CSV with data provided by a frontend user through an input field. My expected result would be that I'd be able to call the jQuery code for fetching the value from the user's entry into the input field. However, while this works when the code is placed outside the ajax call, it does not work inside.
At the same time, I can't place the code for fetching the user's input outside the ajax call, as I need to be able to utilize information from the loaded CSV together with the user input to perform a dynamic calculation.
My code is as below:
HTML:
<input type="text" id="my_input" value="12" maxlength="2">
Javascript:
$.ajax({
url: csv_url,
async: false,
success: function (csvd) {
var csv = $.csv.toObjects(csvd);
// XYZ done with the CSV data to populate various fields
$("#my_input").keyup(function () {
console.log(this.value);
// this does not result in anything being logged
});
},
dataType: "text",
complete: function () {}
});
Of course it will not work. You are telling the compiler to add the keyup event listener to input after the ajax call is successful. Which means it will not work until ajax call is completed successfully.
You need to put the keyup event listener outside and inside the ajax call just get the value like below:
let myInputValue = "";
$("#my_input").keyup(function () {
console.log(this.value);
myInputValue = this.value;
});
$.ajax({
url: csv_url,
async: false,
success: function (csvd) {
var csv = $.csv.toObjects(csvd);
// XYZ done with the CSV data to populate various fields
//And later use the myInputValue here
},
dataType: "text",
complete: function () {}
});
You have not give us enough info. if you only need the current value in the ajax call you can do like below:
$.ajax({
url: csv_url,
async: false,
success: function (csvd) {
var csv = $.csv.toObjects(csvd);
// XYZ done with the CSV data to populate various fields
let myInputValue = $("#my_input").val();//And later use the myInputValue here
},
dataType: "text",
complete: function () {}
});

POST output into a modal from any form class on page

Sorry I am a beginner with jQuery and Javascript. I want to be able to get the results into my modal from any form on the page that has class ajax. My code is below but not working correctly. Currently it opens the post result in a new page and not in the modal. Can anyone shed any light on my code?
Many thanks
$(document).ready(function() {
$('.ajax').click(function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('name').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
console.log(value);
// AJAX request
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
// Add response in Modal body
$('.modal-body').html(response);
// Display Modal
$('#aaModal').modal('show');
}
});
});
});
This probably happens because your browser submits the form by default. It doesnt know youre doing AJAX stuff. To prevent this, use preventDefault().
In addition to that, jQuery has a built in function for serializing (1 and 2) form data.
$(document).ready(function() {
$('form.ajax').click(function(event) {
event.preventDefault(); // prevents opening the form action url
var $form = $(this),
url = $form.attr('action'),
type = $form.attr('method'),
data = $form.serialize();
// console.log(value); // value doesnt exist outside of your loop btw
// AJAX request
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
// Add response in Modal body
$('.modal-body').html(response);
// Display Modal
$('#aaModal').modal('show');
}
});
});
});
Also, its not quite clear if you bind the click event handler to a form or a button, I guess the first one. You should change the handler to the following:
$(document).ready(function() {
$('form.ajax').on('submit', function(event) {

parse name from user input when using jquery serialize

I am trying to grab user input from a dynamic form using jquery serialize. My form looks like this
<form id="lookUpForm">
<input name="q" id="websterInput" />
<button onclick="webster(); return false;">Search</button>
</form>
I want to take the input, and attach it to the end of websters dictionary URL to search for a word.
http://www.merriam-webster.com/dictionary/ + (user input)
When you run an alert to see what the value of 'q' is, you get
q=input
so for example if I put 'cats'
the alert would say q=cats.
I want the the string to just be what the user entered. However, you need to give the input a name to use seralize. So how can I take the user input, and strip out the 'q=' part.
EDIT
as requested here is the function I'm calling. Note. I HAVE to use serialize(); This isnt an option.
function webster() {
var stringHolder = $("#lookUpForm").serialize();
alert(stringHolder);
$.ajax({
type: 'GET',
crossDomain: 'true',
url: "http://www.merriam-webster.com/" + stringHolder,
success: function (data) {
console.log(data);
console.log("http://www.merriam-webster.com/" + stringHolder);
},
error: function () {
alert("Failed to get dictionary data");
console.log("http://www.merriam-webster.com/dictionary/" + stringHolder);
}
});
};
You can just access it using val method of jQuery
function webster() {
var stringHolder = $("#lookUpForm").serialize();
alert(stringHolder);
$.ajax({
// (...) removed some code for brevity
error: function () {
alert("Failed to get dictionary data");
console.log("http://www.merriam-webster.com/dictionary/" +
$('#websterInput').val()); // I suppose you want the user-input here
}
});
};
You could use serializeArray().
And then do something like this and put your string together like you want to
var array = $("#lookUpForm").serializeArray();
$(array ).each(function(){
alert(this.value);
});

How to prevent jQuery ajax submit form on page

I have two ajax calls on a page. There are text inputs for searching or for returning a result.
The page has several non ajax inputs and the ajax text input is within this . Whenever I hit enter -- to return the ajax call the form submits and refreshes the page prematurely. How do I prevent the ajax from submitting the form when enter is pressed on these inputs? It should just get the results.
However, I cannot do the jquery key press because it needs to run the ajax even if the user tabs to another field. Basically I need this to not submit the full form on the page before the user can even get the ajax results. I read return false would fix this but it has not.
Here is the javascript:
<script type="text/javascript">
$(function() {
$("[id^='product-search']").change(function() {
var myClass = $(this).attr("class");
// getting the value that user typed
var searchString = $("#product-search" + myClass).val();
// forming the queryString
var data = 'productSearch='+ searchString + '&formID=' + myClass;
// if searchString is not empty
if(searchString) {
// ajax call
$.ajax({
type: "POST",
url: "<?php echo $path ?>ajax/product_search.php",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#results" + myClass).html('');
$("#searchresults" + myClass).show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results" + myClass).show();
$("#results" + myClass).append(html);
}
});
}
return false;
});
$("[id^='inventory-ESN-']").change(function() {
var arr = [<?php
$j = 1;
foreach($checkESNArray as $value){
echo "'$value'";
if(count($checkESNArray) != $j)
echo ", ";
$j++;
}
?>];
var carrier = $(this).attr("class");
var idVersion = $(this).attr("id");
if($.inArray(carrier,arr) > -1) {
// getting the value that user typed
var checkESN = $("#inventory-ESN-" + idVersion).val();
// forming the queryString
var data = 'checkESN='+ checkESN + '&carrier=' + carrier;
// if checkESN is not empty
if(checkESN) {
// ajax call
$.ajax({
type: "POST",
url: "<?php echo $path ?>ajax/checkESN.php",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#esnResults" + idVersion).html('');
},
success: function(html){ // this happens after we get results
$("#esnResults" + idVersion).show();
$("#esnResults" + idVersion).append(html);
}
});
}
}
return false;
});
});
</script>
I would suggest you to bind that ajax call to the submit event of the form and return false at the end, this will prevent triggering default submit function by the browser and only your ajax call will be executed.
UPDATE
I don't know the structure of your HTML, so I will add just a dummy example to make it clear. Let's say we have some form (I guess you have such a form, which submission you tries to prevent)
HTML:
<form id="myForm">
<input id="searchQuery" name="search" />
</form>
JavaScript:
$("#myForm").submit({
// this will preform necessary ajax call and other stuff
productSearch(); // I would suggest also to remove that functionality from
// change event listener and make a separate function to avoid duplicating code
return false;
});
this code will run every time when the form is trying to be submitted (especially when user hits Enter key in the input), will perform necessary ajax call and will return false preventing in that way the for submission.

Categories