Javascript: Passing dynamic data name attribute in Ajax - javascript

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;

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.

Passing array to ajax

How I can pass a list or array to ajax?
var intArray = [];
$.ajax({
url: '/User/GetGroup',
type: 'GET',
data: intArray,
traditional: true,
success: function (result) {
$(result).each(function () {
var id = this.Id;
var nome = this.Nome;
$("#Default").append($('<option></option>').val(id).html(nome));
});
}
});
Like this way, still doesn't work.
Thanks!
You can pass the array like that, or use data: JSON.stringify(intArray). In ASP.NET MVC, we use the JSON 2 javascript library, available in a Nuget package.
success: function (serverResult) {
// create an object array from json string.
var results = JSON.parse(serverResult);
for ( var item in results){
$("#Default").append($('<option></option>').val(item.Id).html(item.Nome));
}
}
I used data: { i: intArray }, and works too!

Ajax in JavaScript sends only the last data in array

I want to send data from my application with json ajax in JavaScript. I have more than one packet of data, but when I send my data through ajax it only sends the last data packet.
For example, I send two data packets, then ajax sends two data packets but they both contain the same data(the last data packet).
Here is my code.
for(var i=0;i<data.length;) {
/*var d = new Date();
d.setTime(data[i].updated);*/
var send2 = {};
send2.nama= data[i].name;
send2.rumahsakit = data[i].hospital;
//step 1
alert("step 1"+send2.nama);
var client = "coba";
var Idku = data[i].unik;
//clientID
var request2 = {};
request2.jsonrpc = "2.0";
request2.id = "load_reg"+Idku+"";
request2.method = "registrasi:loadByClientUnik";
request2.params = [client,Idku];
//request2.params = akun.value;
var postData = JSON.stringify(request2);
var postArray = {json:postData};
$.ajax({
type: 'POST',
url: 'service.php',
data: postArray,
dataType:'json',
//async: false,
success: function(result){
alert(send2.nama);
//alert step 2;
if(result.result == -1){
//alert("-1 cuk");
var requestx = {};
requestx.jsonrpc = "2.0";
requestx.id = "store_reg";
requestx.method = "registrasi:store";
requestx.params = [send];
var postDatax = JSON.stringify(requestx);
var postArrayx = {json:postDatax};
$.ajax({
type: 'POST',
url: '/service.php',
data: postArrayx,
dataType:'json',
//async: false,
success: function(result){
//alert("sukses");
},
error: function(e){
console.log(e);
alert(e);
} });
}else{
alert(send2.nama);
var request = {};
request.jsonrpc = "2.0";
request.id = "store_reg";
request.method = "registrasi:storeById";
request.params = [result.result,send2];
var postData2 = JSON.stringify(request);
var postArray2 = {json:postData2};
$.ajax({
type: 'POST',
url: '/service.php',
data: postArray2,
dataType:'json',
//async: false,
success: function(result){
//send2 = "";
//alert("sukses ID");
},
error: function(e){
console.log(e);
alert(e);
}
});
}
},
error: function(e){
console.log(e);
alert(e);
}
});
//return false;
i++;
}
getData();
}
Example behavior: I send 2 data packets, 1st has name = 1 and the 2nd has name = 2, then I send both packets:
output :
alert step 1 print 1
alert step 1 print 2
alert step 2 print 2
alert step 2 print 2
I want this output :
alert step 1 print 1
alert step 2 print 1
alert step 1 print 2
alert step 2 print 2
}else{
alert(send2.nama);
var request = {};
request.jsonrpc = "2.0";
request.id = "store_reg";
request.method = "registrasi:storeById";
request.params = [result.result,send2];
var postData2 = JSON.stringify(request);
var postArray2 = {json:postData2};
$.ajax({
type: 'POST',
url: 'http://10.126.14.116/portable_med_services/service.php',
data: postArray2,
dataType:'json',
//context set
context: { send2: send2 },
//async: false,
success: function(result){
//send2 = "";
//alert("sukses ID");
},
error: function(e){
console.log(e);
alert(e);
}
});
This is my updated code with adding context...am I right??
update :
I already fixed this issue following this issue... jQuery ajax inside a loop problem
Your code actually sends both requests one after another (step 1), in order, like you probably want it to.
You get the first debug output due to the asynchronous nature of $.ajax() calls. They send the request and continue with the code execution-- they don't block and they don't wait for the response from the server. That's why your outer/main for loop executes all the way to the end (2 times in your case) before any response is received and the code inside the success callbacks is executed.
When the 2 responses are received, the success callbacks are executed (2 times, once for each response), however at that point in time your local variable send2.nama has the value of "2". That's why you get the output "step 2 print 2" twice, instead of "step 2 print 1" and "step 2 print 2".
This will likely also be the error cause for other requests that you make from inside the success callbacks, since you are using local variables inside the callbacks. You should be using the context parameter instead:
$.ajax({
// ...
context: { send2: send2 },
success: function (result) {
// "this" has the value of the context object
alert(this.send2.nama);
// ...
}
});
I am not sure if your intention is really to send the 2nd request only after the 1st response is already received, but if it is, then you will have to refactor the code a bit and send the 2nd request from a function invoked from inside the success callback of the 1st request.

How to pass the value to URL from dropdown item?

I am asking this question again....because I am not getting correct answer...
answers which I get is incorrect.
I am developing MVC application and I am using razor syntax. I am trying to get the selected item from dropdown list value and to pass it to the controller method.
but I am getting error.
$("#btnForword").click(function(){
d = document.getElementById("HODList").value;
var url2 = "#Html.Raw(Url.Action("SendPaymentAdviceForApproval", "PaymentAdvice", new { paymentAdviceId = "idValue" , nHOD = "d" }))";
url2 = url2.replace("idValue",'#Model.Id');
url2 = url2.replace("d",'#d');
$.ajax({
url: url2, type: "POST", success: function (data) {
$("#btnForword").css("display","none");
}
});
return false;
});
I think error in this line...
url2 = url2.replace("d",'#d');
Issue solved Issue solved
The problem in variable 'D' yes in "D".
I checked using inspect element property of Google chrome, when I saw it in console window....
When I click on the button , I can see the string formed in below way
http://localhost:54255/PaymentAdvice/SendPaymentAdviceForApproval?paymentAdviceId=304&nHO8=D
jquery-1.7.1.min.js:4
see the last character in the above link, it should not be come as a "=D" isnt it ?
I used the below code...and it works perfectly.
$("#btnForword").click(function(){
var url2 = "#Html.Raw(Url.Action("SendPaymentAdviceForApproval", "PaymentAdvice", new { paymentAdviceId = "idValue" , nHOD = "HODId" }))";
url2 = url2.replace("idValue",'#Model.Id');
url2 = url2.replace("HODId",$('#HODList').val());
$.ajax({
url: url2, type: "POST", success: function (data) {
$("#btnForword").css("display","none");
}
});
return false;
});
Is this a bug in Jquery ?
Your variable d is not a server variable that can be called with "#" but a client variable set in javascript, so it should be user like :
$("#btnForword").click(function(){
d = document.getElementById("HODList").value;
var url2 = "#Html.Raw(Url.Action("SendPaymentAdviceForApproval", "PaymentAdvice", new { paymentAdviceId = Model.Id , nHOD = "d" }))";
url2 = url2.replace("d",d);
$.ajax({
url: url2, type: "POST", success: function (data) {
$("#btnForword").css("display","none");
}
});
return false;
});
(and the "#Model.Id" can be called directly in the Url.Action method).
Yes it is. The problem is that the js replace function replaces every "d" character contained in the url2 string with your #d variable!!!
You need to replace the "d" identifier with something that does not appear twice (or more) in the url string. Besides, I think is better if you create the url directly using javascript and not the Razor helper. You can do this in one line of code instead of three. Regards.

JavaScript auto-incrementing a variable in jQuery and AJAX

I have JavaScript using jQuery and AJAX which creates a dynamic array, which has some values used for AJAX request as below;
<script type="text/javascript">
var array = Array("y","y","x","y","y","y");
function updateBackground(cellId, titleId) {
var i = 0;
$.ajax({
type: "POST",
url: "ajax.php",
data: {
filename: Array(array[i], "testdata", $("#"+titleId).html())
},
success: function(response){
$("#"+cellId).css("background-image", "url('pdfthumb/" + response + "')");
}
});
i++;
}
</script>
The script is suppose to submit values in the array in array[i] for each AJAX request. I made a variable var i which auto increments.. But the script is not working.. The script works well if array[i] is replaced by array[0] or array[1] etc..
How can I solve the syntax error?
Every time you call updateBackground() i = 0 (again). May be you must initialize i outside of the function.
What happens if i > array.length? And I would rename the variable.
You don't have an iterator. Your variable i gets set to 0 every time the function runs. The increment at the end is useless.
Maybe you need something like this?
var array = Array("y","y","x","y","y","y");
function updateBackground(cellId, titleId) {
for( var i = 0; i < array.length; i++ ) {
$.ajax({
type: "POST",
url: "ajax.php",
data: {
filename: Array(array[i], "<?php echo $dir; ?>", $("#"+titleId).html())
},
success: function(response){
$("#"+cellId).css("background-image", "url('pdfthumb/" + response + "')");
}
});
}
}
Each time you call updateBackground() function, the i variable is being reinitialized. It's just a local variable and as soon as the function finishes it's being destroyed by GC. You could do something like this:
var UpdateBackground = {
array: [..],
counter: 0,
doUpdate: function(cellId, titleId) {
// AJAX request
this.counter++;
}
};
UpdateBackground.doUpdate(1, 1);
UpdateBackground.doUpdate(1, 1);
I think that you should send the whole array maybe as a commaseparated string and instead and make just one ajax request, because http-requests are expensive and change the server side code accordingly. And fetch the cellids as an array.
If you think that you have a long list or a table it can be like a lot of requests. Do the stuff in client code and do the stuff in server code and keep the number of http-requests as few as possible.
And use the join method on the array.
var arr = [ 'y', 'y' ];
arr.join(',');
// outputs y, y
I fixed it... Thank you so much #Jed, #Pointy, #Crozin, and #Lord Vader for helping me to figure it out.... :)
I just take var i = 0; outside the loop.... above var array like;
var i = 0;
var array = Array("y","y","x","y","y","x");

Categories

Resources