AJAX Data with Dynamic form fields name - javascript

Hello how can can make my ajax data call to be dynamic, I tried this
var opt_name = $(".NAME").data('opt_name');
var opt_business = $(".BUSINESS").data('opt_business');
var opt_phone = $(".PHONE").data('opt_phone');
var opt_email = $(".EMAIL").data('opt_email');
var opt_unique_name=$(".UNIQUE_NAME").data('opt_unique_name');
var opt_name_val = $(".NAME")[key].value;
var opt_business_val = $(".BUSINESS")[key].value;
var opt_phone_val = $(".PHONE")[key].value;
var opt_email_val = $(".EMAIL")[key].value;
var opt_u_val = $(".U_VAL").data('opt_u_val');
var opt_userid_val = $(".USER_ID_VAL").data('opt_user_id_val');
var dataString = {'u': opt_u_val,
'id': opt_userid_val,
opt_email: opt_email_val,
opt_name : opt_name_val,
opt_phone : opt_phone_val,
opt_business : opt_business_val,
opt_unique_name : ''};
$.ajax({
type: 'post',
url: 'https://vative.us15.list-manage.com/subscribe/post',
dataType: "json",
data: dataString, // should be the same as below
// data: {
// 'u': '559dd913b49efd5f5515155bb',
// 'id': '0985c209f3',
// 'MERGE0': opt_email_val,
// 'NAME' : 'Test 3',
// 'PHONE' : '829121',
// 'BUSINESS' : 'hskslas',
// 'b_559dd913b49efd5f5515155bb_0985c209f3' : ''
// },
success: function(data) {
console.log('Submitted');
},
error: function(data){
console.log('Error');
console.log(dataString);
}
});
}
});
I just want to get the field name since this field names always changes depending on the database or from embedded form.
The problem on my above code is that this will work.
data: {
'u': '559dd913b49efd5f5515155bb',
'id': '0985c209f3',
'MERGE0': opt_email_val,
'NAME' : 'Test 3',
'PHONE' : '829121',
'BUSINESS' : 'hskslas',
'b_559dd913b49efd5f5515155bb_0985c209f3' : ''
},
but not this
data: {'u': opt_u_val,
'id': opt_userid_val,
opt_email: opt_email_val,
opt_name : opt_name_val,
opt_phone : opt_phone_val,
opt_business : opt_business_val,
opt_unique_name : ''};

In order to generate dynamic keys inside your object, there is a very clean approach in the new ES2015 standard for JavaScript (formerly called ES6).
The syntax is the following:
var obj = {
[myKey]: value,
}
So your code would look like this:
data: {'u': opt_u_val,
'id': opt_userid_val,
[opt_email]: opt_email_val,
[opt_name]: opt_name_val,
[opt_phone]: opt_phone_val,
[opt_business]: opt_business_val,
[opt_unique_name]: ''
};

It sounds like your goal is to have dynamic keys in your data object?
The reason your example isn't working is that instantiating an object uses the literal value of the keys (so basically a string), whereas what you want is the string value of the variable in the scope.
It's a bit messy to do, but I can think of two possibilities:
data = {};
data[opt_email] = opt_email_val;
data[opt_phone] = opt_phone_val;
// and so on for each dynamic key to value
Alternatively the following may work (after transpilation depending on your targets), though I have not tried it:
data = {
`${opt_email}`: opt_email_val,
`${opt_phone}`: opt_phone_val,
// and so forth
};
This second example works using the Template literal syntax which will take the value of the variable and expand it into the string.

Related

Get JSON array data by field name

I'm trying to get JSON data by field name like this data.name and it return the desired data, but I have 25 fields in the array and I want to make this dynamically, using data + "." + variable, when I alert it returns [Object object].name, so how I can make it executable?
I tried many ways but all failed, please help me doing this.
$.ajax({
type: "Get",
url: "/Home/Report_Data",
datatype: "json",
dataSrc: "",
contentType: 'application/json; charset=utf-8',
data: {
'Arrnagement': Arrnagement
},
success: function(data) {
var result = getElementsById("LD_name LD_Loan_Type LD_id LD_Full_Name_AR LD_GENDER LD_BIRTH_INCORP_DATE LD_PS_MOTHER_NAME LD_Street_AR LD_TEL_MOBILE LD_EMPLOY_STATUS_D LD_EMPLYRS_Name LD_MARITAL_STATUS LD_PS_PL_OF_BIR_AR LD_wifeName LD_Effective_Interest_Rate LD_Contract_amount LD_Repayment_Amount LD_Sector_name LD_NUM_REPAYMENTS LD_Loan_Maturity LD_Orig_Contract_Date LD_Loan_CCY LD_Arrangement LD_COLLATERAL_TYPE LD_Description LD_COLLATERAL_VALUE LD_COLLATERAL_Currency LD_GUARANTOR_ID LD_NATIONALITY LD_G_Full_Name_En LD_G_DATE_OF_BIRTH LD_G_PLACE_OF_BIRTH LD_G_MOTHER_NAME_EN LD_HOUSING_LOAN_AREA_CLASS LD_HOUSING_PROPERTY_NATURE LD_HOUSING_LOAN_PURPOSE LD_HOUSING_PROPERTY_AREA");
var jid;
for (var i = 0; i < result.length; i++) {
jid = (result[i].id.substring(3));
var resulting = data[0].jid;
alert(resulting);
if (result[i].innerHTML = data[0].jid != "undefined") {
result[i].innerHTML = data[0].jid;
} else {
result[i].innerHTML = "";
}
}
//jid = name;
//data[0].name returns "Joun"
//data[0]+"."+jid returns [object object].name but i need it to return "Joun"
This should work. I changed the dot notation while accessing the object property.
$.ajax({
type: "Get",
url: "/Home/Report_Data",
datatype: "json",
dataSrc: "",
contentType: 'application/json; charset=utf-8',
data: { 'Arrnagement': Arrnagement },
success: function (data) {
var result = getElementsById("LD_name LD_Loan_Type LD_id LD_Full_Name_AR LD_GENDER LD_BIRTH_INCORP_DATE LD_PS_MOTHER_NAME LD_Street_AR LD_TEL_MOBILE LD_EMPLOY_STATUS_D LD_EMPLYRS_Name LD_MARITAL_STATUS LD_PS_PL_OF_BIR_AR LD_wifeName LD_Effective_Interest_Rate LD_Contract_amount LD_Repayment_Amount LD_Sector_name LD_NUM_REPAYMENTS LD_Loan_Maturity LD_Orig_Contract_Date LD_Loan_CCY LD_Arrangement LD_COLLATERAL_TYPE LD_Description LD_COLLATERAL_VALUE LD_COLLATERAL_Currency LD_GUARANTOR_ID LD_NATIONALITY LD_G_Full_Name_En LD_G_DATE_OF_BIRTH LD_G_PLACE_OF_BIRTH LD_G_MOTHER_NAME_EN LD_HOUSING_LOAN_AREA_CLASS LD_HOUSING_PROPERTY_NATURE LD_HOUSING_LOAN_PURPOSE LD_HOUSING_PROPERTY_AREA");
var responseData = data[0];
var jid;
for (var i = 0; i < result.length; i++) {
jid = (result[i].id.substring(3));
var resulting = responseData[jid];
alert(resulting);
if (responseData[jid]) {
result[i].innerHTML = responseData[jid];
}
else {
result[i].innerHTML = "";
}
}
Try giving data[0][jid], we can give a variable in brackets also inorder to get the data
Hope it works
If do foo.bar you are getting a property with the name 'bar' on object foo. If you have some variable const bar = "qux" and you want to access property on some object with the same name as bar value /"qux"/ you just need to use square brackets - foo [bar], which will be the same as calling foo.qux; So, in your case you just need to use data[0][jid] instead of data [0].jid, supposing jid contains a string that is also a key in data[0].
You can just do data[0][variableName] and this will return the data you want. for example. If data had a json string [{ "Name" : "Jane Doe"}] You could execute it like this.
var variableName = "Name";
console.log(data[0][variableName])
This would return "Jane Doe".
if you have your field names in an array you can loop through them using $.each or a for loop.
For example say your json string is [{"First_Name" : "Jane", "Last_Name" : "Doe", "Age" : 32}] you could get all the values from the json string doing this.
var FieldNames = ["First_Name" , "Last_Name", "Age"]
$.each(FieldNames, function(i,item) {
console.log(data[0][item])
}
OR
var FieldNames = ["First_Name" , "Last_Name", "Age"]
for(var i = 0; i < FieldNames.length; i++) {
console.log(data[0][FieldNames[i]])
}

Javascript: Passing dynamic data name attribute in Ajax

I have the code below:
image_type = 'photo';
jQuery.ajax({
type: 'POST',
url: '?q=myid_save_input_image',
data:{
'template_id': 1,
'image_id': 2,
'primary_id': 3,
image_type : 4,
}
}).done(function(o){
});
I noticed when the code is executed. Looking at Network tab in Google Chrome Developer Tools:
I am expecting like this:
template_id: 1
image_id: 2
primary_id: 3
photo: 4
How will I achieved it? $image_type is dynamic, so the fourth attribute name can change every now then.
You need to make the object first, then use [] to set dynamic key using variable.
var formData = {
'template_id': 1,
'image_id': 2,
'primary_id': 3
};
image_type = 'photo';
formData[image_type] = 4;
jQuery.ajax({
type: 'POST',
url: '?q=myid_save_input_image',
data: formData
}).done(function(o){
});
Prepare the data variable beforehand and pass it to AJAX function.
Make it like this:
var image_type = "photo";
var dataToPass = {};
dataToPass['template_id'] = 1;
dataToPass['image_id']=2;
dataToPass['primary_id']= 3;
dataToPass[image_type] = 4;

passing the function parameter value to the function inside that function

I have this script which works fine but i want it to move to common js file.
function commonSelect2(selector,url,id,text){
selector.select2({
minimumInputLength:1,
placeholder:"Select Parent Menu",
ajax: {
type:"post",
url: url,
dataType: 'json',
quietMillis: 100,
data: function(term, page) {
return {
term: term, //search term
page_limit: 10 // page size
};
},
results: function(data, page ) {
var newData = [];
$.each(data, function (index,value) {
newData.push({
id: value.id, //id part present in data
text: value.text //string to be displayed
});
});
return { results: newData };
}
}
});
}
mostly it is done except the part of id and text parameter.
Here is how i send parameters
var selector = $('#selectParentMenu');
var url = "{{base_url()}}admin/configurations/loadAllParentFormNames/";
var id = "FormID";
var text = "FormName";
commonSelect2(selector,url,id,text);
problem is that
id: value.id, //id part present in data
text: value.text //string to be displayed
the value.id and value.text do not recognize the id and text is of parameters.
it works if i do like this
id: value.FormID, //id part present in data
text: value.FormName //string to be displayed
but if i put parameters containing these values don't work.
Your id and text parameters are strings containing the names of the properties you are trying to access in your value object. To access properties dynamically like that requires the value[id] syntax.

jQuery : update the database with all of the data from the ajax-request

am trying to update database.
For that iam doing like this
From js code
var data = {
"jobid": $('#jobid').val(),
"names": $('#names').val(),
"scripttype": $('#testscripts').val()
};
var msg="";
for(i = 1; i <=4; i++) {
data["Param" + i + "Key"] = $('#key' + i).val();
data["Param" + i + "Value"] = $('#value' + i).val();
}
$.ajax({
type: 'post',
url: "/save",
dataType: "json",
data: data
});
in node.js side
jobsCollection.update({
_id: id
}, {
$set: {
names: record.names,
script: record.scripttype,
// i dont know what should i place in this part???
// i have to set paramkey and paramValues
}
},
{
upsert: true
},
function (err, result) {
if (!err) return context.sendJson([], 404);
});
in record.names and record.scripttype getting proper values.
I don't know how to set values got from the for loop for updating
request going
Request: /save
{ jobid: '',
names: 'first',
scripttype: 'fow',
Param1Key: '1',
Param1Value: 'oneeeeee',
Param2Key: '2',
Param2Value: 'twoooooooo'
etc........
............
}
Since the property names are dynamic, you'll need to use the indexer-style property accessor of JavaScript as shown below.
Just reverse the process basically. I'm not sure where the data is located at the point you're calling update, so I called it sourceData in the example below;
// create an object with the well known-property names
var set = {
names : record.names,
script : record.scripttype
};
// now loop through the params and set each one individually
for(i = 1; i <=4; i++) {
var key = "Param" + i + "Key"; // build a key string
set[key] = sourceData[key]; // grab the data and set it
key = "Param" + i + "Value"; // and repeat
set[key] = sourceData[key];
}
then, pass it to your update:
jobsCollection.update({
_id: id
}, {
$set: set // pass the object created above
}, /* etc. */
If you don't know the count of Params, you could:
send it
use instead for .. in to loop through all the properties
For #2:
for(var key in sourceData) {
// you could filter the property names here if you'd like
// (like if only Params# were important)
set[key] = sourceData[key];
}

Jquery AJAX function - how can I use a variable for JSON?

I want to be able to supply the JSON variable name and its value via variables, instead of hard-coding it:
data: {
inputVar : inputVal
},
but doing it like that and defining
inputVar = 'myInputVar';
doesn't work, instead entering the POST variable name directly only works:
'myInputVar' : inputVal
In the end, what I'd like to accomplish is to create a function that allows me to just call it to make an AJAX call in the JSON format, by supplying the JSON formatted AJAX variable and value in the function call:
makeAjaxJsonCall(fileName, postVar, postVal) {
$.ajax({
type : 'POST',
url : fileName,
dataType : 'json',
data: {
inputVar : inputVal
},
success : function(data) {
.
.
.
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
.
.
.
}
});
}
Any ideas?
PS. I really don't know too much about JavaScript programming, so please be precise with full code when replying - thanks!
Do you want something like this?:
makeAjaxJsonCall(fileName, postVar, postVal) {
var data = {};
data[postVar] = postVal;
$.ajax({
type : 'POST',
url : fileName,
dataType : 'json',
data: data,
success : function(data) {
.
.
.
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
.
.
.
}
});
}
You can set object values like this.
var obj = {};
//This is the same as...
obj.value1 = 'one';
//This...
var varName = 'value1'
obj[varName] = 'one';
A small explanation of the last two answers:
You can define elements of an object in this way:
var myObj = {};
myObj.element = 1;
// And using a variable just like you want:
var key = 'myKey';
myObj[key] = 2;
console.log(myObj.key); // 2
So, you can build your data object first, and then pass it to the ajax hash:
// ...
var myData = {};
myData[inputVal] = 'my value';
//...
makeAjaxJsonCall(fileName, postVar, postVal) {
$.ajax({
type : 'POST',
url : fileName,
dataType : 'json',
data: myData, // <-------------
success : function(data) {
// ...
Hope this helps.
Regards.

Categories

Resources