How to use element name when initializing object in javascript? - javascript

I'm trying to get data using ajax function, but my code returns :
Uncaught SyntaxError: unexpected string..
Javascript :
var myParams = {
$('#csrf').attr('name') : $('#csrf').val(),
'module' : 'culinary',
'id' : '12',
}
$.ajax({
url: '/uploader/get_list',
type: 'GET',
data: myParams,
success: function(response) {
reponse = $.parseJSON(response);
console.log(response);
}
});
One of my friends suggested to use this:
var myParams = [];
myParams[$('#csrf').attr('name')] = $('#csrf').val();
myParams['module'] = 'culinary';
myParams['id'] = '12';
But if I use the second method, the PHP function can't recognize the parameters.
What's the correct way to send parameters to an ajax function?

The issue is in your creation of the myParams object. To create a key using a variable you need to use bracket notation. Try this:
var myParams = {
'module': 'culinary',
'id': '12',
}
myParams[$('#csrf').attr('name')] = $('#csrf').val();
The second example you have doesn't work because you create an array, ie. [], not an object, {}.
Also note that if you set the dataType property of the request then you don't need to manually parse the response as jQuery will do it for you:
$.ajax({
url: '/uploader/get_list',
type: 'GET',
data: myParams,
dataType: 'json',
success: function(response) {
console.log(response);
}
});

You should define new object {} and not new array [] :
var myParams = [];
Should be :
var myParams = {};
Hope this helps.

Related

how to get variable name on loop javascript, and variable type is array

this is my varibale in js
var schemapost = {};
var schemacrumb = {};
var og = {};
var meta = {};
$.get('json', function(resp) {
schemapost = {
"#context":"http://schema.org",
"#type":"Article",
"mainEntityOfPage":permalink,
"headline":title,
"description":description
};
schemacrumb = {
"#context":"http://schema.org",
"#type":"BreadcrumbList",
};
og = {
"fb:app_id":resp.facebook_app_id,
"fb:admins":resp.facebook_id,
};
meta = {
"description":description,
"keywords":post_keyword,
"robots":"noodp"
};
});
so i collect all variable in one variable which is
var schema = [schemapost,schemacrumb,og,meta];
and i try to loop that variable and got confused
foreach ( a in schema ){
jQuery.ajax({
type: "POST",
url: "/make_schema.php",
data: { data : JSON.stringify(???EACH VARIABLE NAME??),
post_name : slug ,
variablename : ???EACH VARIABLE NAME?? },
});
}
obviously stupid but i try this:
var schema = ["schemapost","schemacrumb","og","meta"];
schema.forEach(function(entry) {
jQuery.ajax({
type: "POST",
url: "/kode/post/make_json",
data: {value : JSON.stringify(entry), post_name:slug, variablename:entry},
});
});
and output is string.. not variable array data like i want,
any suggestion how to loop array variable and get each variable name so i can use for data:variablename in ajax function?
Just send the complete schema array that you have created,
var schema = [schemapost,schemacrumb,og,meta];
using Jquery post method as :
$.ajax({
type: "POST",
url: "/make_schema.php",
data: { data : schema ,
post_name : slug
});
and catch the complete array in backend process as array

I need to serialize an object to JSON. I'm using jQuery. Is there a "standard" way to do this?

I need to serialize an object to JSON. I'm using jQuery. Is there a "standard" way to do this?
My specific situation: I have an array defined as shown below:
var countries = new Array();
countries[0] = 'ga';
countries[1] = 'cd';
...
and I need to turn this into a string to pass to $.ajax() like this:
$.ajax({
type: "POST",
url: "Concessions.aspx/GetConcessions",
data: "{'countries':['ga','cd']}",
...
You can use JSON.stringify(countries);
var c = {
countries: countries
}
$.ajax({
type: "POST",
url: "Concessions.aspx/GetConcessions",
data: JSON.stringify(c),
contentType: "application/json"
...
Note that you will want to specify contentType; otherwise, URI-encoding is assumed.
You can use JSON.stringify() to turn any object in to a JSON string:
var countries = new Array();
countries[0] = 'ga';
countries[1] = 'cd';
var json = JSON.stringify({ countries: countries}); // = '{"countries":["ga","cd"]}'
// or more simply:
var countries = [ 'ga', 'cd' ];
var json = JSON.stringify({ countries: countries}); // = '{"countries":["ga","cd"]}'
However, you should note that it's better practice to provide the data property of $.ajax with an object as jQuery will then create the JSON for you and at the same time escape any invalid characters and do any required encoding. Try this:
$.ajax({
type: "POST",
url: "Concessions.aspx/GetConcessions",
data: {
'countries': countries
}
});
you can use JSON.parse() to convert object to json
like this
countries = JSON.parse(countries);
object is convert in json and store in countries variable

Creating multidimensional array inside each

I want to create a multidimensional array from the values I retrieved on an ajax post request.
API response
[{"id":"35","name":"IAMA","code":"24"},{"id":"23","name":"IAMB","code":"08"}]
jQuery code
var mulArr = [];
$.ajax({
type: 'POST',
url: '/path/to/APIendpoint',
dataType: 'json',
data: {
codes: codes
},
success: function(data) {
$.each(data, function(key, value) {
mulArr[key]['id'] = value.code;
mulArr[key]['text'] = value.name;
});
}
});
Syntax error
TypeError: mulArr[key] is undefined
I can properly fetch the data from the endpoint, the only error I encounter is the one I stated above. In perspective, all I want to do is simply a multidimensional array/object like this:
mulArr[0]['id'] = '24';
mulArr[0]['text'] = 'IAMA';
mulArr[1]['id'] = '08';
mulArr[1]['text'] = 'IAMB';
or
[Object { id="24", text="IAMA"}, Object { id="08", text="IAMB"}]
It happens because mulArr[0] is not an object, and mulArr[0]['id'] will throw that error. Try this:
var mulArr = [];
$.ajax({
type: 'POST',
url: '/path/to/APIendpoint',
dataType: 'json',
data: {
codes: codes
},
success: function(data) {
$.each(data, function(key, value) {
mulArr.push({id: parseInt(value.code), text: value.name});
// or try this if select2 requires id to be continuous
// mulArr.push({id: key, text: value.name});
});
}
});
Alternative to using push (which is a cleaner approach) is to define the new object.
mulArr[key] = {
id: value.code,
text:value.name
};
Another way of achieving what you want would be this one:
var mulArr = [];
$.ajax({
type: 'POST',
url: '/path/to/APIendpoint',
dataType: 'json',
data: {
codes: codes
},
success: function(data) {
mulArr = data.map(value => ({ id: parseInt(value.code), text: value.name }));
}
});
This is cleaner and also uses builtin map instead of jQuery $.each. This way you also learn the benefits of using the map function (which returns a new array) and also learn useful features of ES2015.
If you cannot use ES6 (ES2015) here is another version:
mulArr = data.map(function (value) {
return {
id: parseInt(value.code),
text: value.name
};
});
I guess you can already see the advantages.

Getting Record has been added successfully.[obect Object] instead of actual values [duplicate]

This question already has answers here:
What does [object Object] mean?
(12 answers)
Closed 8 years ago.
The script below normally returns values formatted in into JSON object as shown below:
{"Value":null,"Status":2,"Message":"Greetings."}
For the past couple of days, we have been getting:
Record has been added successfully.**[obect Object]**
Any ideas what could have gone wrong?
This is the code below.
<script type="text/javascript">
function CallService() {
//Creating an object to hold token form field
myToken = new Object();
myToken.Token = $("#token").val();
//Creating an object to hold form fields
myData = new Object();
// Creating variables to hold data from textboxes. First building associated details
myData.Address = $("#Address").val();
myData.CallerAcctNum = $("#CallerAcctNum").val();
myData.CallerAddress = $("#CallerAddress").val();
myData.CallerCellPhone = $("#CallerCellPhone").val();
myData.CallerCity = $("#CallerCity").val();
myData.CallerComments = $("#secondarysitecontact").val();
myData.CallerDistrict = $("#CallerDistrict").val();
myData.CallerEmail = $("#CallerEmail").val();
myData.CallerFax = $("#CallerFax").val();
myData.CallerFirstName = $("#CallerFirstName").val();
myData.CallerHomePhone = $("#CallerHomePhone").val();
myData.CallerLastName = $("#CallerLastName").val();
myData.CallerMiddleInitial = $("#CallerMiddleInitial").val();
myData.CallerState = $("#CallerState").val();
myData.CallerWorkPhone = $("#CallerWorkPhone").val();
myData.CallerZip = $("#CallerZip").val();
myData.City = $("#City").val();
myData.Details = $("#comments").val();
myData.District = $("#District").val();
myData.Location = $("#Location").val();
myData.ProblemSid = $("#RequestID").val();
myData.State = $("#State").val();
myData.StreetName = $("#StreetName").val();
myData.X = $("#X").val();
myData.Y = $("#Y").val();
myData.SiteContactDisplay = $("#sitecontact").val();
myData.Comments = $("#comments").val();
myData.Text1 = $("#deptId").val();
$.ajax({
type: "POST",
url: "proxyCreate.php",
data: {
data: JSON.stringify(myData),
token: myToken.Token
},
dataType: "json",
async: false,
success: function (response) {
alert("Record has been added successfully." + response );
window.location.reload();
}
});
return false;
}
</script>
alert() cannot print an {} object [object Object] unless you JSON.stringify it.
If you usually returned from your success this object:
{"Value":null,"Status":2,"Message":"Greetings."}
from your response argument, than you need to access a desired Object property like:
alert( response.Message );
otherwise, if you want to read fully the object do something like:
alert( JSON.stringify( response, null, "\t") );
Furthermore, to simplify your code I made some changes:
function v(id){ return $("#"+id).val(); } // Get value
function CallService() {
var myToken = v("token");
var myData = {
Token : v("token"),
Address : v("Address"),
CallerAcctNum : v("CallerAcctNum"),
CallerAddress : v("CallerAddress"),
CallerCellPhone : v("CallerCellPhone"),
CallerCity : v("CallerCity"),
CallerComments : v("secondarysitecontact"),
CallerDistrict : v("CallerDistrict"),
CallerEmail : v("CallerEmail"),
CallerFax : v("CallerFax"),
CallerFirstName : v("CallerFirstName"),
CallerHomePhone : v("CallerHomePhone"),
CallerLastName : v("CallerLastName"),
CallerMiddleInitial : v("CallerMiddleInitial"),
CallerState : v("CallerState"),
CallerWorkPhone : v("CallerWorkPhone"),
CallerZip : v("CallerZip"),
City : v("City"),
Details : v("comments"),
District : v("District"),
Location : v("Location"),
ProblemSid : v("RequestID"),
State : v("State"),
StreetName : v("StreetName"),
X : v("X"),
Y : v("Y"),
SiteContactDisplay : v("sitecontact"),
Comments : v("comments"),
Text1 : v("deptId")
};
$.ajax({
type: "POST",
url: "proxyCreate.php",
data: {
data: JSON.stringify(myData),
token: myToken
},
dataType: "json",
async: false,
success: function (response) {
console.log( response ); // open console and take a look.
alert("Record has been added successfully." + response ); // Nest with "." like response.something to print property you need
// window.location.reload(); // Do this later after you fix the bug
}
});
return false;
}
You have to specify which part of the object you want to print, for instance if you wanted the message:
$.ajax({
type: "POST",
url: "proxyCreate.php",
data: {
data: JSON.stringify(myData),
token: myToken.Token
},
dataType: "json",
async: false,
success: function (response) {
alert("Record has been added successfully." + response.Message );
window.location.reload();
}
});
You're trying to use alert, which takes an string and prints it on a dialog, and giving it an object, which... well, it's not an string. Your object CONTAINS strings, so you can access them and print them instead of trying to print the entire object, like show in the code above, where I whent to the message attribute of the response object.
Even simpler example: http://jsfiddle.net/9c0xLwcq/

How can I use the content of a data attribute as a hash key?

I have a DOM element with :
data-update-attribute='name' data-update-url='users/1'
And I want to do something like this:
$.ajax({ type: 'PUT',
url: $el.data('update-url'),
data: { user: { xxx: value } }
});
My problem is that I cant figure out how to replace the xxx with the content from data-update-attribute. This would be trivial in Ruby but I am totally clueless about how to do it in JS :-S
Thanks!
You can't in object literals, you will need to construct an object without the key and then use bracket notation:
var url = $el.data('update-url'),
attr = $el.data('update-attribute'),
user = {};
user[attr] = value;
$.ajax({
type: 'PUT',
url: url,
data: { user: user }
});

Categories

Resources