Is there a way to improve this? Can't find a way to improve..
var $submit = $('#submit-form');
$submit.off('click').on('click', function(e) {
e.preventDefault();
var checkedBOX = $('#checkboxes').find('input:checked');
var servers = [];
$.each(checkedBOX, function(k, v) {
var v = $(v);
servers.push(v.val());
v.prop("checked", false);
});
var doneCount = 0;
$.each(servers, function(key, server) {
$.ajax({
type: "POST",
url: window.location.href,
data: $('#form').serialize() + '&server=' + server + '&submit=',
success: function (data) {
doneCount++;
if (doneCount >= servers.length) {
window.location.reload();
}
}
})
});
});
Can't figure it out what is the best way to make it faster..
Could anyone help me out here?
try this way , remove loop
$(document).on('submit','#submit-form',function(e){
e.preventDefault();
var checkedBOX = $('#checkboxes').find('input:checked');
var servers = [];
$("input:checkbox[name=checkbox]:checked").each(function(){
servers.push($(this).val());
});
console.log(servers);
$.ajax({
type: "POST",
url: window.location.href,
data: $('#submit-form').serialize() + '&server=' + servers + '&submit=',
success:function(data){
window.location.reload();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST" id="submit-form">
<input type="text" name="name" placeholder="NAME"/>
<br/>
<input type="text" name="email" placeholder="EMAIL"/>
<br/>
<input type="checkbox" name="checkbox" value="1" />
<input type="checkbox" name="checkbox" value="2" />
<input type="checkbox" name="checkbox" value="3" />
<input type="checkbox" name="checkbox" value="4" />
<br/>
<button type="submit">SUBMIT</button>
</form>
Related
<script>
$('input[type="checkbox"]').on('change', function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var data = {},
fdata = [],
loc = $('<a>', {href:window.location})[0];
$('input[tpye="checkbox"]').each(function(i){
if(this.checked){
if(!data.hasOwnProperty(this.name)){
data[this.name] = [];
}
data[this.name].push(this.value);
}
});
$.each(data, function(k, v){
fdata[k] = [v.join(',')];
});
fdata = fdata.join('&');
$.post('/wines/all-wines/', fdata);
console.log(fdata);
if(history.pushState){
history.pushState(null, null, loc.pathname+'?'+fdata);
}
});
<div class="panel-body">
<div class="rowElem">
<input type="checkbox" name="country" value="1" id="">
<label>Color #1</label>
</div>
<div class="rowElem">
<input type="checkbox" name="country" value="2" id="">
<label>Color #2</label>
</div>
<div class="rowElem">
<input type="checkbox" name="country" value="3" id="">
<label>Color #3</label>
</div>
</div>
I'm using laravel thats why i'm passing X-CSRF token. What i want to achieve is when user clicks on one or more checkboxes it automatically change url to something like this : link.com/products/all-products?country=1,2,3,4,5
but after clicking on checkboxes it only change url to : link.com/products/all-products? and thats mainly it. What could be wrong in the code? Thank you very much!
In addition to what nbkHope pointed out you need the following:
$.each(data, function(k, v){
fdata[k] = [v.join(',')];
});
var countryArr = fdata["country"];
fdata = countryArr.join('&');
Your array looks like this: {country: Array()}, so you need to get country out of fdata and then call join.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
I've a problem to retrieve my data from database.
In my Ajax call, i have tested my form values and it worked.
$(document).ready(function(){
$("form#form").submit(function(event) {
event.preventDefault();
var color = $('#Color').val();
var radio = $('input[name="filter_opties"]:checked').val();
filter(color, radio);
$.ajax({
type: "POST",
url: "db_querys.php",
data: {'color' : color, 'radio' : radio},
success: function(data) {
alert(data);
}
});
});
But in my db_querys.php, I can't get the values of color and radio.
<?php
$gekozenGemeente = $_POST['color'];
$gekozenCategorie = $_POST['radio'];
if($gekozenGemeente != null)
{
echo $gekozenGemeente . $gekozenCategorie;
}
else
{
echo "<br> Values are null";
}
?>
This is my form:
<form id = "form" action="#" method="post" >
<!----- Select Option Fields Starts Here ----->
<label class="heading">Selecteer uw gemeente:</label>
<br>
<select name="Color" id="Color">
<option value="heemstede">Heemstede</option>
<option value="bloemendaal">Bloemendaal</option>
</select>
<br>
<!---- Radio Button Starts Here ----->
<label class="heading">Radio Buttons :</label><br>
<input type="radio" id="radio1" name="filter_opties" value="Betaald"><label for="radio1">Betaald</label><br/>
<input type="radio" id="radio2" name="filter_opties" value="Vergunning"><label for="radio2">Vergunning</label><br/>
<input type="radio" id="radio3" name="filter_opties" value="Blauwe zone"><label for="radio3">Blauwe zone</label><br/>
<br>
<input id= "submit" name="submit" type="submit" value="Get Selected Values" onclick="filter()">
</form>
Can you guys explain what I'm missing?
EDIT: Added the filter function.
function filter(color, radio){
var locations = <?= json_encode($markers_json ); ?>;
var locations2 = JSON.parse(locations);
var polygons = <?=json_encode($polygons_json );?>;
//var polygons2 = JSON.parse(polygons);
//document.getElementById("demo").innerHTML = polygons2;
initialize(locations2,polygons)
}
$(document).ready(function(){
$("#form").submit(function(event) {
event.preventDefault();
var color = $('#Color').val();
var radio = $('input[name="filter_opties"]:checked').val();
filter(color, radio);
$.ajax({
type: "POST",
url: "db_querys.php",
data: {'color' : color, 'radio' : radio},
success: function(data) {
alert(data);
}
});
});
When I press on my edit button I call a webservice function and it return a list of question parameter and it's working the function return the right value for each edit button but after returning the value I have a post back and all my html input that I fill in this function they are clear again, why?
JavaScript and jQuery:
$(document).ready(function () {
$('.divPreview').on("click", ".editbtn", function () {
var idQ = 0;
idQ = $(this).val();
var Did = { 'Qid': idQ };
alert(idQ);
$.ajax({
type: "POST",
async: false,
url: "/WebService.asmx/GetQuestion",
data: JSON.stringify(Did),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: function (r) {
alert(r.responseText);
},
failure: function (r) {
alert(r.responseText);
}
});
function OnSuccess(response) {
var question = response.d;
$(".dropdown_fields").html('<select id="dplQuestionType" class="dropdown_selector"><option value="radio">Radio Button</option> <option value="checkbox">Check Box</option></select>');
$(".input_field").html('<p>Q1:<input id="txtQuestion" type="text" /></p> <p> Answer Choices:</p><div><input id="hdnC1" type="hidden" value="0" /><input id="txtC1"type="text" name="mytext[]" /><input id="cbActive1" type="checkbox" /></div><div><input id="hdnC2" type="hidden" value="0" /><input id="txtC2" type="text" name="mytext[]" /><input id="cbActive2" type="checkbox" /></div>');
$(".OtherOption").html('<input id="btnAddField" class="btnAddField" type="button" value="Add Choices"/><br>Page Number<input id="txtPageNumber" type="text" /> Question Order: <input id="txtOrder" type="text" /><br/><p><input id="cbCommonField" type="checkbox" />Add a Common Field</p><br/>Is Required<input id="cbIsRequire" type="checkbox" />Is Active<input id="cbIsActive" type="checkbox" /><br/>Hint:<textarea id="txtaHint" rows="2" cols="20"></textarea> ');
$(".ButtonField").html('<p><input id="btnSave" type="button" value="Save" onclick="GetQuestionInfo()" /> <input id="btnCancel" class="btnCancel" type="button" value="Cancel" /></p>');
document.getElementById("btnAddQuest").style.visibility = 'hidden';
document.getElementById("txtOrder").value = question.qst_Order;
document.getElementById("txtPageNumber").value = question.qst_PageNumber;
document.getElementById("cbIsRequire").value = question.qst_Order;
document.getElementById("cbIsActive").value = question.qst_Order;
document.getElementById("txtaHint").value = question.qst_Hint;
document.getElementById("dplQuestionType").value = question.qst_Type;
document.getElementById("hdnQuestionID").value = question.qst_Id;
alert(question.qst_txt);
}
});
});
You aren't actually doing a ajax request you are simply doing a normal post request from a form, to do a ajax request prevent the default submit using e.preventDefault();
$('.divPreview').on("click", ".editbtn", function (e) {
e.preventDefault();
In my abc.html I have the following code which will covert the form data(hard coded for now) to JSON format:
<body>
<form enctype='application/json' method="POST" name="myForm">
<p><label>Company:</label>
<input name='Company' value='TESTCOMPANY'> </p>
<p><label>User Id:</label>
<input name='User' value='TESTUSER'></p>
<p><label>Division:</label>
<input type="text" name='parameterMap[p1]' value='12345' ></p>
<p><label>From:</label>
<input type="text" name='parameterMap[p2]' value='20-MAR-2016'></p>
<p><label>To:</label>
<input type="text" name='parameterMap[p3]' value='22-MAR-2016'></p>
<input value="Submit" type="submit" onclick="submitform()">
</form>
</body>
From the code above I get *
{"Company":"TESTCOMPANY","User":"TESTUSER","parameterMap":{"p1":"12345","p2":"20-MAR-2016","p3":"22-MAR-2016"}}*
Now I need to assign the Json String formed by this data to variable 'FormData' so that FormData is like:
FormData = '{"Company":"TESTCOMPANY","User":"TESTUSER","parameterMap":{"p1":"12345","p2":"20-MAR-2016","p3":"22-MAR-2016"}}'
How do I do this assignment of data ?
The further code in abc.html will use this variable FormData in the following way:
function sendAjax() {
$.ajax({
url : "myurl",
type : 'POST',
dataType : 'json',
data : FormData,
contentType : 'application/json',
mimeType : 'application/json',
success : function(data) {
alert(data.uuid);
},
error : function(data, status, er) {
alert("error: " + data + " status: " + status + " er:" + er);
}
});
}
If you are not handling this in backend you can retrieve the data in Javascript in a variable then just appned it as JSON to your data using JSON.stringify().
This is a working snippet:
function submitform() {
var FormData = {
Company: myForm.Company.value,
User: myForm.User.value,
parameterMap: {
p1: myForm.p1.value,
p2: myForm.p2.value,
p3: myForm.p3.value
}
};
console.log(FormData);
$.ajax({
url: "myurl",
type: 'POST',
dataType: 'json',
data: JSON.stringify(FormData),
contentType: 'application/json',
mimeType: 'application/json',
success: function(data) {
alert(data.uuid);
},
error: function(data, status, er) {
alert("error: " + data + " status: " + status + " er:" + er);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form enctype='application/json' method="POST" name="myForm">
<p>
<label>Company:</label>
<input name='Company' value='TESTCOMPANY'>
</p>
<p>
<label>User Id:</label>
<input name='User' value='TESTUSER'>
</p>
<p>
<label>Division:</label>
<input type="text" name='p1' value='12345'>
</p>
<p>
<label>From:</label>
<input type="text" name='p2' value='20-MAR-2016'>
</p>
<p>
<label>To:</label>
<input type="text" name='p3' value='22-MAR-2016'>
</p>
<input value="Submit" type="submit" onclick="submitform()">
</form>
Notes:
Use Javascript naming conventions, for example FormData will better be formData.
Using the provided HTML structure you could get the data into the format using:
function submitform(){
var form = document.querySelector('form');
var result = {};
var input = form.getElementsByTagName('input');
for(var i = 0; i < input.length; i ++) {
var row = input[i];
var rowName = ((row.name || '').match(/(\w+)(\[(\w+)\])?/) || []);
var rowIndex = rowName[3];
rowName = rowName[1];
if(rowName) {
var typeOfRowIndex = typeof rowIndex;
var rowValue = row.value;
if(typeof result[rowName] === 'undefined') {
var rowToAdd = {};
rowToAdd[rowIndex] = rowValue;
result[rowName] = typeOfRowIndex === 'undefined' ? rowValue : rowToAdd;
} else if(typeOfRowIndex !== 'undefined') {
result[rowName][rowIndex] = rowValue;
}
}
}
document.getElementById('output').innerHTML = JSON.stringify(result)
console.log(result);
return false;
}
<body>
<form enctype='application/json' method="POST" name="myForm">
<p>
<label>Company:</label>
<input name='Company' value='TESTCOMPANY'>
</p>
<p>
<label>User Id:</label>
<input name='User' value='TESTUSER'>
</p>
<p>
<label>Division:</label>
<input type="text" name='parameterMap[p1]' value='12345'>
</p>
<p>
<label>From:</label>
<input type="text" name='parameterMap[p2]' value='20-MAR-2016'>
</p>
<p>
<label>To:</label>
<input type="text" name='parameterMap[p3]' value='22-MAR-2016'>
</p>
<input value="Submit" type="submit" onclick="return submitform()">
</form>
<p>JSON Output (after clicking submit button):</p>
<div id="output"></div>
<p>Can also check console to see JSON object (after clicking submit button)</p>
</body>
var FormData = $('form[name=myForm]').serializeArray();
FormData = JSON.stringify(FormData);
I don't like jQuery, but:
var $inputs = $('form[name="myForm"]').find('input');
var res = {};
Array.prototype.forEach.call($inputs, function($item, index) {
res[ $item.getAttribute('name') ] = $item.value;
});
var FormData = JSON.stringify(res);
alert(FormData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form enctype='application/json' method="POST" name="myForm">
<p><label>Company:</label>
<input name='Company' value='TESTCOMPANY'> </p>
<p><label>User Id:</label>
<input name='User' value='TESTUSER'></p>
<p><label>Division:</label>
<input type="text" name='parameterMap[p1]' value='12345' ></p>
<p><label>From:</label>
<input type="text" name='parameterMap[p2]' value='20-MAR-2016'></p>
<p><label>To:</label>
<input type="text" name='parameterMap[p3]' value='22-MAR-2016'></p>
<input value="Submit" type="submit" onclick="submitform()">
</form>
</body>
I need to pass values of selected check boxes to the javascript method but it does not detect the checkbox.
<form name="cat" method="POST" action="myaction">
<c:forEach items="${items}" var="item">
<input type="checkbox" id="pro" name="pro" value="${item.id}"/>
</c:forEach>
...
<input type="button" value="getItem" onclick="getItem(this.form)"/>
</form>
Javascript
function getItem(frm) {
alert("size:" + frm.pro.length); <<< it returns size:unidentified
var values = "";
for (var i = 0; i < frm.pro.length; i++)
{
if (frm.pro[i].checked)
{
values = frm.pro[i].value + ",";
}
}
alert(values); << it is empty
....
//pass values to the back-end
I think your approach is old fashioned. Here's a jQuery version.
NOTE: you are adding multiple id="pro" and this is just wrong remove it
First add id="form" to your form
Here you can find a fiddle. :D
http://jsfiddle.net/SXffG/3/
HTML:
<form id="form" name="cat" method="POST" action="myaction">
<input type="checkbox" name="pro" value="1"/>
<input type="checkbox" name="pro" value="2"/>
<input type="checkbox" name="pro" value="3"/>
<input type="checkbox" name="pro" value="4"/>
<input type="checkbox" name="pro" value="5"/>
<input type="checkbox" name="pro" value="6"/>
<input type="button" class="getItem" value="getItem"/>
</form>
<div id="info">Click the button</div>
JavaScript
var allVals = [];
$(function() {
$('#form .getItem').click(function() {
allVals = []
$('#form :checked').each(function() {
allVals.push($(this).val());
});
//alert("Values " + allVals);
$.ajax({
type: "POST",
url: "http://localhost:8080/example/ajaxSubmit.action",
data: "allVals=" + allVals,
success: function(response){
$('#info').html("OK! Data [" + allVals + "] Sent with Response:" + response);
},
error: function(e){
$('#info').html("OH NOES! Data[" + allVals +"] Not sent with Error:" + e);
}
});
});
});
var check = document.getElementsByName("pro");
var textArray = [];
for(var c = 0; c < check.length;c++){
if(check[c].checked){
textArray .push(check[c].value);
}
}
textArray = textArray .join("~");
you will get the data as tilde separated. Hope this helps you.