Code not getting expected values when reading URL parameters - javascript

I've been racking my brain about this and I can not figure out why this isn't working.
I have a link that looks like this:
http://exampledomain.com/page.html?var1=42&var2=hello
and page.html is calling a javascript page that says:
alert(var1);
alert(var2);
But when I test the page all I get is function Number() { [native code] }
Anybody know what I could be going wrong?

Use this function:
var GET = function(query){
var varsArray = [],
url = window.location.search.match(/[^\?\&]+/g),
vars = [];
for(var i=0;i<url.length;i++)
if(/\=/.test(url[i]))
vars.push(url[i]);
for(var i=0;i<url.length;i++){
var This = url[i].split('=');
varsArray[This[0]] = This[1];
}
return query ? varsArray[query] : (varsArray || '');
}

Related

Object handling in Chrome/FF?

I have this code:
$('.gBook').click(function(){
var values = [];
var getDiff = $('#totalPrice').attr("data-value");
var i = 0;
$('td[data-check="true"]').each(function(){
var valueToPush = { };
valueToPush["price"] = $(this).attr("data-price");
valueToPush["id"] = $(this).attr("data-id");
valueToPush["diff"] = getDiff;
values.push(valueToPush);
i++;
});
var arrayToSend = {values};
$.post( '<?php echo PATH;?>ajax/updateRoom.php',arrayToSend, function(data){
if(data != "ERROR"){
$('#all-content').html(data).css("overflow-y","auto");
}else{
alert("ERROR");
}
});
});
In Chrome, this line gives an error var arrayToSend = {values}; (Uncaught SyntaxError: Unexpected token }) In Firefox everything is fine.
I guess it's because of the rather "loose" error handling of FF, but how am I doing it correctly?
I tried to initialize the object with var arrayToSend = new Object(); before the $.each, but that gives an empty array after POST.
Where is my mistake?
try this
var arrayToSend = {optionsChosen:values};
Then in php or whatever you use for data handling look for the POST variable optionsChosen.
What you did was try to make an Object with parameter array = nothing
You basically did this in your code. It doesn't take an expert to see whats wrong with this statement.
arrayToSend = new function() {
this.(new Array(1,2,3)); // This is cringeworthy if you see it like this.
}
In the example I gave it translates to this:
arrayToSend = new function() {
this.optionsChosen = new Array(1,2,3);
}

JSON.stringify not working - undefined

I'm getting into troubles with JSON in javascript. I have one code where I use the JSON.stringify all the time and never had problems with it. But when I enter my application, I cannot use it. It keeps returning me in console (Google Chrome) the following:
Uncaught TypeError: undefined is not a function lista.js:188
which is definetly the line where the stringify function is on.
Do any of you know any ways to solve this problem? It's like the JSON unit is not found or something. Or maybe a workaround... I'll post my code below:
Thanks in advance!
in my index.php I have a header with:
<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
//This is the code to the function.
function Salvar(AIdProcesso){
var Respostas = new Array ();
var Registro = 1;
$('.chkResposta').each(function(){
var chk = $(this);
var IdTitulo = chk.attr("idTitulo");
var Valor = chk.isChecked() ? 'true' : 'false';
var Item = [IdTitulo, Valor];
Respostas[Registro] = Item;
Registro = Registro+1;
});
$('.edtValor').each(function(){
var edt = $(this);
var IdTitulo = edt.attr("idTitulo");
var Valor = edt.val();
var Item = [IdTitulo, Valor];
Respostas[Registro] = Item;
Registro = Registro+1;
});
//this is where I get the error!!
var JsonString = JSON.stringify(Respostas, function(){}, 2);
$.post(
'processos/lista.php', {
Op: 'Inscricao',
Id: AIdProcesso,
Itens: JsonString
}, function(rHtml){
JSON = jQuery.parseJSON(rHtml);
$('.breadcrumb').html(JSON.breadcrumb);
$('.Box').html(JSON.box);
});
}
On this line
var JsonString = JSON.stringify(Respostas, function(){}, 2);
you're passing in a replacer function that doesn't return anything. The replacer function you pass into stringify is expected to return something. Refer to the specification for details.
Side note: You're including json2.js in your page, but note that all modern browsers, as well as IE8, support JSON natively. Unless you need to support IE7 and earlier, or truly old browsers from other vendors, you don't need that script anymore.

Javascript to Read/Count Sharepoint 2010 List Items

I am having a lot of trouble with this. Essentially, I am trying to count the number of times Decommission appears in a particular list column. From what I can tell, the javascript is correct, but it doesn't work. Can anyone provide some guidance? Thanks!
<script type="text/javascript">
var myItems = null;
var siteUrl = &apos;https://chartiscorp.sp.ex3.secureserver.net/&apos;
function SuperDuper()
{
var queryString = &apos;<View><Query><Where><Gt><FieldRef name="End State" /><Value Type="String">Decommission</Value></Gt></Where></Query></View>&apos;;
var myContext = new SP.ClientContext(siteUrl);
var myWeb = myContext.get_web();
var myList = myWeb.get_lists().getByTitle(&apos;System_Information&apos;);
var myQuery = new SP.CamlQuery();
myQuery.set_viewXml(queryString);
myItems = myList.getItems(myQuery);
myContext.load(myItems,&apos;Includes(End State)&apos;);
myContext.executeQueryAsynch(Function.createDelegate(this,SuperDuperSuccess),Function.createDelegate(this,SuperDuperFail));
}
function SuperDuperFail(sender, args)
{
alert(&apos;Failed &apos; + args.get_message());
}
function SuperDuperSuccess(sender, args)
{
var endStateEnumerator = myItems.getEnumerator();
var decommCount = 0;
while(endStateEnumerator.moveNext())
{
//var currentEndState = endStateEnumerator.get_current();
decommCount = decommCount + 1;
}
alert(decommCount);
}
window.onload = SuperDuper;
</script>
What is the error?
Have you tried to see the script error it is throwing?
In function SuperDuperSuccess() you can simply put
var count=0;
count=this.myItems.get_count();
No need to write while loop .
Pls try to put alert and after some line and see what is coming.

Cannot access children of JSON object

I have a JSON object musicianobj, an example of which I have pasted below:
{
id: "451026389391"
name: "John Frusciante"
type: "profile"
url: "http://open.spotify.com/artist/XXXXXXXXXXXXXX"
}
I got this from the Facebook API using the Javascript SDK. I can run console.log(musicianobj); which successfully prints the object to the log in Chrome, but console.log(musicianobj.name);, console.log(musicianobj[1]);, and console.log(musicianobj["name"]); all return undefined for no apparent reason. Any ideas?
Edit: code below.
var playFriendsTrack = function(friend){
FB.api("/"+friend+"/music.listens", function(data) {
var songname = data.data[0].data.song.title;
var artistname = "";
FB.api(data.data[0].data.song.id,function(trackdata){
var musicianobj = trackdata.data.musician;
console.log(musicianobj);
console.log(musicianobj["name"]); // Doesn't work
console.log(musicianobj.name); // Doesn't work
artistname = musicianobj[1]; // Doesn't work
});
if(artistname.length <= 0){
alert("Error! Please try another friend.")
}
}
);}
Have you decoded it? It seems it is still a string.
musicianobj = JSON.parse(musicianobj);
console.log(musicianobj.name); // Now this should work
Got it working! I had to put a [0] after musicianobj. Apparently I don't know JSON as much as I'd like to. The working code is pasted below:
var playFriendsTrack = function(friend){
FB.api("/"+friend+"/music.listens", function(data) {
var songname = data.data[0].data.song.title;
var artistname = "";
FB.api(data.data[0].data.song.id,function(trackdata){
var musicianobj = trackdata.data.musician;
console.log(musicianobj);
console.log(musicianobj[0]["name"]);
console.log(musicianobj[0].name);
artistname = musicianobj[0].name;
});
if(artistname.length <= 0){
alert("Error! Please try another friend.")
}
}
);}

Why am I recieving the error 'document.write can be a form of eval'?

This is all I've got going, but my debugger says 'document.write can be a form of eval,' and my jsonString variable prints as undefined. Any help is appreciated, thanks.
function getUrlVars() {
var map = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
map[key] = value;
});
return map;
}
var jsonString = getUrlVars()['json'];
document.write(jsonString);
The reason document.write can be a form of eval is because if you write a script element it will be evaluated.
As for why your jsonString is undefined, you probably don't have a parameter named 'json'.

Categories

Resources