Passing checkbox values as JSON in Jquery - javascript

I have an input form which has three text fields and a checkbox input section where the user can select more than one value. I also have an ajax request which sends a POST request to an api. I have written a function to iterate over the form inputs and parse them to JSON, however, it has come to my attention that this wont work for checkbox values. Here is my function:
<script>
console.log(document);
var form = document.getElementById("myform");
form.onsubmit = function (e) {
// stop the regular form submission
e.preventDefault();
// collect the form data while iterating over the inputs
var info = {};
for (var i = 0, ii = form.length; i < ii; ++i) {
var input = form[i];
if (input.name) {
info[input.name] = input.value;
}
addPerson(info);
}
}
function addPerson(info) {
$.ajax({
type: "POST",
url: "http://example.com",
data: JSON.stringify(info),
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "json",
success: function (data, status, jqXHR) {
alert("success");
},
error: function (jqXHR, status) {
// error handler
console.log(jqXHR);
}
});
}
</script>
I've been trying to get the checkbox values into JSON using
$.each($('input[id="data[i].id"]:checked'), function() {
var value = $(this).val();
qualifications.push(value);
});
but I cant figure out how to add these values to the JSON that is being posted to the server, can anyone help?

Have tried .serialize() and I THINK it is working-
<script>
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
$('myform').submit(function() {
$('#result').text(JSON.stringify($('myform').serializeObject()));
return false;
});
});
function addPerson(result){
$.ajax({
type: "POST",
url: "http://example.com",
data: JSON.stringify(result),
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "json",
success: function (data, status, jqXHR) {
alert("success");
},
error: function (jqXHR, status) {
// error handler
console.log(jqXHR);
}
});
}
</script>
If anyone has thoughts/ comments as to how effective the above is, or if there is a better way of doing it, I would like to hear them?

Try this:
var input = form[i];
if (input.name) {
if(input.tagName.toLowerCase() === 'input' &&
(input.type.toLowerCase() === 'checkbox' || input.type.toLowerCase() === 'radio') &&
input.checked)
info[input.name] = input.value;
else
info[input.name] = input.value;
}
addPerson(info);
EDIT:
I suggest using jQuery form.serialize() method as #Drixson OseƱa mentioned.

Related

Show modal form before ajax cal and get data from it

I have an ajax function something like this:
function foo(e, e1, curc)
{
var sender = (e && e.target) || (window.event && window.event.srcElement);
$.ajax({
type: 'POST',
url: 'script.php',
dataType: 'json',
data: "id="+e+"&mod="+e1+"&curc="+curc,
beforeSend: function() {
$('#mform').show();
},
complete: function() {
$('#fountainG').hide();
},
success: function(data) {
document.getElementById("itog").innerHTML = data.d+data.a;
},
error: function(xhr) {
document.getElementById("itog").innerHTML = '123';
}
});
}
I need to show some modal form to user, and get the data from it in ajax script. I tried to add show function to ajax beforeSend - but I do not understand how to wait for user form submit, and get data from modal form. Ajax function call in html: href="javascript:void(0)" onclick="javascript:foo(3800064420557,1,138)
You just need to re-arrange your logic. Instead of trying to show the modal "within" the ajax request, hold off on sending the ajax request until you have gotten the necessary data from the modal. Here is a rough outline, presuming that your modal element $('#mform') has a form in it with an id of myform which is the form you want to get data out of.
function foo(e, e1, curc)
{
var sender = (e && e.target) || (window.event && window.event.srcElement);
var modal = $('#mform');
var form = $('#myform', modal);
form.on( 'submit', function(){
$('mform').hide();
// make your ajax call here the same way, and inside the
// onsuccess for this ajax call you will then have access to both
// the results of your ajax call and the results of the form
// data from your modal.
$.ajax({ ... });
});
}
To get form data, you can try with below code
function foo(e, e1, curc)
{
var sender = (e && e.target) || (window.event && window.event.srcElement);
form_values = {}
$('mform').show();
$('#myForm').submit(function() {
var $inputs = $('#myForm :input');
$inputs.each(function() {
form_values[this.name] = $(this).val();
});
console.log("form data:", form_values)
// with form_values continue with your coding
$.ajax({
type: 'POST',
url: 'script.php',
dataType: 'json',
data: "id="+e+"&mod="+e1+"&curc="+curc,
success: function(data) {
$('mform').show();
document.getElementById("itog").innerHTML = data.d+data.a;
},
error: function(xhr) {
document.getElementById("itog").innerHTML = '123';
}
});
});
}
Hope it will help you :)

check Multiple Word in Input Field textbox using javascript

I am having textbox Input field and in that i have to check Multiple words. I am able to check single Word but not able to check multiple words. A list of word is stored in xml and from that i have to check. Need Help.
Here MyName is Input Field Id and lblMyName is Label Id.
if ($("#MyName").val() != '') {
$.ajax({
type: "GET",
url: "Xml/Badwords.xml",
dataType: "xml",
success: function (xml) {
$(xml).find('Badwords').each(function () {
var flag = true;
$(this).children().each(function () {
var tagName = this.tagName;
var val = $(this).text();
if (val.toLowerCase() == $("#MyName").val().toLowerCase()) {
$("#lblMyName").css("display", "block");
$("#lblMyName").text("Please refrain from using profanity.");
$(".postermyname").text('My Name);
flag = false;
return false;
}
You'll have to split the input value on word boundaries and then compare that against the "bad" words.
Note that profanity filters is in generally a really bad idea, and will usually cause more issues than they solve
if ( $("#MyName").val().trim() != '' ) {
$.ajax({
type: "GET",
url: "Xml/Badwords.xml",
dataType: "xml",
success: function(xml) {
var input = $("#MyName").val().toLowerCase().split(/\b/),
flag = true;
$(xml).find('Badwords').each(function() {
$(this).children().each(function() {
var val = $(this).text().toLowerCase;
if (input.indexOf(val) !== -1) {
$("#lblMyName").css("display", "block")
.text("Please refrain from using profanity.");
flag = false;
}
});
});
});
});
}

Wordpress: Jquery submit event, page reloading instead of firing a document.location.href

So, I have a jQuery submit event handler, that on submit queries a database, and if no records are returned, prevents the form page from reloading, and if records were found, should then redirect the user to another page using document.location.href.
But what is actually happening is that records are being found, and instead of then redirecting the user to another page, the form page itself reloads.
What am I overlooking here?
jQuery('#MyForm').submit(function(e) {
console.log("getUserIDs is successfully hit.");
alert("The submit event has been hit");
var countryVal;
var cityVal;
var townVal;
var categoriesVal;
var serialized = jQuery('#MyForm').serialize();
var url = window.location.hostname;
countryVal = jQuery("#CountryList").val();
cityVal = jQuery("#CityList").val();
townVal = jQuery("#TownList").val();
if (typeof townVal == 'object') {
townVal = "object";
}
categoriesVal = jQuery("#CategoriesList").val();
jQuery.ajax({
cache: false,
type: "POST",
async: false,
url: gymRegions.ajaxurl,
data: {
action: "showcountries",
makeselection: "getUserIDs",
countryID: countryVal,
cityID: cityVal,
townID: townVal,
categoriesID: categoriesVal,
locationHref: url,
serialized
},
dataType: "json",
success: function(data) {
alert("Success of the submit event has been hit.");
localStorage.setItem('dataObjectTemp2', JSON.stringify(data));
var numericRecCount = parseInt(data.c);
jQuery.post('', function(data) {
document.location.href = window.location.hostname + '/index.php/anotherpage/';
});
},
error: function(data, status, error) {
alert("No records were returned for your search. Please make another selection.");
e.preventDefault();
return false;
console.log(data);
console.log(status);
console.log(error);
}
});
});
<form id="MyForm" method="Post">
<input type="submit" name="fl-button" id="fl-button" role="button" value="SEARCH" class="fl-button" disabled="disabled" value="Send" />
</form>
jQuery('#MyForm').submit(function (e) {
e.preventDefault();
var countryVal;
var cityVal;
var townVal;
var categoriesVal;
var serialized = jQuery('#MyForm').serialize();
var url = window.location.hostname;
countryVal = jQuery("#CountryList").val();
cityVal = jQuery("#CityList").val();
townVal = jQuery("#TownList").val();
if (typeof townVal == 'object') {
townVal = "object";
}
categoriesVal = jQuery("#CategoriesList").val();
jQuery.ajax({
cache: false,
type: "POST",
async: false,
url: gymRegions.ajaxurl,
data: serialized + '&action=showcountries&makeselection=getUserIDs&countryID=' +
countryVal + '&cityID=' + cityVal + '&townID=' + townVal + '&categoriesID=' +
categoriesVal + '&locationHref=' + url,
dataType: "json",
success: function (data) {
alert("Success!");
localStorage.setItem('dataObjectTemp2', JSON.stringify(data));
var numericRecCount = parseInt(data.c);
window.location.href = url + '/index.php/anotherpage/';
},
error: function (data, status, error) {
alert("No records were returned for your search. Please make another selection.");
}
});
return false;
});
jQuery('#MyForm').submit(function (e) {
e.preventDefault(); //use prevent default here
console.log("getUserIDs is successfully hit.");
alert("The submit event has been hit");
var countryVal;
var cityVal;
var townVal;
var categoriesVal;
var serialized = jQuery('#MyForm').serialize();
var url = window.location.hostname;
countryVal = jQuery("#CountryList").val();
cityVal = jQuery("#CityList").val();
townVal = jQuery("#TownList").val();
if (typeof townVal == 'object'){
townVal = "object";
}
categoriesVal = jQuery("#CategoriesList").val();
jQuery.ajax({
cache: false,
type: "POST",
async: false,
url: gymRegions.ajaxurl,
data:{action: "showcountries",
makeselection: "getUserIDs",
countryID: countryVal,
cityID: cityVal,
townID: townVal,
categoriesID: categoriesVal,
locationHref: url,
serialized},
dataType: "json",
success: function (data) {
alert("Success of the submit event has been hit.");
localStorage.setItem('dataObjectTemp2', JSON.stringify(data));
var numericRecCount = parseInt(data.c);
document.location.href = window.location.hostname + '/index.php/anotherpage/';
},
error: function (data, status, error) {
alert("No records were returned for your search. Please make another selection.");
console.log(data);
console.log(status);
console.log(error);
}
});
});

Why trigger and click do not work in this case?

I have a piece of code that does:
$('td.unique').live('click', function () {
//function logic here
});
This works fine on I click on the td of my table. All fine!
Now I would like to be able to have the same functionality programatically in certain cases without the user actually pressing click.
I have tried:
$(document).ready(function() {
$(".clearButton").click( function () {
var username = $(this).closest('tr').find('input[type="hidden"][name="uname"]').val();
var user_id = $(this).closest('tr').find('label').val();
var input = [];
input[0] = {action:'reset', id:user_id,user:username,};
$.ajax({
url: 'updateprofile.html',
data:{'user_options':JSON.stringify(input)},
type: 'POST',
dataType: 'json',
success: function (res) {
if (res.status >= 1) {
//all ok
console.log("ALL OK");
$(this).closest('tr').find('.unique').trigger('click');
$(this).closest('tr').find('td.unique').trigger('click');
$(this).closest('tr').find('td.unique').click();
}
else {
alert('failed');
}
}
});
This button is in the same row that the td.unique is
None of these work. Why? Am I doing it wrong? Is the function that I have bind in live not taken into account when I click this way?
You need to cache the $(this) inside the ajax function.
var $this = $(this);
the $(this) inside the ajax function will not refer to the element that is clicked
$(".clearButton").click(function () {
var $this = $(this);
var username = $this.closest('tr').find('input[type="hidden"][name="uname"]').val();
var user_id = $this.closest('tr').find('label').val();
var input = [];
input[0] = {
action: 'reset',
id: user_id,
user: username,
};
$.ajax({
url: 'updateprofile.html',
data: {
'user_options': JSON.stringify(input)
},
type: 'POST',
dataType: 'json',
success: function (res) {
if (res.status >= 1) {
console.log("ALL OK");
$this.closest('tr').find('.unique').trigger('click');
$this.closest('tr').find('td.unique').trigger('click');
$this.closest('tr').find('td.unique').click();
} else {
alert('failed');
}
}
});
});

how to submit form as JSON object

what I am doing is creating a form using JSON this form can then be edited a and produce new JSON object. The problem I am having seems to be with getting the form id.
The code I am using to return a JSON object is:
form = document.forms[0];
$.fn.serializeObject = function()
{
alert("start serializeObject");
var o = {};
var a = this.seralizeArray();
$.each(a, function(){
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
alert(o);
};
$(function() {
alert("here");
form.submit(function(){
result.append(JSON.stringify(form.serializeObject()));
return false;
});
});
This just refresh's the pageI am not sure why.
This program is not on a server and not be used on a server.
by this I mean It is only every going to be run locally on a local machine, with no apache2 setup.
Thanks.
You code can be written pretty easy. This is how I do it:
Ajax:
$('#formID').on('submit',function () {
$.ajax({
url: 'submit.php',
cache: false,
type: 'POST',
data : $('#formID').serialize(),
success: function(json) {
alert('all done');
}
});
});
If you are not sending it with Ajax, why would you do this? If you are simply submitting the form, you can do it using PHP like this:
<?php
$json_object = json_decode($_POST);
?>
$('#formID').on('submit',function (e) {
e.preventDefault();
$.ajax({
url: 'submit.php',
cache: false,
type: 'POST',
data : $('#formID').serialize(),
success: function(json) {
alert('all done');
}
});
});
if you want not redirect or refresh use e.preventDefault();

Categories

Resources