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

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.

Related

AJAX Data with Dynamic form fields name

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.

Trying to pass values from Javascript to Java

I'm using this Javascript to send x, y values to Java from front-end (Javascript).
Sometimes this code pass the x any y values to Java and sometimes it's doesn't.After pressing the 'save' button, the function saveObjectMovingPath() will be called.
I don't know why it doesn't work sometimes! Can anyone help me to solve this issue?
<script type="text/javascript">
function saveObjectMovingPath() {
var building_Id = $("#building").val();
var floor_Id = $("#floor_level").val();
console.log('building_Id :' + building_Id + ', floor_Id : ' + floor_Id);
var json = {};
json["building_Id"] = building_Id;
json["floor_Id"] = floor_Id;
json["dataset"] = dataset;
$.ajax({
type: "post",
url: "savepath?pathConfig=" + unescape(JSON.stringify(json)),
success: function(data) {
alert("response data : " + data);
var response = JSON.parse(data);
}
});
}
</script>
This is sample data passing on URL:
"http://localhost:8080/Track/savepath?pathConfig={%22building_Id%22:%223%22,%22floor_Id%22:%2224%22,%22dataset%22:[{%22x%22:785.260498046875,%22y%22:624.4688720703125},{%22x%22:783.3544921875,%22y%22:624.4688720703125},{%22x%22:781.4485473632812,%22y%22:624.4688720703125},{%22x%22:779.5425415039062,%22y%22:624.4688720703125},{%22x%22:777.6365966796875,%22y%22:624.4688720703125},{%22x%22:775.7306518554688,%22y%22:624.4688720703125},{%22x%22:773.8246459960938,%22y%22:624.4688720703125},{%22x%22:770.9656982421875,%22y%22:624.4688720703125},{%22x%22:769.0596923828125,%22y%22:624.4688720703125},{%22x%22:767.1537475585938,%22y%22:624.4688720703125},{%22x%22:764.2947998046875,%22y%22:624.4688720703125},{%22x%22:763.341796875,%22y%22:624.4688720703125},{%22x%22:762.3887939453125,%22y%22:623.5159301757812},{%22x%22:760.4828491210938,%22y%22:623.5159301757812},{%22x%22:759.5298461914062,%22y%22:623.5159301757812},{%22x%22:757.6239013671875,%22y%22:623.5159301757812},{%22x%22:756.6708984375,%22y%22:623.5159301757812},{%22x%22:755.7178955078125,%22y%22:623.5159301757812},{%22x%22:754.7649536132812,%22y%22:623.5159301757812},{%22x%22:752.8589477539062,%22y%22:623.5159301757812},{%22x%22:751.9059448242188,%22y%22:623.5159301757812},{%22x%22:750.9530029296875,%22y%22:623.5159301757812},{%22x%22:749.0469970703125,%22y%22:623.5159301757812},{%22x%22:748.0940551757812,%22y%22:623.5159301757812},{%22x%22:747.1410522460938,%22y%22:624.4688720703125},{%22x%22:745.2350463867188,%22y%22:624.4688720703125},{%22x%22:744.2821044921875,%22y%22:625.421875},{%22x%22:743.3291015625,%22y%22:625.421875},{%22x%22:741.423095703125,%22y%22:625.421875},{%22x%22:740.4701538085938,%22y%22:626.3748779296875},{%22x%22:739.5171508789062,%22y%22:626.3748779296875},{%22x%22:738.5641479492188,%22y%22:626.3748779296875},{%22x%22:737.6112060546875,%22y%22:627.327880859375},{%22x%22:736.658203125,%22y%22:627.327880859375},{%22x%22:735.7052001953125,%22y%22:627.327880859375},{%22x%22:734.752197265625,%22y%22:627.327880859375},{%22x%22:733.7992553710938,%22y%22:628.2808227539062},{%22x%22:732.8462524414062,%22y%22:628.2808227539062}]}"
you try to send GET parameters on POST method
first you need to call the error function in your AJAX declaration and console.log it , if there is no error and the problem not resolved please check your java side (server side , maybe you try to save something need to parse ... )
second : make ajax statement look like this :
$.ajax({
type: "post",
data : {
building_Id : $("#building").val(),
floor_Id : $("#floor_level").val()
dataset: dataset;
}
url: "savepath?pathConfig=" + unescape(JSON.stringify(json)),....
....
instead of this :
var json = {};
json["building_Id"] = building_Id;
json["floor_Id"] = floor_Id;
json["dataset"] = dataset;

AJAX call within Javascript class (prototype function)

I am implementing a Javascript class which I am having trouble getting to work.
After I initialize an instance of the class, I then call a method of that class which makes an AJAX request. The data that is returned on 'success' of the AJAX function is then needed to be set to the a property of that instance. When I output the this.results variable later in my code, it is empty when it shouldn't be. Here is my code:
//Individual Member Class
function GetReports(options) {
this.options = options;
this.results = {};
}
GetReports.prototype.getResults = function() {
jQuery.ajax({
type : 'post',
dataType : 'json',
url : 'reporting/getStaffMemberReports',
async : false,
data : options,
success : function(data) {
this.results = data;
setResult(this.results);
}
});
}
GetReports.prototype.returnResults = function(type) {
if(type === "JSON") {
JSON.stringify(this.results);
} else if (type === "serialize") {
this.results.serialize();
}
return this.results;
};
GetReports.prototype.setResult = function(data) {
this.results = data;
};
And my code which creates an instance of the 'class':
var jsonString = <?php echo json_encode($JSONallocatedStaffMembers); ?>;
options = {
all : true,
members : JSON.parse(jsonString),
type : 'highperform'
};
var all = new GetReports(options);
all.getResults();
var results = all.returnResults("JSON");
console.log(results);
Now, as the AJAX call is asynchronous, I was thinking this may be the issue? I have tried putting 'async : false,' in but that doesn't help.
Can anyone see where I am going wrong?
There is one thing to be fixed here.
The this
inside ajax callback refers to ajax object, and not your
GetReport instance. You have to declare a var on getResults and point
it to this before make the ajax.
GetReports.prototype.getResults = function() {
var self = this;
jQuery.ajax({
type : 'post',
dataType : 'json',
url : 'reporting/getStaffMemberReports',
async : false,
data : options,
success : function(data) {
self.results = data;
setResult(self.results);
};
});
}

Ajax post - POST array is returning empty on server side

I have an js function that is collecting data and sending it to a php file.
I am trying to submit an array as part of the post:
function send_registration_data(){
var string = "{username : " + $('#username').val() + ", password : " + $('#pass1').val() + ", level : " + $("#userrole").val() + ", 'property[]' : [";
var c = 0;
$('input[name=property]:checked').each(function(){
if( c == 0){
string +="\"" +this.value+"\"";
c=1;
} else {
string +=",\""+this.value+"\"";
}
});
string+="]}";
$('#input').html( JSON.stringify(eval("(" + string + ")")) );
$.ajax({ url: './php/submit_registration.php',
//data: { username : $('#username').val() , password : $('#pass1').val() , email : $('#email').val() , level : $("#userrole").val() },
data: JSON.stringify(eval("(" + string + ")")) ,
type: 'post',
success: function(output) {
$('#output').html( output );
}
});
};
On submit my php file returns an the POST array as NULL. I am not sure what I am doing wrong here.
EDIT: IT is the same weather I try to convert the string to json or not.
ALso, the inputs contain just text names.
string keyword
Do not use the "string" keyword.
eval
Eval is evil - use it with caution.
strict mode
Make sure always to work in the "strict mode" by placing this line at the beginning of your code:
'use strict'
Building your response object
You do not have to glue your post object manually. Just do it this way:
var post = {
'username': $('#username').val(),
'password': $('#password').val(),
'myArray[]': ['item1', 'item2', 'item3']
};
jQuery the right way
Avoid messing up with unnecessary syntax.
$.post(url, post)
.done(function(response){
// your callback
});
Conclusion
'use strict'
var url = './php/submit_registration.php'; // try to use an absolute url
var properties = {};
$('input[name="property"]:checked').each(function() {
properties.push(this.value);
});
var data = {
'username': $('#username').val(),
'password': $('#pass1').val(),
'level': $('#userrole').val(),
'property[]': properties
};
// submitting this way
$.post(url, data)
.done(function(response) {
// continue
})
.fail(function(response) {
// handle error
});
// or this way
$.ajax({
type: 'POST',
url: url,
data: JSON.stringify(data), // you'll have to change "property[]" to "property"
contentType: "application/json",
dataType: 'json',
success: function(response) {
// continue
}
});
You need to get from php://input if you are not using multipart/form-data, so, application/json
$myData = file_get_contents('php://input');
$decoded = json_decode($myData);
If you're sending this up as json, your $_POST variable will continue to be NULL unless you do this.

AJAX/JS Syntax passing with arrays, Syntax Error

Background
I have a javascript code which passes three values dynamically into JSON for processing... After discussing a previous problem I had with a colleague, he has proposed that the best way to pass multiple variables into JSON would be to define them as an array in javascript, and then pass the object directly into the ajax/JSON. However, after a little trial and error coding, it appears the methodology is not being run correctly by the JSON processor. My question is as follows, in the following two examples, are they functionally the same, and if so, then why would the syntax fail.
Working Code
/* New Syntax: */
var data_id = $(this).data('id');
var data_action = "get";
var column_toact_on = $(this).data('column');
$.ajax({
url: 'xyz.php',
type: 'POST',
data: {id : data_id, action: data_action, column: column},
dataType: 'json',
success: function(data){
alert("Information Passed Correctly");},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus);}
});
Not Working Code
/* old Syntax: */
var dataObj = {};
dataObj["id"] = $(this).data('id');
dataObject["column"] = $(this).data('column');
dataObj["action"] = "get"; // "get" or "set"
$.ajax({
url: 'xyz.php',
type: 'POST',
data: dataObj,
dataType: 'json',
success: function(data){
alert("Information Passed Correctly");},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus);}
});
The reason your non-working code is not working..
var dataObj = {};
dataObj["id"] = $(this).data('id');
dataObject["column"] = $(this).data('column');
dataObj["action"] = "get";
You create an object, dataObj - thats fine. You assign a property on dataObject (does not exist, you mean dataObject, but the JS interpreter does not know that), which for obvious reasons wont work.
Try this instead.
var dataObj = {};
dataObj["id"] = $(this).data('id');
dataObj["column"] = $(this).data('column');
dataObj["action"] = "get";

Categories

Resources