How to make can.Model send JSON data when update? - javascript

I have this code:
var SotriesModel = can.Model.extend({
findAll: 'GET /api/stories/',
create: function(story) {
console.log(story)
return $.ajax({
url: '/api/stories/',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(story)
});
},
update : function(story) {
console.log(story)
return $.ajax({
url: '/api/stories/',
type: 'PUT',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(story)
});
},
destroy: 'DELETE /api/stories/{id}'
}, {});
var story = new SotriesModel({id:123123, name:"test"});
story.save();
What I expect from save is a PUT request with a JSON in payload, but what I get is just the id number:
123123

The update method signature for using a function is can.Model.update: function(id, serialized) -> can.Deffered.
So as the first parameter you always get the id and as the second the serialized data.
Changing your update : function(story) {} to update : function(id, story) {} should solve the problem.

Related

How to send #RequestParam in AJAX POST request

I have my API which accepts Request Param:
#PostMapping(value = "/export")
#ResponseBody
public ResponseEntity<String> bulkExport(
#RequestParam(value = "managedObjects", required = false) List<String> managedObjects) {
//data
}
);
I want to send AJAX POST request.
$.ajax({
type: "POST",
//url: "policy/js_policy",
url: "/export/ ,
async: false,
data: { "managedObjects": ["Audit","Logs"]},
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function (XMLHttpRequest, textStatus) {
//File Handling
}
});
I tried to send managedObjects in URL. In data also I am sending the same.But my API is not working. How to send the #RequestParam from AJAX POST request exactly?
pass a list in Query Param
$.ajax({
...
url: "/export?managedObjects=Audit,Logs" ,
...
});
pass a list in Request Body
$.ajax({
type: "POST",
url: "/export/",
...
data: {managedObjects[0]: "Audit",
managedObjects[1]: "Logs"}
...
});
Try stringifying your data:
var data = {
managedObjects: ["Audit", "Logs"]
}
$.ajax({
type: "POST",
url: "/export/",
async: false,
data: JSON.Stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function (XMLHttpRequest, textStatus) {
}
});
Additionally you should use "name" instead "value" in #RequestParam:
#PostMapping(value = "/export")
#ResponseBody
public ResponseEntity<String> bulkExport(
#RequestParam(name = "managedObjects", required = false) List<String> managedObjects) {
//data
}
);
I think the problem is just with list that you want to send in your request.
var dataToSend = {
list: [{ fieldname: 'ABC' }, { fieldname: 'DEF' }]; // your list should something like this.
$.ajax({
type: "POST",
//url: "policy/js_policy",
url: "/export/?managedObjects=" + Mos ,
async: false,
data: JSON.stringify(dataToSend),
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function (XMLHttpRequest, textStatus) {
}
});

Model is not attaching with controller in MVC using Ajax call?

I am trying to pass the model from view to controller using ajax AND when I check the value in the JS debugger model has data but it's not binding with controller and the controller model is showing null.
function BulkUpdate()
{
debugger;
var model = #Html.Raw(Json.Encode(Model.tags))
$.ajax({
type: 'GET', //GET
data: JSON.stringify({model}),
url: '#Url.Action("BulkUpdate", "Home")',
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
$('#myModalContent').html(data);
$('#myModal').modal('show');
}
});
}
//and my controller code is
public ActionResult BulkUpdate(List<Tag> tags)
{
ModelAccessor obj1 = new ModelAccessor();
obj1.updatedDatas = new List<UpdatedData>();
foreach (var item in tags)
{
var tag = db.Tags.Where(x => x.Id.Equals(item.Id)).FirstOrDefault();
if (tag.TagValue != item.TagValue)
{
UpdatedData changedRow = new UpdatedData {
OldTagValue=tag.TagValue,
NewTagValue=item.TagValue.Trim()
};
obj1.updatedDatas.Add(changedRow);
}
}
return PartialView("_UpdateConfirmationBulk", obj1);
}
I have a solution.
function BulkUpdate()
{
debugger;
var model = #Html.Raw(Json.Encode(Model.tags))
$.ajax({
type: 'GET', //GET
data: {'tags':JSON.stringify({model})},
url: '#Url.Action("BulkUpdate", "Home")',
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
$('#myModalContent').html(data);
$('#myModal').modal('show');
}
});
}
Try this because your method expects a parameter named tags and this is missing in you ajax call.
Can you try the type by post?
var model = #Html.Raw(Json.Encode(Model.tags))
$.ajax({
type: 'POST', //GET
data: JSON.stringify({model}),
url: '#Url.Action("BulkUpdate", "Home")',
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
$('#myModalContent').html(data);
$('#myModal').modal('show');
}
});

i am trying to pass parameter to data through ajax

I am trying to pass value through an ajax json array but value of catergory variable is not getting in controller action
var category = $('#category').val();
var url = $('#ajax_action_search').val();
$.ajax({
type: "POST",
data: {
'category': category
},
dataType: "json",
cache: false,
contentType: false,
processData: false,
success: function(response) {}
});
You need to use the parameter namespace matching your extension/plugin:
$.ajax({
// ...
data: {
'tx_myext_foo[category]': category,
},
// ...
});
But you'll also need to configure the cHash evaluation since this will lead to a HTTP request like /?tx_myext_foo[category]=X which will fail without a matching cHash.
This can be done with the excludedParameters configuration option.
Please check the Controller action if category (parameter name) passed from the ajax is exactly same in the controller action too
var category = $('#category').val();
var url = $('#ajax_action_search').val();
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
cache: false,
async: false,
url: url,
data: JSON.stringify {
category: category
},
dataType: 'json',
success: function(response) {}
});
You need to make ajaxurl with action and controller. and then pass the data in full format.
var ajaxUrl = '<f:uri.action action="youraction" controller="Yourcontroller" />';
var category = $('#category').val();
$.ajax({
type: 'POST',
url: ajaxUrl,
data: '&tx_yourext_yourplugin[category]='+category,
success: function(response) {
},
});
Just make the following changes :
var category = $('#category').val();
var url = $('#ajax_action_search').val();
$.ajax({
type: "POST",
url:url,
data: {'category': category},
dataType: "json",
success: function(response) {}
});

Passing data with ajax and read it with Request.Form[""]

I try to pass parameters into aspx.cs page from js script. When I omit:
contentType: "application/json; charset=utf-8"
in ajax request I get by Request.Form["ORDER"] sth like {%7b%22ORDER_ID%22%3a126333%7d}. It means that this data comes to aspx.cs, but it is not decoded.
When I add contentType I get nothing in request.
Below I attach request.
It is important to read parameters from Request.Form["ORDER"] in aspx.cs;
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ ORDER_ID: orderKeyId }),
dataType: "json",
url: sUrl,
success: function (data) {
var s = 0;
},
error: function () {
var s = 0;
}
});
According to #Rory McCrossan comment, below ajax state worked:
$.ajax({
type: 'POST',
contentType: "application/x-www-form-urlencoded",
data: "ORDER_ID=" + encodeURIComponent(orderKeyId),
url: sUrl,
success: function (data) {
var s = 0;
},
error: function () {
var s = 0;
}
});

Send byte[] in ajax

I need to send data with id,name , and file (PdfBytes) byte[] with ajax to my service.
How can i add my PDF file to var pdf and add it to my ajax.
My code
var PdfBytes;
//Tried to fill PdfBytes with get,didnt work
$.get('http://testservices.xxx/PdfService/MYTest.pdf', function(data)
{
PdfBytes=data;
});
var ConvertHtmlToPdfAndSendEmail = {
"PdfBytes":PdfBytes,
id": id,
"Name": name
};
$.ajax({
type: "POST",
data: JSON.stringify(ConvertHtmlToPdfAndSendEmail),
dataType: 'json',
url: "http://testservices.xxx/ConvertHtmlToPdfAndDownload",
contentType: 'application/json; charset=utf-8',
async: true,
cache: false,
success: function (result) {
//my code
},
error: function (req, err) {
//my code
}
})
In the server i get PdfBytes is null
function expect to get byte[] PdfBytes
Sow how i can upload my pdf from my pc to var PdfBytes ,and send it in ajax to my service.
There two way to send byte[] in Ajax
You convert byte[] to string for GET or to json for POST
=> The main thing you should convert to byte array to text
and recover the data format when call the server script
$.ajax({
type: "GET",
url: "http://testservices.xxx/ConvertHtmlToPdfAndDownload?data="+encodeURI(byte_array.join())
});
$.ajax({
type: "POST",
dataType: "json",
data: JSON.stringify(byte_array),
url: "http://testservices.xxx/ConvertHtmlToPdfAndDownload"
});
Hope it help!
I think you should use option call 'async' so do that:
var PdfBytes = $.ajax({
url: 'http://testservices.xxx/PdfService/MYTest.pdf',
type: 'GET',
async: false
});
var ConvertHtmlToPdfAndSendEmail = {
PdfBytes: PdfBytes,
id: id,
Name: name
};
$.ajax({
type: "POST",
data: JSON.stringify(ConvertHtmlToPdfAndSendEmail),
dataType: 'json',
url: "http://testservices.xxx/ConvertHtmlToPdfAndDownload",
contentType: 'application/json; charset=utf-8',
async: true,
cache: false,
success: function (result) {
//my code
},
error: function (req, err) {
//my code
}
});
Hope it help.

Categories

Resources