I have some data that is being fed into my form via php. I am then adding additional information to that and it is being sent out. There is no telling how many rows will be in my table, and Values 1-3 is the additional information that I am adding to EACH row.
How I send the info:
if(isset($_POST['val1']))
{
echo "Submitting\n";
print_r($_POST);
$variable = "val1=" . $_POST['val1'] . ",val2=" . $_POST['val2'] . ",val3=" . $_POST['val3'];
// set post fields
$post = [
'submit' => 'true',
'activity_name' => 'DataSend',
'params' => [
'Data' => $variable
]
];
How I think I need to get it to go out as a string to the application (I realize there is a bunch of options here, I'm not sure how to get it to work) I need this to go out as a string, right now it is being received as an Array:
<script type="text/javascript">
function sendData() {
var inputs = document.getElementById(‘TableName’).getElementsByTagName('input'),
data = [],
name, val1[], val2[], val3[];
for (var i = 0; i < inputs.length; i++) {
if ( inputs[i].type === 'submit') {
continue;
}
var variable = ''; for (var i = 0, len = input.length; i<len,i++) { variable += 'val1' + i + '=' + val1[i] + ',val2' + i + '=' + val2[i] + ',val3' + i + '=' + val3[i] + ','; }
var array_objects = [
{'name': 'val1';},
{'name': 'val2';},
{'name': 'val3';},
]
var array_to_join = [];
for (x = 0; x < array_objects.length;
x++) {
_.map(array_objects[x], function(key, value) {
array_to_join.push(key + '=' + value);
});
}
document.body.innerHTML =
array_to_join.join(', ');
}
}
}
</script>
Related
The object array is built here in the first script..."order_items". I want to pass it into the second script so I can loop through values and build a pixel to render to my screen. I'm stuck trying to pass the array.
#for (int i = 0; i < OrderItemsReceived.Count; i++)
{
<script type="text/javascript" id="pepper" data-search="order_items">
var order_items = [{
'name':ProductName',
'sku': SKU',
'price': UnitPrice.ToString().Replace(",", "")',
'quantity': Quantity.ToString()'
}]
</script>
}
<script type="text/javascript">
var script_tag = document.getElementById('pepper');
var order_items = script_tag.getAttribute("data-search");
var order_id = #Model.OrderId;
var pixel_html = '';
var integration = 'DYNAMIC';
var program_id = 7302;
if (order_id && order_items) {
jQuery.each( order_items, function (i, order_item) {
pixel_html += '&' + 'ITEM_ID' + i + '=' + order_item.sku +
'&' + 'ITEM_PRICE' + i + '=' + order_item.price +
'&' + 'QUANTITY' + i + '=' + order_item.quantity;
});
if (pixel_html) {
pixel_html = '<iframe src="https://t.pikespeak.com/track?' +
'INT=' + integration +
'&' + 'PROGRAM_ID' + '=' + program_id +
'&' + 'ORDER_ID' + '=' + order_id +
pixel_html +
'" width="1" height="1" frameborder="0"></iframe>';
}
}
$('body').append(pixel_html);
</script>
this is how I solved the problem.
<script type="text/javascript" id="pepper" data-search="order_items">
alert("hello");
var order_items = #Html.Raw(Json.Encode(Model.OrderItemsReceived.OrderItemsReceived));
var order = [];
var order_listItems = [];
for (var i = 0; i < order_items.length; i++){
var orderList = order_items[i];
order = [{
'sku': orderList.SKU,
'price': orderList.UnitPrice,
'quantity': orderList.Quantity
}]
order_listItems.push(order);
}
I chose to go ahead with a json object because my array would be constructed of key, value pairs. Once I realized this, the scope of the variable was no longer the issue.
I submit some data via jQuery .ajax() and receive some data back via response. I need to output the data on my page. For example this is one of the responses I get:
{
"res": 1,
"item": [
{"id":"1","desc":"blue box","rating":"1"},
{"id":"2","desc":"red ball","rating":"5"}
]
}
I output this response via a loop like this:
...
success: function (response) {
for (var i = 0; i < response.item.length; i++){
var item = response.item[i].id,
desc = response.item[i].desc,
rate = response.item[i].rating;
$('#em' + response.res).append(item+'. '+ desc + ' Rating:' + rate);
}
}
Unfortunately what I get is two rows of the same item. What am I missing?
For starters, your not closing your for loop.
success: function (response) {
for (var i = 0; i < response.item.length; i++){
var item = response.item[i].id,
desc = response.item[i].desc,
rate = response.item[i].rating;
$('#em' + response.res).append(item + '. ' + desc + ' Rating:' + rate);
}
}
I have a working recursive function that creates an <ul> list from an object, it works fine,
my problem is that I want to keep track of the index, and add it as class to <li> elements,
I need that the "index count system" will count in a particular way, and this is the output that I want:
class0
class0_0
class0_0_0
class0_0_1
class0_1
class0_1_0
class0_1_1
class1
class1_0
class1_0_0
class1_0_1
class1_1
class1_1_0
class1_1_1
by increasing, restarting and have maybe multiple "index count" variables in the recirsive function
This is what I'm trying, but I still can't figure out where to properly set, increase, reset the counters to achieve that result..
var i = 0;
function object2ul(data) {
var json = "<ul>";
for(var key in data) {
json = json + "<li>" +'<b>'+i+'</b>'+ key; i++;
if(typeof data[key] == 'object') {
json = json + object2ul(data[key]);
}else{ i=0;
json = json + '<ul><li>'+ data[key]+'</li></ul>';
}
json = json + "</li>";
}
return json + "</ul>";
}
document.body.innerHTML = object2ul(object);
In this example I omitted to set the classes avoiding to complicate the function
DEMO
Something like this?
var object = {
root0: {
child0: {
leaf: 'text',
leaf: 'text'
},
child1: {
leaf: 'text',
leaf: 'text'
}
},
root1: {
child0:{
leaf: 'text',
leaf: 'text'
},
child1: {
leaf: 'text',
leaf: 'text'
}
}
};
var i = 0;
function object2ul(data, prefix) {
prefix = prefix || '0'; // default
var json = "<ul>";
var childIndex = 0;
for(var key in data) {
json = json + "<li>" +'<b>'+i+'</b>'+ key; i++;
if(typeof data[key] == 'object') {
json = json + object2ul(data[key], prefix + '_' + childIndex);
}else{ i=0;
json = json + '<ul><li>'+ data[key]+'---(' + prefix + ')</li></ul>';
}
json = json + "</li>";
childIndex++;
}
return json + "</ul>";
}
document.body.innerHTML = object2ul(object);
To get the kind of indexing you want, you are going to have to use Object.keys. The following should work for an arbitrary object:
var testObj = { a: { b: '2', d: '5', e: { f: '3' } }, c: '3' };
var indexes = [];
var object2ul = function (data) {
var keys = Object.keys(data);
var json = "<ul>";
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
indexes.push(i);
json += "<li>" + "<b>" + indexes.join('_') + "</b>" + key;
if (typeof(data[key]) === 'object') {
json += object2ul(data[key]);
} else {
json += "<ul><li>" + data[key] + "</li></ul>";
}
json += "</li>";
indexes.pop();
}
return json + "</ul>";
}
document.body.innerHTML = object2ul(testObj);
Here's it in action:
JSFiddle
Here's a simple loop I'm running:
for (var key in TestApp.config.services) {
if (TestApp.config.services[key].files != "") {
var files = TestApp.config.services[key].files.split(',');
for (var i = 0; i <= files.length - 1; i++) {
var file_url = files[i];
console.log("About to download :" + file_url);
$.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent(file_url) + '&callback=?', function(data) {
console.log("Downloaded file: " + file_url);
console.log(key);
});
}
}
}
The problem is that the key value is always the same by the time the JSON request finishes. How can I avoid this race condition so that the right key value is used when the $.getJSON is finished?
you need an Immediately-invoked function expression (IIFE):
for (var key in TestApp.config.services) {
if (TestApp.config.services[key].files != "") {
var files = TestApp.config.services[key].files.split(',');
for (var i = 0; i <= files.length - 1; i++) {
var file_url = files[i];
console.log("About to download :" + file_url);
// IIFE
(function(thiskey,this_file_url){
$.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent(this_file_url) + '&callback=?', function(data) {
console.log("Downloaded file: " + this_file_url);
console.log(thiskey);
});
})(key,file_url);
}
}
}
One simple solution is to simply send the key with the request. I prefer to write it in {} notation.
Let me give you the basis to an answer to your question; I will disregard the part with the files, to emphasize where to look at.
index.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var items = ['Hello', 'World', 'foo', 'bar'];
for (var i=0; i < items.length; i++) {
console.log("About to download :" + items[i] + '" - key: ' + i);
$.getJSON( "ajax.php",
{
url: items[i],
key: i
},
function(data) {
var key = data.key;
console.log("Downloaded file: " + data.url + '" - key: ' + key);
}
);
}
</script>
ajax.php
<?php
echo json_encode(array('url'=>$_GET['url'], 'key'=>$_GET['key']));
?>
I have the following (example) array of objects:
var theArray = [
{theId:'1', num: 34},
{theId:'2', num: 23},
{theId:'5', num: 26}
];
and this function, which works fine to loop through them:
function printValues() {
var i = 0;
for(i; i<theArray.length; i++) {
var obj = theArray[i];
document.getElementById('result1').innerHTML += obj.theId + ' = ' + obj.num + '<br>';
}
}
However, if I want to abstract this function for use on similar arrays by using function variables to access objects within them, like this:
function printValuesVar(arr,elemId,arrId,arrNum) {
var i = 0;
for(i; i<arr.length; i++) {
var obj = arr[i];
document.getElementById(elemId).innerHTML += obj.arrId + ' = ' + obj.arrNum + '<br>';
}
}
'undefined' is the result when called as below (as I'd kind of expect since 'arrId' is not an object name):
printValuesVar(theArray,'result2','theId','num');
How can I use the values passed to the function's variables to access values of objects within the array by name?
rewritten following advice against antipatterns:
function printValuesVar(arr,elemId,arrId,arrNum) {
var i = 0;
var content = '';
for(i; i<arr.length; i+=1) {
var obj = arr[i];
content += obj[arrId] + ' = ' + obj[arrNum] + '<br>';
}
document.getElementById(elemId).innerHTML = content;
}
Try this:
function printValuesVar( arr, elemId, arrId, arrNum ) {
var content = '';
arr.forEach( function ( arrElem ) {
content += arrElem[ arrId ] + ' = ' + arrElem[ arrNum ] + '<br>';
});
document.getElementById( elemId ).innerHTML = content;
}
Or a bit more advanced:
function printValuesVar( arr, elemId, arrId, arrNum ) {
document.getElementById( elemId ).innerHTML = arr.map( function ( arrElem ) {
return arrElem[ arrId ] + ' = ' + arrElem[ arrNum ];
}).join( '<br>' );
}
ES5-shim for shitty browsers
Because you are loking for key "arrId", not the key stored in variable arrId
document.getElementById(elemId).innerHTML += obj[arrId] + ' = ' + obj[arrNum] + '<br>';