Set form data without creating DOM inputs - javascript

I have an empty form tag, and a function which generates 4000 hidden inputs which contains the data to be send by the form.
Generating the 4000 hidden inputs is pretty fast (takes about 4ms). However, the browser freezes for about 1 second when i am appending the hidden inputs in the form tag.
I have also wrapped the hidden inputs in a <div/> tag, but doesn't helps too much.
Is there any way to set the form data programmatically, without using the input DOM elements?
Something like:
$form[0].setData([{ id: 1, value: "A" }, { id: 2, value: "B" }]);
$form.submit();
Here is the function which generates the hidden inputs
function saveUIPositions() {
var $form = $("#saveUIPositionsForm");
$form.empty();
console.time("ui");
var array = [];
array.push("<div>");
var items = dataTable.dataView.getItems();
for (var i = 0, len = items.length; i < len; i++) {
var item = items[i];
var index = dataTable.dataView.getRowById(item.Id) + 1;
array.push("<input type='hidden' name='[");
array.push(i);
array.push("].Item_Id' value='");
array.push(item.Id);
array.push("' />");
array.push("<input type='hidden' name='[");
array.push(i);
array.push("].Index' value='");
array.push(index);
array.push("' />");
}
array.push("</div>");
console.timeEnd("ui");
// here it gets very costly (and not because of array.join())
$form.append(array.join(""));
$form.submit();
};

Maybe you can send this data using ajax ? If so you will not have to generate and append your 4K hidden inputs to the DOM.
If ajax is not an option, can you give us the code generating and appending your inputs ? Maybe it can be optmized.
I wrote a small jsFiddle (open your debug console to see time informations)
to illustrate the difference between a generate then append all solution:
for(var i=0; i<4000; i++)
inputs += '<input type="hidden" value="' + i + '"/>'
$('form').append(inputs);
and generate and append each:
for(var i=0; i<4000; i++)
$form.append('<input type="hidden" value="' + i + '"/>');

You don't even really need a form element when working in just Javascript, data can be sent to your server with an ajax request.
$.ajax({
url: "myScript.php", //The script on your server that deals with the data
data: {
dataA: "a",
dataB: "b",
dataC: "c" //Your form input name and value key pairs
},
success: function(data){
alert("Form Submitted, Server Responded:"+data); //The server response
},
error: function(data){
alert("Error contacting server:"+data); //Error handler
}
});
You don't even need to reload the page when the form is submitted. Unless you want to, then just add:
location.href="http://link.com";
to the success callback.

You don't need to add the inputs to the DOM, you could create an array of the data an post the form via ajax e.g.
inputNames = 'YourInputNameHere'; // Could be an array of names
generatedData = arrrayOfData //presumably generated elsewhere
for (i=0;i<400;i++) {
formData[inputName][i] = generatedData[i]
// if you are using an array of names you want to change the above line to
// formData[inputName[i]] = generatedData[i]
}
$('body').on('submit', '#myForm', function(e) {
e.preventDefault();
postUrl = 'url/to/send/data';
// get any other use inputs that might have been taken from user ignore
// this line if there are no inputs
formData[] = $(this).serialize();
$.ajax(
{
url: postUrl,
type: 'POST',
data: formData,
dataType: 'html',
success: function( data )
{
// redirect, post message whatever
}
}
)
});
Hope this helps and makes sense.

Related

Adding to JSON array by HTML button

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.

Need to submit form multiple times with javascript

As the title says I need to submit a form multiple times, form's action is an external php file. The form submits once but I need it to submit once with each loop.
function send_sms(){
var receivers = document.getElementById('receivers').value.toString();
var receivers_array = receivers.split(',');
for(var i = 0; i < receivers_array.length; i++) {
// Trim the excess whitespace.
receivers_array[i] = receivers_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
document.getElementById('receiver').value = receivers_array[i];
document.getElementById("smsForm").submit();
}
}
What the code is basically supposed to do is split up phone numbers that the user enters and send a text message to each of the numbers. It submits and a text is sent to the first number in the array but not the other entered numbers. Spliting and everything works(I've used console.log on everything to check). The loop isn't interrupted either because it console logged each receiver value after assigning it inside the loop.
UPDATE: Got it working like this
function send_sms(){
var receivers = document.getElementById('receivers').value.toString();
console.log(receivers);
var receivers_array = receivers.split(',');
console.log(receivers_array[0]);
for(var i = 0; i < receivers_array.length; i++) {
// Trim the excess whitespace.
receivers_array[i] = receivers_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
document.getElementById('receiver').value = receivers_array[i];
console.log(document.getElementById('receiver').value);
//document.getElementById("smsForm").submit();
$.ajax({
url:'../API/sendsms.php',
type:'post',
data:$('#smsForm').serialize(),
success:function(){
alert("worked");
}
});
}
}
Submit triggers page reload/redirect to your action. You have to add ajax listener for your form submit so it won't refresh the page every time the submit triggers.
$(document).on('submit', 'form#smsForm', function() {
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
console.log('Submitted');
},
error: function(xhr, err) {
console.log('Error');
}
});
return false;
});
function send_sms() {
var receivers = document.getElementById('receivers').value.toString();
var receivers_array = receivers.split(',');
for (var i = 0; i < receivers_array.length; i++) {
// Trim the excess whitespace.
receivers_array[i] = receivers_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
document.getElementById('receiver').value = receivers_array[i];
document.getElementById("smsForm").submit();
}
}
You can try collect all numbers and send them in one request, after this parse them on backend side and send sms

Ajax sends two files at one time through one onclick event in JavaScript

jQuery AJAX seems to be sending two requests at once when I use the onclick event with JavaScript in a tag. I click once, and that seems ok, but when I change the id value to an invalid id value, it sends two requests to the PHP file. I think the problem may be caused by the browser caching JavaScript code.
Here's is the JavaScript code I'm using to generate the query:
function unlike_image(id, image_id, obj) {
var url_unlike_image = base_url + 'profile/unlike_image';
$.ajax({
type: "POST",
data:
{
user_id: id,
image_id: image_id
},
url: url_unlike_image,
success: function(data) {
if (data.status=='error_exists') {
alert('This image not exists');
}
if (data.status=='success') {
//like = like - 1 for view
var str = $(obj).next().text();
var n = str.length;
str_like = str.substring(1, n-1);
var number_likes = parseInt(str_like) - 1;
$(obj).next().text('('+number_likes+')');
//change event click unlike
$(obj).text('Like');
$(obj).attr('onclick', 'like_image('+id+' ,'+image_id+ ',this); return false');
}
}
});
}
After changing the true id to the wrong id, I check the website traffic, I see two instances where unlike_image is called. The first is with the true id, and the second is with the wrong id.

dynamically assign object properties in jquery/javascript to post through ajax

i am trying to dynamically have javascript object properties to send through ajax..
Here is what i have done..
var checkBoxName = $(this).attr('name');
var postData = {
Module: ModuleID,
Group:GroupID
};
if($(this).is(":checked")){
postData.checkBoxName = 1;
}else{
postData.checkBoxName = 0;
}
$.ajax({
url: "<?php echo base_url(); ?>user_site/user_group_add_pri/updatePrivilege",
data:postData,
type: "POST",
success: function (output) {
console.log(output);
}
i have multiple checkboxes. every checkbox has different name so what i am trying to do is post data to controller with checkbox name and its value..
but instead it is sending checkBoxName for all checkboxes...
i mean CheckBoxName is a variable but when i did used it like this cuz i thought it would send its value but it is not sending,
i tried like this postData.checkBoxName = but instead of value of variable it is sending as Text??
=-=-=-=-=-=-=-=-=-=--=-=-=-=-=
Update:
The event Occurs when checkbox value is changed.
$("input[type='checkbox']").on('change',function(e){
///Above Code Inside Here
}
If I understand right, I might have an idea.
You can do a loop through all your checkboxes and check if they are checked or not. Then push it into a tab and send through ajax :
var infoCb = new Array();
$('input[type=checkbox]').each(function(){
var tempArray = {
'nameOfCb' : $(this).attr('name'),
'value' : $(this).attr('checked')
}
infoCb.push(tempArray);
});
And then send it via Ajax.

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