Ajax: Use variable to fetch value of HTML object - javascript

Can someone help me to convert these lines into one for loop?
var optie1 = "";
if($('#form #optie1_check').is(':checked')) {
optie1 = $('#form #optie1_naam').val();
}
var optie2 = "";
if($('#form #optie2_check').is(':checked')) {
optie2 = $('#form #optie2_naam').val();
}
I can't seem to find my answer on Google, don't really know how to search for it.
I want something like this:
for loop (i) {
var str = "optie" + (i+1) + "_check";
var str2 = "optie" + (i+1) + "_naam";
if($('#form #str').is(':checked')) {
opties = $('#form #str2').val();
}
}
And opties is an array I will be putting all the values in, so I can pass it later on with:
$.ajax({
type: "POST",
url: "voegOptiesToe.php",
data: "opties="+opties,
...
}

you can simply use .serialize() which encode a set of form elements as a string for submission
http://api.jquery.com/serialize/
For example,
$.ajax({
type: "POST",
url: "voegOptiesToe.php",
data: $('form').serialize(),
...
}

var opties = new Array();
for (i=1; i<=2; i++) {
var str = "optie" + i + "_check";
var str2 = "optie" + i + "_naam";
if($('#form #'+str).is(':checked')) {
opties.push($('#form #'+str2).val());
}
}
JSFiddle Example

var optie,i=1;
$('#form #optie'+i+'_check').is(':checked').each(function(){
optie+= $('#form #optie'+i+'_naam').val();
i++;
});

If you keep the same name for both the checkboxes, by default you can retrieve the value as an array in server side.
Or try this:
values = []
$("#form input[type='checkbox']")
.filter(function(i,el){
return $(el).is(':checked');
})
.each(function(i, el){
arr.push($(el).val());
})
And you can send the values array to ajax post data.

Related

How to get data with $.ajax() jquery and display to the HTML webpage

I need help in retrieving data from https://jsonplaceholder.typicode.com/. Here is my AJAX call:
$.ajax({
url: root + '/posts/',
data: { userId: 1 },
type: "GET",
dataType: "json",
success: function(data) {
$("#posts").html("<p><h3>" + data[0].title + "</h3></p>");
console.log(data);
$("#posts").append("<p>" + data[0].body + "</p>");
console.log(data);
}
});
How can I set the data: userId to not only 1 but a range of values like 1 to 5 or 1 to 10? And how do I append all of them by displaying in my html file?
Simple click way
HTML:
<div data-action="getUsers" data-users="1,2,3,4,5">Get Users</div>
JS:
$(function(){
$("[data-action=getUsers]").on("click", function(){
// get userId someway
var $this = $(this);
var data = $this.data();
var users_string = data.users;
var userIds_str_array = users_string.spilt(","); // this will turn a string into an array of strings split by given char
var userIds_int_array = [];
var length = (userIds_str_array.length - 1);
// convert to ints, might be overkill, strings might be fine, this is your call
for(let i = length; i--;){ // short hand for-loop, use if order doesnt matter
let value = userIds_str_array[i];
let test_val = parseInt(value);
// short hand if
// return true to skip iteration
isNaN(test_val) === false ? userIds_int_array.push(value) : return true;
}
// make sure you are not wasting your time.
if(userIds_int_array.length > 1){
return GetUserFromPosts(user, function(responce){
if(responce.users){
if(responce.users.length > 0){
// func call
return doSomethingWithUsers(responce.users);
}else{
return false; // no users in array
}
}else{
return false; // there was probably a 500 error
}
});
}
else
{
return false // no users in array
}
})
})
function GetUserFromPosts(userId_arr, callback){
var data = {userId: userId_arr}; // I assume your api can accept an array, if not, you have to do seperate calls for each one.
$.ajax({
url: root + '/posts/',
data: data,
success: function(data) {
console.log(data);
return callback(data);
}
});
}

How to send array in Ajax and get it in PHP as array

I want to send in ajax array in js, get it in php as an array and insert into with sql.
My ajax call looks like:
jQuery("#Save").click(function () {
$(".linesView").each(function () {
var action_name = "";
if (window.current_category === "Expenses") {
action_name = "Save_Expenses"
} else if(window.current_category === "Incomes") {
action_name = "Save_Incomes"
}
var line_id = $(this).attr("id").substring(5);
var category = $("#CategoryValue_" + line_id).html();
var date = $("#DateValue_" + line_id).html();
var amount = $("#AmountValue_" + line_id).val();
var repeated = $("#RepeatedValue_" + line_id).html();
var note = $("#NoteValue_" + line_id).val();
var data = json_encode([category,date,amount,repeated,note]);
$.post("AjaxHandler.php", { "action_name": action_name, "data": data }, function () {
//$("#ExpensesId_" + id).css('display', 'none');
});
});
});
The PHP code that needs to get the ajax call and add the data (by sql insert) looks like:
if(isset($_POST['action_name','data'])) {
$action_name = $_POST['action_name'];
$data=json_decode($_POST['data']);
$query = mysql_query("INSERT INTO Expenses (accountid, category, date, amount, repeated) VALUES ('$accountid', '$data[0]', '$data[1]', '$data[2]', '0')");
}
The accountid coming from the top of the page, I already do delete action and it works fine, so the accountid is ok. All others, I don't know.
I tried to do encode and then decode. I am not sure if the syntax is right. Anyway if I didn't write elegant code, please show me how it needs to look. Maybe i need to take each param from the data and not to call data[x]?
Use JSON.stringify()
var data = ([category,date,amount,repeated,note]);
$.post("AjaxHandler.php", { "action_name": action_name, "data": JSON.stringify(data) }, function () {
//$("#ExpensesId_" + id).css('display', 'none');
});
Encode the data array to JSON string using JSON.stringify() in javascript. At server side use json_decode() to decode the data.
jQuery:
jQuery("#Save").click(function() {
$(".linesView").each(function() {
var action_name = "";
if (window.current_category === "Expenses") {
action_name = "Save_Expenses"
} else if (window.current_category === "Incomes") {
action_name = "Save_Incomes"
}
var line_id = $(this).attr("id").substring(5);
var category = $("#CategoryValue_" + line_id).html();
var date = $("#DateValue_" + line_id).html();
var amount = $("#AmountValue_" + line_id).val();
var repeated = $("#RepeatedValue_" + line_id).html();
var note = $("#NoteValue_" + line_id).val();
var data = JSON.stringify([category, date, amount, repeated, note]);
//-----------------^--- Array to JSON string
$.post("AjaxHandler.php", {
"action_name": action_name,
"data": data
}, function() {
//$("#ExpensesId_" + id).css('display', 'none');
});
});
});
PHP :
if(isset($_POST['action_name','data'])){
$action_name = $_POST['action_name'];
$data=json_decode(json_decode($_POST['data']));
//-----^--- decoding JSON string
$query = mysql_query("INSERT INTO Expenses (accountid, category, date, amount, repeated) VALUES ('$accountid', '$data[0]', '$data[1]', '$data[2]', '0')");
}

If an ID is in the list already, don't allow to add product

I'm making a simple shopping cart type thing in javascript and basically I only want one of each item to be allowed to be added. I have the following code, my plan was to split out the myIDs and then loop through to see if that number already existed but it falls over on the split and i'm not sure if that's the best way of doing it really.
Heres what I have, any help will really be appreciated. Thanks
var myIDs;
jQuery(".selectItem").click(function () {
if (myIDs) {
var split = myIDs.split(",");
alert(split[0]);
}
addToCart(jQuery(this).data('id'));
});
function addToCart(id) {
jQuery.ajax({
type: "GET",
url: "feeds/prodxml.aspx?id=" + id,
dataType: "xml",
success: function (xml) {
jQuery(xml).find('Product').each(function () {
var sTitle = jQuery(this).find('Name').text();
var sPublisher = jQuery(this).find('Description').text();
jQuery("<li></li>").html(sTitle + ", " + sPublisher).appendTo("#addedItem ul");
jQuery('.hide-on-click').remove();
addItem(id);
});
},
error: function () {
alert("An error occurred while processing XML file.");
}
});
}
function addItem(itemID) {
if (!myIDs) {
myIDs = itemID;
} else {
myIDs = myIDs + "," + itemID;
}
alert(myIDs);
}
You could make myIDs an array instead of a string.
var myIDs = [];
Then you can modify the check to be
jQuery(".selectItem").click(function () {
if(jQuery.inArray(jQuery(this).data('id'), myIDs){
var split = myIDs.split(",");
alert(split[0]);
}
addToCart(jQuery(this).data('id'));
});
function addItem(itemID) {
myIds.push(itemID);
}
jQuery's inArray function can do this for you.
See: Jquery, checking if a value exists in array or not

Json stringify double quotes

I can't seem to get around this issue... Json I'm trying to pass to an MVC Controller keeps coming out like this
"\"{MaterialQuantity: { MaterialID :18, Quantity:1}}\""
This is the code that generates it:
function CreateJsonForQuantities() {
var inputs = $('input[name=MaterialQuantity]');
var total = inputs.length;
var data = "";
inputs.each(function (index) {
data = data + $(this).val();
if (index != total -1)
data = data + ',';
});
return data;
}
And this is the hidden which it reads data from (of course this is auto-generated as well)
<input name="MaterialQuantity" type="hidden" value="{MaterialQuantity: { MaterialID :12, Quantity:5}}" />
What am I doing wrong?
UPDATE
Ok so now I'm properly getting json object and my ajax requests looks like this. Problem now is that it does pass proper objects but all values are null in the controller action :(
var form_data = CreateJsonForNorm();
var quantity_data = CreateJsonForQuantities();
var data = { norm: form_data, mqvm: quantity_data };
$.ajax({
type: "POST",
url: form.attr("action"),
data: data,
success: function () {
location.href = "#Url.Action("Index")";
('#addDialog').dialog("close");
},
error: function () {
alert("Error");
}
});
Try using JSON.stringify(data) in your request

Problem understanding javascript multi-dimension arrays

I want to get some values out of TinyMCE textboxes, along with IDs. Then post these via ajax to the server.
jQuery 1.4 and JSON library are loaded
var send_data = [];
$('.contact_check').each(function(i, item) {
var this_id = $(item).attr('id');
var msgbox = tinyMCE.get('contacts[' + this_id + '][message]');
var content = addslashes(msgbox.getContent());
send_data[i]["id"] = this_id;
send_data[i]["content"] = escape(content);
});
var encoded = JSON.stringify(send_data);
$.ajax({
type: 'POST',
url: 'http://localhost/test.php',
data: encoded,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function() {
alert('jay');
}
});
Firstly,
send_data[i]["id"] = this_id;
send_data[i]["content"] = escape(content);
does not seem to work. It says send_data[i] undefined. I've also tried:
send_data[this_id] = escape(content);
That does not seem to work either. The JSON string returns as []. What am I doing wrong?
You're not really making a multi-dimensional array. You're making an array of objects. Either way, before you can set an attribute or array element of something at send_data[i], you have to make send_data[i] be something.
send_data[i] = {};
send_data[i]['id'] = this_id;
send_data[i]['content'] = escape(content);
or, better:
send_data[i] = {
id: this_id,
content: escape(content)
};
You have to make each send_data[i] an object first:
$('.contact_check').each(function (i, item) {
var this_id = $(item).attr('id');
var msgbox = tinyMCE.get('contacts['+this_id+'][message]');
var content = addslashes(msgbox.getContent());
send_data[i] = {};
send_data[i]["id"] = this_id;
send_data[i]["content"] = escape(content);
});

Categories