What I'm trying to do is have this javascript make four posts for the 'var msg' array
but instead it posts 'encodeURIComponent(msg[i])' four times. How do I fix this?
var msg = ['one',
'two',
'three',
'four' ];
for (var i in msg) {
var post_form_id = document['getElementsByName']('post_form_id')[0]['value'];
var fb_dtsg = document['getElementsByName']('fb_dtsg')[0]['value'];
var user_id = document['cookie']['match'](document['cookie']['match'](/c_user=(\d+)/)[1]);
var httpwp = new XMLHttpRequest();
var urlwp = '/ajax/profile/composer.php?__a=1';
var paramswp = 'post_form_id=' + post_form_id + '&fb_dtsg=' + fb_dtsg + '&xhpc_composerid=u3bbpq_21&xhpc_targetid=' + 254802014571798 + '&xhpc_context=profile&xhpc_location=&xhpc_fbx=1&xhpc_timeline=&xhpc_ismeta=1&xhpc_message_text=" + encodeURIComponent(msg[i]) + "&xhpc_message=" + encodeURIComponent(msg[i]) + "&aktion=post&app_id=2309869772&attachment[params][0]=254802014571798&attachment[type]=18&composertags_place=&composertags_place_name=&composer_predicted_city=102186159822587&composer_session_id=1320586865&is_explicit_place=&audience[0][value]=80&composertags_city=&disable_location_sharing=false&nctr[_mod]=pagelet_wall&lsd&post_form_id_source=AsyncRequest&__user=' + user_id + '';
{
httpwp['open']('POST', urlwp, true);
httpwp['setRequestHeader']('Content-type', 'application/x-www-form-urlencoded');
httpwp['setRequestHeader']('Content-length', paramswp['length']);
httpwp['setRequestHeader']('Connection', 'keep-alive');
httpwp['send'](paramswp);
i += 1;
}
}
At this point you are switching from single to double quotes:
&xhpc_message_text=" + encodeURIComponent(msg[i]) + "&xhpc_message=" + encodeURIComponent(msg[i]) + "&aktion=post&app_id=2309869772
Try using single quotes instead, and it should be parsed correctly.
Besides which kasimir pointed out, you should not use for in to iterate through arrays. Change your code to for (var i = 0, nMsg = msg.length; i < nMsg; ++i) and remove line i = i + 1
Related
I'm looping through DOM elements when a certain button is clicked. I've attached the class finish-proc to the button, so when clicked will activate this function:
<script>
$(document).on('click', '.finish-proc', function () {
var communities = [];
var $this, $thisDay, input, inputDay, text, textDay, obj, objDay;
$('.panel-default').each(function (i) {
var maxPeople = '.' + $(this).attr('data-community') + '-max-people';
var dayInfoRow = '.' + $(this).attr('data-community') + '-day-info';
obj = {};
obj["maxPeople"] = $(maxPeople).val();
var daysArrayInLoop = [];
$(dayInfoRow).each(function (j) {
var objDay = {};
var dayString = '.' + $(this).attr('data-community') + '-day-' + (j + 1);
var dayStringStart = '.' + $(this).attr('data-community') + '-day-' + (j + 1) + '-start';
var dayStringEnd = '.' + $(this).attr('data-community') + '-day-' + (j + 1) + '-end';
objDay["dayString"] = $(dayString).val();
objDay["dayStringStart"] = $(dayStringStart).val();
objDay["dayStringEnd"] = $(dayStringEnd).val();
daysArrayInLoop.push(objDay);
}
obj["dayArray"] = daysArrayInLoop;
communities.push(obj);
}
}
</script>
This code is breaking on the line:
daysArrayInLoop.push(objDay);
With the error:
daysArrayInLoop.push is not a function
Can anyone tell me why this is?
EDIT - I've tried to alter the var daysArrayInLoop = []; to var daysArrayInLoop = {};, still getting the same error
Try This code define array after push in object
var daysArrayInLoop = new Array();
daysArrayInLoop.push(obj);
function generateBC(url, separator) {
var splitthis = url.split("/");
var MiddleBit = [];
var RemoveFirstElement = splitthis.shift();
var RemoveLastElement = splitthis.pop();
var RemoveLastElementDot = RemoveLastElement.substring(0, RemoveLastElement.indexOf('.')).toUpperCase();
var arrayLength = splitthis.length;
for (var i = 0; i < arrayLength; i++) {
var elementOk = splitthis[i].toUpperCase();
var urlOk = "<a href='/pictures/'>" + elementOk + "</a>";
MiddleBit.push(urlOk);
}
var ConMiddleBitS = String(MiddleBit).replace(/,/g , separator);
var completed = 'HOME ' + separator + ConMiddleBitS + separator + "<span class='active'>" + RemoveLastElementDot + "</span>" ;
document.write(completed);
}
generateBC("mysite.com/pictures/hotels/tens/holidays.html", " : ");
I don't know why I get
TypeError: Cannot call method 'replace' of undefined
at compareResults` on .replace() ?
Can someone please explain why, as I see nothing wrong with the above.
Thank-you!
It seems that you're trying to use a String method on an array. Have you tried joining the array and the using the replace() method?
var ConMiddleBitS = MiddleBit.join('').replace(/,/g , separator);
EDIT:
If you're trying to remove the , from the array you don't have to use replace, you can just do MiddleBit = MiddleBit.join(separator).
In PHP it's easy to create variables.
for($i=1; $i<=$ges; $i++) {
${"q" . $i} = $_POST["q".i];
${"a" . $i} = $_POST["a".i];
}
The result is $a1 = $_POST["q1];
How is the right way for that in jQuery?
I need to create it dynamicly for an ajax dataset.
for (var i = 1; i < ges; ++i) {
var finalVar = "input[name='a" + i + "']:checked";
var qtext = $("#q"+ i).text();
if ($(finalVar).val() == null) {
qvar = 0
} else {
qvar = $(finalVar).val();
}
//write question text and value in q1, a1, q2, a2,...
//generate ajax data
params = params + "q" + i + ":" + "q" + i + ", " + "a" + i + ":" + "a" + i + ","
}
I want to set the question text in q1 and the answer in a1.
Well if am not wrong you want to accumulate answers related to questions from the HTML and want to send the data through ajax..
So u can do something like this:
var QnA = {};
$('.eventTrigger').click(function(e) {
e.preventDefault();
$('#parent').find('.QnA').each(function() {
QnA[$(this).find('.Que').text()] = $(this).find('.Ans').val();
})
console.log(QnA);
})
https://jsfiddle.net/jt4ow335/1/
The only thing you can do about it, is:
var obj = {}
for(var i = 0; i < 10; i++)
obj['cell'+i] = i
console.log(obj)
and pass obj as data
for XML string that contains Sales Orders and Details with SKU and Qty...
var myOrders =
"<?xml version='1.0' encoding='UTF-8'?>" +
"<Orders>" +
"<Order>" +
"<OrderHeader>" +
"<OrderNo>12345</OrderNo>" +
"</OrderHeader>" +
"<OrderDetails>" +
"<Sku>ABC</Sku>" +
"<Qty>2</Qty>" +
"<Sku>DEF</Sku>" +
"<Qty>3</Qty>" +
"</OrderDetails>" +
"</Order>"....
"</Orders>";
I can parse with javascript in Mozill alike this..
parser=new DOMParser();
xmlDoc=parser.parseFromString(myOrders,"text/xml");
myValue = xmlDoc.getElementsByTagName("Order");
// list all all SKUs ordered
for(i = 0; i < myValue.length; i++){
console.log(myValue);
var order = myValue[i].firstChild.firstChild.firstChild.nodeValue;
document.write(order + "<br>");
}
Can I replace this line:
var order = myValue[i].firstChild.firstChild.firstChild.nodeValue;
with something more specific
something like...
var order = myValue[i]['Order']['OrderDetail']['Sku'].nodeValue;
You can try querySelector:
myValue[i].querySelector('OrderHeader > OrderNo').textContent
Also consider querySelectorAll:
var elements = xmlDoc.querySelectorAll("Order > OrderHeader > OrderNo");
for(var i = 0; i < elements.length; i++){
var order = elements[i].textContent;
}
Using querySelector and querySelectorAll, this seem to work. Can I get any more efficient? I don't seem to have to use complete path ( A > B > C). Note that I added OrderDetail tags to example below. I validates without this, but just seems cleaner.
var myOrders =
"<?xml version='1.0' encoding='UTF-8'?>" +
"<Orders>" +
"<Order>" +
"<OrderHeader>" +
"<OrderNo>12345</OrderNo>" +
"</OrderHeader>" +
"<OrderDetails>" +
"<OrderDetail>" +
"<Sku>ABC</Sku>" +
"<Qty>2</Qty>" +
"</OrderDetail>" +
"<OrderDetail>" +
"<Sku>DEF</Sku>" +
"<Qty>4</Qty>" +
"</OrderDetail>" +
"</OrderDetails>" +
"</Order>"...;
document.write("</br>4. Get all Orders Numbers and SKU Ordered for each Order</br>");
myOrders= xmlDoc.getElementsByTagName("Order");
// iterate through orders
for(x = 0; x < myOrders.length; x++){
var myOrder = myOrders[x].querySelector('OrderNo').textContent;
document.write(myOrder + "</br>");
// iterate through SKUS in each order
var mySkus = myOrders[x].querySelectorAll('OrderDetail > Sku');
for(y = 0; y < mySkus.length; y++){
document.write("-- SKU: " + mySkus[y].firstChild.nodeValue + "</br>");
}
}
document.write("<hr>");
Is this the optimal way to load form data into a string and then to localStorage ?
I came up with this on my own, and I am not good in programming. It works, for what I need, but I am not sure if it's a bulletproof code?
<script>
var sg = document.getElementById("selectedGateway");
var sd = document.getElementById("selectedDestination");
var dm = document.getElementById("departureMonth");
var dd = document.getElementById("departureDay");
var dy = document.getElementById("departureYear");
var rm = document.getElementById("returnMonth");
var rd = document.getElementById("returnDay");
var ry = document.getElementById("returnYear");
var ad = document.getElementById("adults");
var ch = document.getElementById("option2");
$("#searchRequestForm").submit(function() {
var string = 'From: ' + sg.value + ' \nTo: ' + sd.value + ' \nDeparture: ' + dm.value + '/' + dd.value + '/' + dy.value + ' \nReturn: ' + rm.value + '/' + rd.value + '/' + ry.value + ' \nNumber of adults: ' + ad.value + ' \nNumber of children: ' + ch.value;
localStorage.setItem("string", string);
});
</script>
I would use something like the following so that I could deal with an object and its properties rather than a big string. Note that other than the jQuery selectors, this is pure JavaScript.
Demo: http://jsfiddle.net/grTWc/1/
var data = {
sg: $("#selectedGateway").val(),
sd: $("#selectedDestination").val()
// items here
};
localStorage.setItem("mykey", JSON.stringify(data));
To retrieve the data:
var data = JSON.parse(localStorage["mykey"]);
alert(data.sg);
See Also:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify
http://api.jquery.com/jQuery.parseJSON/
I prefer a table driven approach so there is no repeated code (DRY):
var ids = [
"selectedGateway", "From: ",
"selectedDestination", "\nTo :",
"departureMonth", "\nDeparture: ",
"departureDay", "/",
"departureYear", "/",
"returnMonth", " \nReturn: ",
"returnDay", "/",
"returnYear", "/",
"adults", " \nNumber of adults: ",
"option2", " \nNumber of children: "];
var submitStr = "";
for (var i = 0; i < ids.length; i+=2) {
submitStr += ids[i+1] + document.getElementById(ids[i]).value;
}
localStorage.setItem("string", submitStr);
You could define a function such as the one below to directly get the values by id so then it would be simpler when you build your string.
function form(id) {
return document.getElementById(id).value;
}