Add parameter in Ajax call if a conditions is true - javascript

Here is my previous code:
$.ajax({
type: "POST",
url: "/Test/Save",
data: {
comments: $('#comments').val()
<% if (SomeCondition) { %>,
profit: parseInt(profitCombo.getSelectedValue())
<% } %>,
myData: JSON.stringify(someData).toString()
}
...
Now, I placed this code in a separate JS file and I need to remove the ASPX call. I have a variable someConditionJsVariable, so I want to make something like this:
data: {
comments: $('#comments').val()
if (someConditionJsVariable) {,
profit: parseInt(profitCombo.getSelectedValue())
},
myData: JSON.stringify(someData).toString()
}
If that variable is true, add a comma and another parameter. how to make this?

You can update code to following
// create object
var data = {
comments: $('#comments').val(),
myData: JSON.stringify(someData).toString()
}
if (someConditionJsVariable) {,
data.profit = parseInt(profitCombo.getSelectedValue());
}
data : data // pass object

Just build your object before, using a function:
$.ajax({
type: "POST",
url: "/Test/Save",
data: getMyDataObject()
//other settings
});
function getMyDataObject() {
var myDataObject = {
comments: $('#comments').val()
myData: JSON.stringify(someData).toString()
}
if (someConditionJsVariable) {
myDataObject.profit= parseInt(profitCombo.getSelectedValue());
}
return myDataObject;
}

You could wrap all of the logic into a function like so:
var testSave = function(someConditionJsVariable, someData, profitCombo) {
// construct your data object
var data = {
comments: $('#comments').val(),
myData: JSON.stringify(someData),
}
// assign the conditional property with value depending on condition
!!someConditionJsVariable && (data.profit = parseInt(profitCombo.getSelectedValue()));
// return the jQuery promise from ajax call
return $.ajax({
type: "POST",
url: "/Test/Save",
data: data
});
}
And then use the function like this:
testSave(someConditionJsVariable, someData, profitCombo)
.then(function(result) {
// do something with result
});

Related

Reuse the same AJAX calls

I have a couple of ajax requests to urls that are very similar, but are supposed to do different things with the responses at different points. So instead of writing a new ajax call every time I need it, I am trying to reuse the ajax calls as a function with parameters:
function createAjaxObj(type,name,id,successFunc){
var config = {
url: MY_URL,
type: type,
data: {
name : name,
id : id,
},
headers: { "X-CSRFToken": returnCsrfToken(); },
success: successFunc,
error: function(xhr,ajaxOptions, thrownError) { console.log('error=',xhr);},
};
$.ajax(config);
}
So now, I am planning on calling this function every time I need it like that:
var myFunc = function(context){console.log(context)}
createAjaxObj("GET","MyName",58,myFunc)
I was wondering if this is a good idea or common practice or is there an easier way to achieve this?
I would do it in a Promise way:
function myAjax(type, name, id) {
return $.ajax({
url: MY_URL,
type: type,
data: {
name : name,
id : id,
},
headers: { "X-CSRFToken": returnCsrfToken(); })
})
.fail(function(){
console.log('error');
});
}
var myFunc = function(context){ console.log(context); };
myAjax("GET", "MyName", 58).then(myFunc);
You can make it a promise, if what you're doing with the response changes:
function createAjaxObj(type,name,id,successFunc){
return $.ajax({
url: MY_URL,
type: type,
data: {
name: name,
id: id
}
})
}
now you can run it like so:
createAjaxObj('foo', 'bar', 1)
.then(function(data) { // do something with data })
.error(function(err) { // do something with error })
I think that should work for you. Let me know if not, I'll create a fiddle for it.

Ajax POST don't work after button click

My problem is lack of action after pressing the button. Under the button hook AJAX function.
Please a hint where I have a bug // errors.
My code:
Controller:
[HttpPost]
public ActionResult InsertCodesToDB(string name)
{
cl.InsertCodesToDB(name);
fl.MoveCodeFileToAccept(name);
string response = "Test";
return Content(response, "application/json");
}
View / Button:
<input type="button" class="btn btn-success sendCodesToDB" value="Umieść kody w bazie" data-value="#item.Name"/>
View / Script:
<script>
$('.sendCodesToDB').on('click', function () {
var name = $(this).data("value");
$.ajax({
url: '/ActualCodes/InsertCodesToDB',
type: 'POST',
dataType: 'json',
cache: false,
data: JSON.stringify({ 'name': 'name' }),
success: function (response) {
#(ViewBag.MessageOK) = response;
},
error: function () {
onBegin;
}
});
});
function onBegin() {
$('#files').hide();
$('#insertFiles').hide();
$('#loading').show();
$('#lblSelectedProductName').text('Trwa umieszczanie kodów w bazie danych. Proszę czekać ...');
$('#ttt').show();
}
</script>
Thank you in advance for your help.
You seem to not be adding the on ready function for jQuery. Try adding it before your click action and closing it before your onBegin() function, like so:
<script>
// open here
$( document ).ready(function() {
$('.sendCodesToDB').on('click', function () {
var name = $(this).data("value");
$.ajax({
url: '/ActualCodes/InsertCodesToDB',
type: 'POST',
dataType: 'json',
cache: false,
data: JSON.stringify({ 'name': 'name' }),
success: function (response) {
#(ViewBag.MessageOK) = response;
},
error: function () {
// function call missing "()"
onBegin();
}
});
});
// and close here
});
function onBegin() {
$('#files').hide();
$('#insertFiles').hide();
$('#loading').show();
$('#lblSelectedProductName').text('Trwa umieszczanie kodów w bazie danych. Proszę czekać ...');
$('#ttt').show();
}
</script>
The code in Ajax must be JavaScript. You cannot use C# code there (except to print some values). What is #(ViewBag.MessageOK) doing here:
success: function (response) {
#(ViewBag.MessageOK) = response;
},
If you want to display the response in a message box, try something like:
success: function (response) {
$("#your_message_id").html(response);
},
Notes: aside from that, you have several errors in your code as others pointed out in the comments.
1- Remove the quotes from the data like this:
data: JSON.stringify({ name: name }),
2- Change the error to this:
error: function () {
onBegin(); // You need "()" here
}
Or better this:
error: onBegin // You don't need "()" here
I guess you are sending data inside the AJAX call in the wrong way.
Try it like this
data: JSON.stringify({ name: name })
Hope this will help you.

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.

jQuery: Mixing Strings and List of Javascript Objects in JSON

What I'm trying to do is possibly quite simple, however beeing not very familiar with jQuery I can't figure out how to do it.
I want to send some Data as JSON to an ASP.NET Controller. The Data contains some Strings and a list of Objects.
The Code would look somewhat like this:
View:
$(document).ready(function () {
var stuff = [
{ id: 1, option: 'someOption' },
{ id: 2, option: 'someOther' },
{ id: 3, option: 'anotherOne' }
];
things = JSON.stringify({ 'things': things });
var dataRow = {
'String1': 'A String',
'String2': 'AnotherOne'
}
dataRow = JSON.stringify(dataRow);
var sendData = dataRow + things;
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Backend/DoStuffWithStuff',
data: sendData,
success: function () {
alert('Success!');
},
failure: function (response) {
alert('Fail! :(');
}
});
});
Controller:
public class Stuff
{
public int id { get; set; }
public string option{ get; set; }
}
public void DoStuffWithStuff(string String1, String2, List<Thing> things)
{
//Do my Stuff
}
Any Ideas would be great! :)
You do not need to stringify the json data.
You just create an object you van to send and than
var jsonObject = {
'string' : 'string',
'object' : {
'stirng': 'string'
}
};
$.ajax({type: "POST", url: DotNetScript, data: jsonObject})
.done(function(dataBack){
//what to do with data back
});
It actually doesn't look too bad so far! Just a few things...
[HttpPost]
public void DoStuffWithStuff(string String1, String2, List<Stuff> things)
{
//Do my Stuff
}
In here, you don't actually give a type to string2. I'm going to assume this is a typo, but that's the minor part here.
Also, in that method, notice it has the HttpPost on the top. In your javascript here:
$.ajax({
...
type: 'POST',
...
});
You specify POST, so you must make the method support post (You could also get away with GET in this case by changing type to GET, then removing the attribute, but i'm not sure what your "stuff" entails...)
var stuff = [
{ id: 1, option: 'someOption' },
{ id: 2, option: 'someOther' },
{ id: 3, option: 'anotherOne' }
];
things = JSON.stringify({ 'things': things });
var dataRow = {
'String1': 'A String',
'String2': 'AnotherOne'
}
dataRow = JSON.stringify(dataRow);
var sendData = dataRow + things;
You didn't actually pass stuff into your method, which may be helpful...
Here is the ajax method re-written with the proper JSON pass (for what you're trying to do here).
$(document).ready(function () {
var stuff = [
{ id: 1, option: 'someOption' },
{ id: 2, option: 'someOther' },
{ id: 3, option: 'anotherOne' }
];
var dataRow = {
String1: 'A String',
String2: 'AnotherOne'
things: stuff
}
$.ajax({
dataType: 'json',
type: 'POST',
url: '/Backend/DoStuffWithStuff',
data: sendData,
success: function () {
alert('Success!');
},
failure: function (response) {
alert('Fail! :(');
}
});
});

Knockout.js Observable Array with onlick event

Hi I have a web application, I'm very new to KnockOut.js
I have my JS COde
ko.applyBindings(new LOBViewModel());
//COMMENTED SECTION BINDS THE DATA TO HTML, BUT DOES NOT TRIGGER ONLICK EVENT
//function LOBViewModel() {
// var self = this;
// self.vm = {
// LOBModel: ko.observableArray()
// };
// GetLOB();
//
// self.DeleteRecord = function (lobmodel) {
// $.ajax({
// type: "POST",
// url: '/Admin/DeleteLOB',
// data : {LOB_ID : lobmodel.LOB_ID},
// success: function (data)
// {
// alert("Record Deleted Successfully");
// GetLOB();//Refresh the Table
// },
// error: function (error)
// {
// }
// });
// };
// function GetLOB() {
// $.ajax({
// url: '/Admin/GetLOB',
// type: "POST",
// dataType: "json",
// success: function (returndata) {
// self.vm.LOBModel = returndata;
// ko.applyBindings(self.vm);
// alert("Hello");
// },
// error: function () {
// }
// });
// };
//}
//UNCOMMENTED SECTION DOES NOT BIND THE DATA TO HTML
function LOBViewModel() {
var self = this;
self.LOBModel = ko.observableArray([]);
GetLOB();
self.DeleteRecord = function (lobmodel) {
$.ajax({
type: "POST",
url: '/Admin/DeleteLOB',
data: { LOB_ID: lobmodel.LOB_ID },
success: function (data) {
alert("Record Deleted Successfully");
GetLOB();//Refresh the Table
},
error: function (error) {
}
});
};
function GetLOB() {
$.ajax({
url: '/Admin/GetLOB',
type: "POST",
dataType: "json",
success: function (returndata) {
self.LOBModel = returndata;
alert(self.LOBModel.length);
},
error: function () {
alert("eRROR GET LOB");
}
});
};
}
Details
My Json is in the following format
[0] = > { LOB_ID : 0 , LOB_Name : "data" LOB_description : "data" }
[1] => and so on
HTML File
<tbody data-bind="foreach: LOBModel">
<tr>
<td data-bind="text:LOB_ID"></td>
<td data-bind="text: LOB_Name"></td>
<td data-bind="text: LOB_Description"></td>
<td><button data-bind="click: $root.DeleteRec">Delete</button></td>
</tr>
</tbody>
My Question is
why is that
i have to use vm to bind the json into LOADModel so that it works, when i use self.LOBModel = ko.observableArray([]); the binding does not happen. i.e, my table does not load the data.
my Onlick does not get triggered in both the version of the code, I've tried self.DeleteRec, $root.DeleteRec and just DeleteRec as well. Though seems very obvious it just doesnot work.
Would the DeleteRec know which record i'm deleting. is lobmodel.LOB_ID correct way to use ?
To answer point by point:
(1) Your problem is in the GetLOB function, on this line:
self.LOBModel = returndata;
By doing that, you overwrite the self.LOBModel = ko.observableArray([]). What you should do instead is this:
self.LOBModel(returndata);
Then you should see the data in your table (if you have no other errors). The thing to remember here, is that if you make a variable observable, you always need to use the ()-syntax to read or write the underlying value. If you use = instead, you erase the observable functionality.
(2) the approach with '$root.DeleteRecord' is correct. 'self.DeleteRecord' would not work, and neither would just DeleteRecord. What would also work is '$parent.DeleteRecord'. The problem seems to be that you do 'DeleteRec' instead of 'DeleteRecord'.
(3) your approach is the right one. Deleted my others comments on this point, since Richard Dalton below me made a correct comment that invalidates what I typed here.
Edit: working Fiddle
http://jsfiddle.net/LFgUu/4/

Categories

Resources