Error ' missing : after property id' when using Jquery ajax function - javascript

In the following code, I'm trying to send a key-value pair and I always get the error:
" missing: after property id "
$(".general").change(function () {
fields = { $(this).attr('id') : "1" };
$.ajax({
type: "POST",
url: "ajax/update_general.php",
data: { fields: fields },
dataType: "json",
});
})
I've figured that what causes the problem is:
$(this).attr('id')
But I have no clue why. I've tried to first assign $(this).attr('id') to a variable, and put the variable in the ajax call, but that didn't help.
How can I fix that?
Thank you!

It's a syntax error. You can't use the return value of a function call as a property name.
You can, however, use that return value in bracket notation after initializing the object:
fields = {};
fields[$(this).attr('id')] = '1';

When declaring object with {} syntax, ONLY strings (like {'foo':1}) or bare string is allowed ({foo:1})
You should write something like this:
var fields = {};
fields[$(this).attr('id')] = 1;

Change this line:
fields = { $(this).attr('id') : "1" };
to this:
fields = $(this).attr('id') || "1";
That's if you intended to have something like a default value.
If you want an object, use this:
fields[$(this).attr('id')] = "1";

Related

Javascript Not Passing Value to Function

Hi I am trying to pass 3 values into some Javascript. This works for the first function. All values are found to be correct here......
function handleClick(cb,colum,id) {
if (cb.checked == true){
var checked = 1;
} else {
var checked = 0;
}
sendHddToPHP2(checked,column,id);
}
But once the second function is called I get nothing....
function sendHddToPHP2(editableObj,column,id) {
window.alert(editableObj);
$.ajax({
url: "update/hdd.php",
type: "POST",
data:'column='+column+'&editval='+editableObj+'&id='+id,
success: function(data){
$(editableObj).css("background","#FDFDFD");
}
});
}
I added the alert to check if the variable was present and it didn't run. I can't see any typos and my knowledge isn't that great on Javascript. Is there something I have missed?
You have a typo: "colum" in the argument list.
Also, seems like you want to access the check box later in the Ajax callback, that will fail since you're trying to reference it via the "editableObj" value of the checkbox rather than the element.
As I understand you want your function to be like this:
function handleClick(cb,colum,id) {
var checked = (cb.checked)?1:0;//same as(cb.checked==true)1:0
sendHddToPHP2(checked,column,id);
}
but are you sure you want to return a 1 or 0? because in the second function you will be using $(1).css("background","#FDFDFD");
$(0).css("background","#FDFDFD");

Multiy String Variable Names Not Working In Javascript

Recently I posted about Dynamic Names in Javascript. I went ahead and tried to make a multi string variable name (combining a string and a variable to make a new variable name), and it does not seem to work. I am very confused because I am doing what many posts on SO say to do (so I think anyhow).
Anyhow here is the dynamic variable I am using:
var dynamic["replyupvote"+replyid] = false;
and then when I am calling it I use:
dynamic["replyupvote"+replyid]
So my question is where am I going wrong? If you would like to see my full code:
function replyupvote(replyid, upvotes, downvotes, votesclass, votesnumber) {
var dynamic["replyupvote"+replyid] = false;
return function() {
if (dynamic["replyupvote"+replyid]) {
dynamic["replyupvote"+replyid] = true;
}
else {
$.ajax({
url: "http://localhost/postin'/categories/votes.php",
type: "POST",
data: { 'itemid': replyid,
'userid': <?php echo $_SESSION["logged_in"]; ?>,
'action': "upvotes",
'type': "reply" },
success: function() {
$("." + votesclass).css("color", "orange");
$("." + votesnumber).text(parseInt(upvotes - downvotes) + 1);
}
});
dynamic["replyupvote"+replyid] = true;
}
}
}
This code worked before I through in the Multi String Variable Names. So what am I doing wrong? Thank You! :)
EDIT
I thought I should throw this in. Javascript throws the error that the function is not defined because of the incorrect syntax.
Regardless if what you are doing here makes sense or not, to dynamically create properties on an object, you will need to make sure JS knows it's an object, not an array. So before you try to create a dynamic object property, explicitly declare dynamic as an object:
var dynamic = {};
dynamic["replyupvote"+replyid] = false;
That should get rid of the syntax error at least.
You would have to set dynamic as an object first
var dynamic = {};
dynamic["replyupvote"+replyid] = false;
variableName[keyName] = value; is the syntax of an object.
You have to tell js that your variable is an object before you can use this notation.

JS/JQ: Access variable from inline function

I'm trying to use a variable inside my getJSON function. How can I pass it in? This is what I've tried.
function getComments(parent_id) {
if(typeof(parent_id)==='undefined') parent_id = -1;
console.log("parent_id type: " + typeof(parent_id)); // parent_id type: number
var message = { parentMessageID: parent_id };
$.getJSON(UPDATECOMMENTCALL, message, function(data, parent_id) {
console.log("JSON parent_id: " + typeof(parent_id)); // JSON parent_id: string
}
}
Instead of parent_id being -1 inside the function, it's a string with value "success". How can I pass it in properly?
You can just use it, don't put it as a parameter inside the callback function of the getJSON, just use it as a variable, because it's already global.
You callback function parameter has a higher priority than the scope variable with the same name (parent_id). So by accessing it inside the callback function you're actually refering to the function parameter rather than the variable you've defined outside of the function. Changing the name of the callback variable will fix it. For example:
var parent_id = -1;
console.log("parent_id type: " + typeof(parent_id)); // parent_id type: number
var message = { parentMessageID: parent_id };
$.getJSON(UPDATECOMMENTCALL, message, function(data, p_id) { // changed to p_id
console.log("JSON parent_id: " + typeof(parent_id)); // JSON parent_id: string
}
Generally, it's a good idea to avoid using the same names thus staying away from all the duplicate name mess.
Simple example to show you what's going on:
var a = 1;
function f(a) {
console.log(a);
}
Think what will f(2); output.

how to pass function in json as a function?

in arrayRec , onShow value should be a function.
Following is my reference code.
Any help?
This is my reference code:
if (rec.element_flag == '111'){
var arrayRec = [];
$.ajax({
type:'GET',
url: "/aps/one-url",
success: function(responseData){
for (var i = 0; i < responseData.length; i++){
var recJ;
var newFunction1 = function onshowdata(counter){
if(responseData[counter].fields.on_show_fn != null){
return function responseData[counter].fields.on_show_fn;
}
else
return;
}
recJ = {
element: responseData[i].fields.element_class,
placement: responseData[i].fields.placement,
title: responseData[i].fields.title,
content: responseData[i].fields.content,
onShow: newFunction1(i)
}
arrayRec.push(recJ);
console.log('-------arrayRec------');
console.log(arrayRec)
aps.walk.setupBootstrap(arrayRec);
}
},
error: function(){
alert('get failure');
}
});
}
Tried many ways but what I am missing?
in JSON, only text can be used, not objects. Functions are objects too. So, in JSON, name of the function can be passed, not the function object. An alternate way is to send the text of that entire function, which can be run using "eval", though this way is not recommended.
Use closure technique here. Define function above the ajax code, and use the name of the function inside it, which is a standard method of doing this.

Add objects to array javascript, and associative array?

I'd like to create array filters_array, first thing I noticed in console is that filter_group is nowhere to be found, is this a correct way to save objects?
Second, on second click I want array to grow, but at this point it is only overwritten, what am I doing wrong?
//
var filters_array;
//Ajax call to filter movies, grab them and reload container
$(".option-set a").on("click", function(){
var filter_value = $(this).data("filter-value");
var filter_group = $(this).parents("ul").data("filter-group");
filters_array = {filter_group : filter_value};
console.dir(filters_array);
$.ajax({
url: templatePath + "getmovies.php",
type: "GET",
data: "",
cache: false,
success: function (data){
console.dir("ajax call success!");
}
});
return false;
});
"Associative arrays" in JavaScript are simply objects. We usually call them "objects" or "maps", to avoid confusing them with "arrays" (which aren't really arrays in JavaScript, but let's ignore that for now).
You want to initialize your filters_array with a blank object:
var filters_array = {};
...and then within the click handler, to add an entry to it with the key being the value of the filter_group variable and the value being the value in the filter_value variable:
filters_array[filter_group] = filter_value;
So for instance, if filter_group had the value "foo" and filter_value had the value "bar", you'd end up with a property on filters_array called foo with the value "bar". You could then access that property in several ways:
console.log(filters_array["foo"]); // "bar"
console.log(filters_array.foo); // "bar"
var x = "foo";
console.log(filters_array[x]); // "bar"
// Loop through all of the filter groups you've added
var key;
for (key in filters_array) {
// here, `key` will be `"foo"` (for instance)
console.log(filters_array[key]); // One of these will be "bar"
}
I'd like to create array filters_array, first thing I noticed in console is that filter_group is nowhere to be found, is this a correct way to save objects?
Yes, it is the right way, but it is right that you can't see it from the console, it is declared inside the function's scope. But you can do this if you need to access it from the outside:
var filters_array, filter_value, filter_group; //hoisted here
//Ajax call to filter movies, grab them and reload container
$(".option-set a").on("click", function(){
filter_value = $(this).data("filter-value");
filter_group = $(this).parents("ul").data("filter-group");
filters_array = {filter_group : filter_value};
console.dir(filters_array);
$.ajax({
url: templatePath + "getmovies.php",
type: "GET",
data: "",
cache: false,
success: function (data){
console.dir("ajax call success!");
}
});
return false;
});
Second, on second click I want array to grow, but at this point it is only overwritten, what am I doing wrong?
Well that's simple, you're initializing it again and again assigning it a new object every time, you have to do this:
filters_array[filter_group] = filter_value;
After having assigned to filters_array an empty object outside the function scope. Obviously you need to remove filters_array = {filter_group : filter_value}; and replace it with that line!

Categories

Resources