Make Array in Jquery For AJAX Posting - jquery-ui

$('#saveplaylist').click(function () {
var length = $(' .organizer-media').length;
var contents=$(' .organizer-media');
var data = null;
for (var i = 0; i < length; i++) {
data[i] = contents[i].title;
}
$.ajax({
type: 'POST',
data: JSON.stringify(data),
url: '/Builder/Save',
success: function () {
alert("Playlist saved successfully!!");
}
})
})
As shown above in my code I am not able to send my values by making an array of data filled by using for loop How can I make an array of data & post it through AJAX?

You have to initialize the variable as an array, not null.
var data = [];

In addition to what Barmar said, you need to set content type of your ajax call to JSON
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
url: '/Builder/Save',
success: function () {
alert("Playlist saved successfully!!");
}
})

Remove space from ' .organizer-media' and ' .organizer-media'
and change
var data = null;
to
var data = new Array();

Instead of JSON.stringify() you could use the $.param() method
$('#saveplaylist').click(function () {
var length = $(' .organizer-media').length;
var contents=$(' .organizer-media');
var data = null;
for (var i = 0; i < length; i++) {
data[i] = contents[i].title;
}
$.ajax({
type: 'POST',
data: $.param({data: data}),
url: '/Builder/Save',
success: function () {
alert("Playlist saved successfully!!");
}
});
});
This will store the content titles as members of the data array, which you should be able to access server side.
In Rails you would access this like so:
titles = params[:data]
In PHP it might be something like:
$titles = $_POST["data"];
EDIT:
One thing I missed, as Barmar mentioned above, you need to initialize data as an empty array, not null.

Related

How to save data into smart table in UI5?

I have a smart table which has editable fields, I want to save these multiple records in the backend. How should I achieve this?
oModel.create("/Set", [{obj1}, {obj2}])
oModel.createBatchOperation("/set", "POST" , obj1)
oModel.createKey("set" , obj)
oModel.submitChanges()
All of them
use batch call, giving
same error -- 400 -- XML parse error.
If you are using sap.ui.model.odata.v2.ODataModel use below code
var oModel = this.getView().getModel();//gets the v2 odata model
oModel.setUseBatch(true);//setting batch true if not already set
var jModel = oTable.getModel("jTabModel").getProperty("/Carriers");
for (var i = 0; i < jModel.length; i++) {
var oEntry = jModel[i];
oModel.create("/FlightSet", oEntry, {
method: "POST",
success: function(data) {
},
error: function(e) {
}
});
}
oModel.submitChanges({
success: function(data, response) {
//To do
},
error: function(e) {
//To do
}
});

Why JSON not works when i put a single quotation on my input parameter?

i want to send data to server it works fine but today i found if my user put a single quotation on data entry it will not works and i trace by codes and understood the trace will not go to my action not at all and it do not gives me an error or somethings like this
my codes:
// this code will not works because has a single quotation on mydata parameter
var mydata="I'm a developer";
var inputParams = "{abc: '" + mydata + "'}";
fra = $.ajax({
url: "/Updateit",
type: 'POST',
dataType: 'json',
data: inputParams,
contentType: 'application/json; charset=utf-8',
success: function (msg) {
......
},
error: function (msg) {
......
}
});
You need to do
var mydata = "I'm a developer";
inputParams = { abc: mydata };
$.ajax({
....
data: JSON.stringify(inputParams),
...

Ajax not allowing View rendering

I have a couple of variations on the ajax depending on the flow of interactions on the page. But it's only the variables that changes. here is one of them:
$('#btn_skickaEnkel').bind('click', function () {
$.ajax({
type: 'POST',
url: '/Contact/IntresseAnmälan/',
dataType: 'json',
data: {
Namn: $('#namn').val(),
Mail: $('#mail').val(),
Info: $('#meddelande').val(),
Nivå: $('#nivå').find(":selected").text(),
IsEnkel: true,
Telefon: $('#nr').val(),
ID: function () {
var url = window.location.pathname;
var id = url.substring(url.lastIndexOf('/') + 1);
return id;
}
},
traditional: true
});
});
In my controller i am unable to redirect or return a different view. At this point the data from JSON is no longer relevant because it's already been saved to DB.
My Controller:
public ActionResult IntresseAnmälan(BokningContainer bokning)
{
db = new DbContext();
//Saving some data to database(removed)
//Just determening the state of container obj.
if (bokning.IsEnkel)
{
//Geting som information from db (removed)
//Creating a mail (removed)
email.Send(bokning.Namn, bokning.Mail, body);
}
else
{
}
//db.SaveChanges();
//This part is not working, I think it's beacuase of the Ajax
return View("IntresseAnmälan");
}
The view is not rendered and I think it's related to the ajax. The view is simply not rendered. Is there some way to force returning it and ignoring the ajax? As I said the data is no longer needed because the content is already saved to the DB.
You cannot render view on ajax call,simply you can use form post method or just redirect it to desired action on "succcess" of ajax call as below:
$('#btn_skickaEnkel').bind('click', function () {
$.ajax({
type: 'POST',
url: '/Contact/IntresseAnmälan/',
dataType: 'json',
data: {
Namn: $('#namn').val(),
Mail: $('#mail').val(),
Info: $('#meddelande').val(),
Nivå: $('#nivå').find(":selected").text(),
IsEnkel: true,
Telefon: $('#nr').val(),
ID: function () {
var url = window.location.pathname;
var id = url.substring(url.lastIndexOf('/') + 1);
return id;
}
},
traditional: true,
success: function(result) {
window.location.href = '#Url.Action("action", "Controller")';
}
});
});
I couldn't believe my eyes when I figured out this "Bugg". The problem was that I, at some point, changed the submit to a button. So the form was never submiting. Well, at least I learnt a bit about views and Ajax.
Sorry for taking your time.

Issue with sending array to action method

I want to send array to my action method:
var items = { 'myIdList[]': [] };
$(':checkbox').change(function () {
$(":checked").each(function () {
items['myIdList[]'].push($(this).val());
});
$('#locationsCheckList').submit();
});
$('#locationsCheckList').submit(function () {
$.ajax({
url: this.action,
type: this.method,
traditional: true,
data: { "myIdList": items }...
Action method:
[HttpPost]
public void GetLocations(int[] myIdList)...
items variable have data but when I pass it like this I get null but if I change
data: { "myIdList": items }
with
data: { "myIdList": [1,2,3,4,5] }
it works.
When I debug in browser in items variable I have values:
0: "1"
1: "2"
2: "3"
I can't pass array and I don't know why, if it works hardcoded?
What if you use a simple array, similar to your example that works:
var items = [];
// your jQuery loop
items.push($(this).val());
// and so on
data: { "myIdList": items }...
Your AJAX call needs to include:
dataType: "json",

Sending String Data to MVC Controller using jQuery $.ajax() and $.post()

There's got to be something I'm missing. I've tried using $.ajax() and $.post() to send a string to my ASP.NET MVC Controller, and while the Controller is being reached, the string is null when it gets there. So here is the post method I tried:
$.post("/Journal/SaveEntry", JSONstring);
And here is the ajax method I tried:
$.ajax({
url: "/Journal/SaveEntry",
type: "POST",
data: JSONstring
});
Here is my Controller:
public void SaveEntry(string data)
{
string somethingElse = data;
}
For background, I serialized a JSON object using JSON.stringify(), and this has been successful. I'm trying to send it to my Controller to Deserialize() it. But as I said, the string is arriving as null each time. Any ideas?
Thanks very much.
UPDATE: It was answered that my problem was that I was not using a key/value pair as a parameter to $.post(). So I tried this, but the string still arrived at the Controller as null:
$.post("/Journal/SaveEntry", { "jsonData": JSONstring });
Answered. I did not have the variable names set correctly after my first Update. I changed the variable name in the Controller to jsonData, so my new Controller header looks like:
public void SaveEntry(string jsonData)
and my post action in JS looks like:
$.post("/Journal/SaveEntry", { jsonData: JSONstring });
JSONstring is a "stringified" (or "serialized") JSON object that I serialized by using the JSON plugin offered at json.org. So:
JSONstring = JSON.stringify(journalEntry); // journalEntry is my JSON object
So the variable names in the $.post, and in the Controller method need to be the same name, or nothing will work. Good to know. Thanks for the answers.
Final Answer:
It seems that the variable names were not lining up in his post as i suggested in a comment after sorting out the data formatting issues (assuming that was also an issue.
Actually, make sure youre using the
right key name that your serverside
code is looking for as well as per
Olek's example - ie. if youre code is
looking for the variable data then you
need to use data as your key. –
prodigitalson 6 hours ago
#prodigitalson, that worked. The
variable names weren't lining up. Will
you post a second answer so I can
accept it? Thanks. – Mega Matt 6 hours
ago
So he needed to use a key/value pair, and make sure he was grabbing the right variable from the request on the server side.
the data argument has to be key value pair
$.post("/Journal/SaveEntry", {"JSONString": JSONstring});
It seems dataType is missed. You may also set contentType just in case. Would you try this version?
$.ajax({
url: '/Journal/SaveEntry',
type: 'POST',
data: JSONstring,
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
Cheers.
Thanks for answer this solve my nightmare.
My grid
..
.Selectable()
.ClientEvents(events => events.OnRowSelected("onRowSelected"))
.Render();
<script type="text/javascript">
function onRowSelected(e) {
id = e.row.cells[0].innerHTML;
$.post("/<b>MyController</b>/GridSelectionCommand", { "id": id});
}
</script>
my controller
public ActionResult GridSelectionCommand(string id)
{
//Here i do what ever i need to do
}
The Way is here.
If you want specify
dataType: 'json'
Then use,
$('#ddlIssueType').change(function () {
var dataResponse = { itemTypeId: $('#ddlItemType').val(), transactionType: this.value };
$.ajax({
type: 'POST',
url: '#Url.Action("StoreLocationList", "../InventoryDailyTransaction")',
data: { 'itemTypeId': $('#ddlItemType').val(), 'transactionType': this.value },
dataType: 'json',
cache: false,
success: function (data) {
$('#ddlStoreLocation').get(0).options.length = 0;
$('#ddlStoreLocation').get(0).options[0] = new Option('--Select--', '');
$.map(data, function (item) {
$('#ddlStoreLocation').get(0).options[$('#ddlStoreLocation').get(0).options.length] = new Option(item.Display, item.Value);
});
},
error: function () {
alert("Connection Failed. Please Try Again");
}
});
If you do not specify
dataType: 'json'
Then use
$('#ddlItemType').change(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("IssueTypeList", "SalesDept")',
data: { itemTypeId: this.value },
cache: false,
success: function (data) {
$('#ddlIssueType').get(0).options.length = 0;
$('#ddlIssueType').get(0).options[0] = new Option('--Select--', '');
$.map(data, function (item) {
$('#ddlIssueType').get(0).options[$('#ddlIssueType').get(0).options.length] = new Option(item.Display, item.Value);
});
},
error: function () {
alert("Connection Failed. Please Try Again");
}
});
If you want specify
dataType: 'json' and contentType: 'application/json; charset=utf-8'
Then Use
$.ajax({
type: 'POST',
url: '#Url.Action("LoadAvailableSerialForItem", "../InventoryDailyTransaction")',
data: "{'itemCode':'" + itemCode + "','storeLocation':'" + storeLocation + "'}",
contentType: "application/json; charset=utf-8",
dataType: 'json',
cache: false,
success: function (data) {
$('#ddlAvailAbleItemSerials').get(0).options.length = 0;
$('#ddlAvailAbleItemSerials').get(0).options[0] = new Option('--Select--', '');
$.map(data, function (item) {
$('#ddlAvailAbleItemSerials').get(0).options[$('#ddlAvailAbleItemSerials').get(0).options.length] = new Option(item.Display, item.Value);
});
},
error: function () {
alert("Connection Failed. Please Try Again.");
}
});
If you still can't get it to work, try checking the page URL you are calling the $.post from.
In my case I was calling this method from localhost:61965/Example and my code was:
$.post('Api/Example/New', { jsonData: jsonData });
Firefox sent this request to localhost:61965/Example/Api/Example/New, which is why my request didn't work.

Resources