JQuery post function problem - asp.net-mvc-2

I try to post some data via json objects to my asp.net mvc view, here is the code
$("#submitButton").click(function () {
var name = $("#name")[0].valueOf();
var price = $("#price").valueOf();
var url = $("#url").valueOf();
var product = { Name: name, Price: price, Url: url };
$.post("/Home/NewProduct", product, function (json) { $('ul.items').append("<li><img src=" + url + "/></li>"); },"json");
});
and now, the result is an error:
uncaught exception: [Exception... "Illegal operation on WrappedNative prototype object" nsresult: "0x8057000c (NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)" location: "JS frame :: http://localhost:1804/Scripts/jquery-1.4.2.min.js :: f :: line 132" data: no]
I try JQuery 1.4.1 and 1.4.2, If I try this code the error is the same
$.ajax({
type: "POST",
url: "/Home/NewProduct",
dataType: "json",
data: { Name: name, Price: price, Url: url },
success: function () { $('ul.items').append("<li><img src=" + url + "/></li>"); }
});
What I'm doing wrong? Please help!
Thanks!

To get the value of an input type element, use .val() instead of .valueOf(), like this:
var name = $("#name").val(),
price = $("#price").val(),
url = $("#url").val();
When you call .valueOf() on a jQuery object, it gets an array of DOM elements...and that doesn't serialize well :)

In your $.post call if you pass JSON as a 4th parameter then jQuery will expect VALID json string only other wise it might cause error.
example of valid JSON is
var json = {"a":"my name", "b":"my school"};

Related

problem sending html2canvas image to ajax

I am working in ASP.net. I can create an image using html2canvas of the div i want, but sending it through AJAX causes an error. The error statuscode is 'OK'. Not sure what that means. The serever side code never gets executed. The AJAX call I am making looks like this:
html2canvas($('#box1'), {
onrendered: function (canvas) {
$('#box1').html('');
$('#box1').append(canvas);
cartImage = canvas.toDataURL('image/jpeg');
$.ajax({
type: "POST",
url: pageUrl + '/UploadImage',
data: { "imageData": cartImage },
dataType: "json",
success: function (msg) {
console.warn(msg.d);
},
error: function (result) {
console.warn(result.statusText);
}
});
The server side code looks like this:
Public Shared Function UploadImage(imageData) As String
imageData = imageData.Replace("data:image/png;base64,", "")
Dim fileNameWitPath As String = "TempDownload/" & Guid.NewGuid().ToString & ".png"
Dim fs As FileStream = New FileStream(fileNameWitPath, FileMode.Create)
Using (fs)
Dim bw As BinaryWriter = New BinaryWriter(fs)
Using (bw)
Dim data As Byte() = Convert.FromBase64String(imageData) 'convert from base64
bw.Write(data)
bw.Close()
End Using
End Using
Return "Success"
I did find the AJAX call would work if I used JSON.stringify({ "imageData": cartImage }) for the data parameter in the AJAX call.

How to pass params in axios PUT request?

axios.put('http://localhost:3000/api/userDatas/findUserAddProp',{
params: {
userId: "5bb8c3bd16bf1f515ce5b42f",
prop: "questions",
questionId: "5bb8c466cb49d8421c05eeda"
}
});
Server
Userdatas.findUserAddProp = function(req, res, cb) {
const queryId = req.query.userId;
const propToUpdate = req.query.prop;
const questionId = req.query.questionId;
console.log("queryId: ", queryId);
console.log("propToUpdate: ", propToUpdate);
console.log("questionId: ", questionId);
...
}
Here is the the server output on the console.
queryId: undefined
propToUpdate: undefined
questionId: undefined
Why is that happening i just passed all params to the server?
the put method expects an extra parameter "data" (sent in request body):
axios.put(url[, data[, config]])
pass it as null and you're done:
axios.put('http://localhost:3000/api/userDatas/findUserAddProp', **null,** {
...
You can open Axios Interface
put<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
The Put method recieve the config after the data so you can do:
axios.put('http://localhost:3000/api/userDatas/findUserAddProp',
// Add null here in the data,
null,
// then you can give params in the config
{ params: { /* your params goes here */ }
});
Did you try
req.params.userId
req.param is used to read Url Params like /user/:id whereas req.query is used to read query parameters like http:localhost:8080/api/users?id=123

Sending POST requests to a nested API endpoint URL using Ember Data

I see several questions on SO attempting to solve this problem of sending POST requests to nested API resource routes.
See:
- [Sending REST requests to a nested API endpoint URL using Ember Data(Sending REST requests to a nested API endpoint URL using Ember Data)
- Custom request URLs in Ember model
I've started overloading the createRecord, updateRecord, and deleteRecord methods on the RESTAdapter to attempt some sort of hackery solution to building the correct URL. Now, using a method similar to this is the route I've taken so far.
Here is the updateRecord method in their solution:
App.UserAdapter = DS.RESTAdapter.extend({
updateRecord: function(store, type, record) {
if(!record.get('parent') || null === record.get('parent')){
return this._super(store, type, record);
}
var data = {};
var serializer = store.serializerFor(type.typeKey);
var parent_type = record.get('parent');
var parent_id = record.get(parent_type).get('id');
var child_parts = Ember.String.decamelize(type.typeKey).split('_');
var path = Ember.String.pluralize(parent_type) + '/' + parent_id + '/' + Ember.String.pluralize(child_parts.pop());
serializer.serializeIntoHash(data, type, record);
var id = record.get('id');
return this.ajax(this.buildURL(path, id), "PUT", { data: data });
}
....
});
This method should work great in tandem with adding the parent type to the model and ensuring the related parent model id is also represented on the model. For PUT and DELETE requests, this shouldn't be a problem, as we already have the parent ID relation on the object in store.
Project model:
App.ProjectModel = DS.Model.extend({
name: DS.attr('string'),
createdAt: DS.attr('date'),
updatedAt: DS.attr('date'),
workspace : DS.belongsTo('workspace'),
parent: 'workspace',
....
});
Where this method appears to go awry for me is in creating new resources with a post. I've attempted it, but since the payload hasn't been returned from the API server with the related parent ID, I actually don't have access to it.
Here's my crappy first attempt, that doesn't work. The workspace id always returns null.
createRecord: function(store, type, record) {
if (!record.get('parent') || null === record.get('parent')){
return this._super(store, type, record);
}
var data = {};
var serializer = store.serializerFor(type.typeKey);
var parent_type = record.get('parent');
var parent_id = record.get(parent_type).get('id');
var path = Ember.String.pluralize(parent_type) + '/' + parent_id + '/' + type.typeKey);
serializer.serializeIntoHash(data, type, record, { includeId: true });
return this.ajax(this._buildURL(path, null), "POST", { data: data });
},
Got any thoughts on how I can get the parent ID, before I have a saved record?
I am the author of the solution you cited in your question.
What does your model hook look like in the route where you are creating the new ProjectModel?
Assuming your Workspace route looks something like:
App.WorkspaceRoute = Ember.Route.extend({
model: function (params) {
return this.store.find('workspace', params.id);
}
});
Then your Workspace Project add/create route's model hook would need to be something like:
App.WorkspaceProjectAddRoute = Ember.Route.extend({
model: function () {
var workspace = this.modelFor('workspace');
return this.store.createRecord('project', {
workspace: workspace
});
}
}
I hope this makes some sense...

JQuery AJAX get not working correctly?

I have a partial view with this jquery script:
$("#btnGetEmpInfo").click(function () {
var selectedItem = $('#EmployeeId').val();
var focusItem = $('#EmployeeId')
alert("Starting");
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "<%= Url.Action("getEmpInfo", "NewEmployee")%>?sData=" + selectedItem,
data: "{}",
success: function(data) {
if (data.length > 0) {
alert("Yeah!");
} else {
alert("No data returned!");
}
}
});
alert("Back!");
});
Then in my controller I have:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult getEmpInfo(string sData)
{
return new JsonResult { Data = "test" };
}
I can breakpoint in the controller and it is hitting, but the only "Alerts" I get are the "Starting" and "Back". Why would the data not be returned or at least hit saying no data returned?
Thanks in advance for any and all help.
Geo...
You probably might want to improve this ajax call like this:
$.ajax({
type: 'GET',
url: '<%= Url.Action("getEmpInfo", "NewEmployee")%>',
data: { sData: selectedItem },
success: function(data) {
// Warning: your controller action doesn't return an array
// so don't expect a .length property here. See below
alert(data.Data);
}
});
and have your controller action accept GET requests:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult getEmpInfo(string sData)
{
return Json(new { Data = "test" }, JsonRequestBehavior.AllowGet);
}
OK, now that we have fixed the error let me elaborate. In your code you were using an application/json content type to format your request string. Unfortunately in ASP.NET MVC 2 there is nothing out of the box that is capable of making sense of JSON requests (unless you wrote a custom json value provider factory). Then using string concatenation to append the sData parameter to the URL without ever URL encoding it meaning that your code would break at the very moment the user enters some special character such as & in the EmployeeId textbox.
Try adding the 'beforeSend', 'error' and 'complete' callbacks to get more info in your javascript debugger. http://api.jquery.com/jQuery.ajax/
Are you using a javascript debugger? (firebug, ie9 dev-tools, chrome dev-tools are decent ones 3 that come to mind)

Sending parameters in AJAX call

This has been asked before by others, but I have not been able to use their answers.
I am trying to sending some data by doing the following:
function addForumPost() {
var title = jQuery('#forumTitle').val();
var message = htmlEncode(jQuery('#message').htmlarea("toHtmlString"));
var tagNames = addTags();
var dataPost = $.toJSON({ title: 'testingsadf', message: message, tagNames: tagNames });
jQuery.ajax({
type: "POST",
url: "/Create",
data: dataPost,
dataType: "json",
success: function (result) {
}
});
}
I have checked, and doubled checked that the input contains data, but I only receive the data from the message parameter in my controller. The other two values are null. As you can see in the the example above, I have even assigned some static text to the title parameter, but I still only receive data for the message parameter.
The controller looks like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(string title, string message, List<string> tagNames)
{
....
}
Your error is very simple. If you have an action which returns JsonResult then it means not that you have to send also JSON encoded input parameters to the method. Just remove the usage of $.toJSON() and use the object as a value of data parameter of jQuery.ajax (see the answer of Darin for example).
If you call ASMX Web Service instead of ASP.NET MVC action you have to use contentType: "application/json; charset=utf-8" and convert the values of all web-method parameters to JSON but in a little other way (see How do I build a JSON object to send to an AJAX WebService?). But ASP.NET MVC hat no such requirement. MVC converts the input parameters which you send with respect of Parse method (int.Parse, DateTime.Parse and so on) and not deserialize from JSON. So if you search for code examples look exactly which technology are used on the backend: ASP.NET MVC, ASMX web serveces or WFC.
Try setting the traditional parameter starting from jQuery 1.4. This works for me:
var title = 'title';
var message = 'message';
var tagNames = ['tag1', 'tag2'];
jQuery.ajax({
type: 'POST',
url: '/Home/Create',
data: { title: title, message: message, tagNames: tagNames },
dataType: 'json',
traditional: true,
success: function (result) {
}
});
With this action:
[HttpPost]
public ActionResult Create(
string title,
string message,
IEnumerable<string> tagNames
)
{
return Json(new
{
Title = title,
Message = message,
TagNames = tagNames
});
}
You don't have to post json for the type of action you described.
You don't have to manually assemble the fields into a map. Use .serializeArray()
var postData = $('.myform').serializeArray()