I need send stored procedure with parameter in ajax data.
Below is my example, after send get this error
Apostrophes real problem,any solution?
function sendData(userNameVal, procedureNameVal, jsonCallBackFunc) {
var stringVal = "wsInsertData N'EXECUTE carInsert N''160655'',N''data:image/png;base64,AAAAAAAAAAAA'',N''18602''', N'18602'";
$.ajax({
type: "POST",
url: 'helloService.asmx/myService',
data: "{userName:\"" + userNameVal + "\",procedureName:\"" + stringVal + "\",callback:\"" + jsonCallBackFunc + "\",}",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (response) {
$('#lblError').html(JSON.stringify(response));
},
error: function (error) {
console.log(error);
}
});
}
Security! All it takes is a user to edit the JSON response to the server and add their own SQL, and they can make your SQL server do anything they want. Pass whatever parameters you need, and have the server construct the Stored Proc after sanitizing possible crazy inputs from the client.
Before 'callback' you add a single quote ', which is not terminated.
Related
So, this is driving me nuts and I've never seen this before. I'm using Javascript to post JSON to AWS Lambda. The issue is that the payload is being sent as indexed characters instead of JSON. I can't for the life of me figure out why. I use this same code in another project and don't have this issue with posting JSON. This is what is being sent:
0=%7B&1=%22&2=C&3=o&4=m&5=p&6=a&7=n&8=y&9=N&10=a&11=m&12=e&13=%22&14=%3A&15=%22&16=R&17=T&18=S&19=%22&20=%2C&21=%22&22=F&23=i&24=r&25=s&26=t&27=N&28=a&29=m&30=e.....
As you can see it's indexing every single character of the data.
Here's my function:
$.ajax({
url: serviceUrl + "UpdateCompany",
type: "POST",
data: JSON.stringify(company),
contentType: 'application/json',
dataType: "json",
success: function success(res) {
if (res.status == "ok") {
utils.notify("Company updated successfully");
callback(res.data);
}
else {
utils.notify(res.message);
}
},
error: function error(res) {
alert("Could not complete action. Please refresh the page and try again.");
}
})
My "company" object is created like this:
var company = {};
company["CompanyName"] = $("#txtCompany").val();
company["FirstName"] = $("#txtFirstName").val();
When I debug it and run JSON.stringify(company), it displays the data correctly in JSON format, but when it's sent through the POST, it's not JSON format and indexing the characters like above.
I have a function that calls a method in controller through an Action URL, but I need use a parameter like name of Method, but this is not possible in this way.
function changeDropDownList(id, dropNameToChange, actionName, descriptionName) {
var control = $('#'+dropNameToChange);
control.prop("disabled", false);
$.ajax({
//Here I need use the actionName var, but only accept a string
url: '#Url.Action(actionName, "ThirdPartiesDef")',
dataType: "JSON",
data: { id: id },
contentType: "application/json; charset=utf-8",
success: function (result) {
control.empty();
$.each(result, function (index, item) {
control.append(
$('<option/>', {
value: item.Id,
text: item[descriptionName]
})
);
});
},
error: function (error) {
alert("Error: " + error);
}
});
}
I don't know so much of ajax and if you can say me some more easy method, it's ok.
Thank you for your help
You could use a placeholder inside the Url.Action server side Razor function that will be replaced by your javascript actionName variable on the client side:
url: '#Url.Action("#THE-ACTION#", "ThirdPartiesDef")'.replace('#THE-ACTION#', actionName)
which basically will emit the following markup inside the browser on the client:
url: '/#THE-ACTION#/ThirdPartiesDef/'.replace('#THE-ACTION#', actionName)
which after calling the changeDropDownList javascript function on the client it will replace the placeholder with the actionName javascript variable and you will end up with the correct url to use for your AJAX call.
As a side note you should remove the contentType: "application/json; charset=utf-8" parameter from your AJAX call because you are not sending any JSON at all in your data parameter.
You have to use JSON.stringify() method.
JSON.stringify() method turns a javascript object to json text and stores it in a string.
You specified contentType: "application/json; charset=utf-8", and the server waits to receive data in json format.
Also, you used wrong #Url.Action : #Url.Action(actionName, "ThirdPartiesDef")',.
One solution is to use .replace function:
'#Url.Action("myAction", "ThirdPartiesDef")'.replace('myAction', actionName).
In Razor every content using a # block is automatically HTML encoded by Razor.
For example, I'm currently implementing client side javascript that will use a POST if the additional parameters exceed IE's safety limit of 2048ish charachers for GET HTTP requests, and instead attach the parameters to the body in JSON format. My code looks similar to the following:
var URL = RESOURCE + "?param1=" + param1 + "¶m2=" + param2 + "¶m3=" + param3();
if(URL.length>=2048) {
// Use POST method to avoid IE GET character limit
URL = RESOURCE;
var dataToSend = {"param3":param3, "param1":param1, "param2":param2};
var jsonDataToSend = JSON.stringify(dataToSend);
$.ajax({
type: "POST",
data: jsonDataToSend,
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("POST error");
},
success: function(data) {
alert("POST success");
}
});
}else{
// Use GET
$.ajax({
type: "GET",
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("GET error");
},
success: function(data) {
alert("GET success");
}
});
}
Is there a way of me avoiding writing out this ajax twice? Something like
if(URL.length>=2048) {
// Use POST instead of get, attach data as JSON to body, don't attach the query parameters to the URL
}
N.b. I'm aware that using POST instead of GET to retrieve data goes against certain principles of REST, but due to IE's limitations, this has been the best work around I have been able to find. Alternate suggestions to handle this situation are also appreciated.
The $.ajax method of jQuery gets an object with properties. So it's quite easy, to frist generate that object and a "standard setting" and modify them based on certain logic and finally pass it to one loc with the ajax call.
Principle:
var myAjaxSettings = {
type: "POST",
data: jsonDataToSend,
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("POST error");
},
success: function(data) {
alert("POST success");
}
}
if ( <condition a> )
myAjaxSettings.type = "GET";
if ( <condition b> )
myAjaxSettings.success = function (data) { ...make something different ... };
$.ajax(myAjaxSettings);
I am having having problem with sending the an object and two parameter in an ajax call.
My Server side method:
public ActionResult AddUpdate(string model, bool IsEdit, string Type)
{
//Do something
}
Client side ajax call is:
I am fetching all form values provided by user and saving them into "MemberObj" and sending another 2 parameters ie IsEdit and Type. but at server side i am getting only the IsEdit and Type values model parameter is null. The date value in ajax call after stringify is like:
"{"model":{"id":"123","Name":"Jhon Doe","Relation":"Father","Dob":"15-3-2014","Address":"abc":" abc","City":"abc","MobileNumber":"1234567890"},"IsEdit":false,"Type":"FamilyMember"}"
var MemberObj={};
MemberObj.Name="aaa";
var requestJSONData={ "model": MemberObj, "IsEdit": IsEdit, "Type": str[0] }
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: '/Employee/AddUpdate',
data: JSON.stringify(requestJSONData)
success: function (msg) {
//Success
},
error: function (msg) {
}
});
Any help is most appericiate.
Thanks
in one of my projects i used the following line and it works like a charm:
data: "{'sid':'" + sid.toString() + "'}",
try adapting yours to this format, it should work.
Let me start by saying I am not extremely familiar with Javascript and I cannot figure out what is going on here.
I have the following function:
self.search = function () {
var searchTerms = {
"City": this.cityName,
"State": this.stateName,
"StoreNumber": this.storeNumber,
};
$.ajax("/api/SearchApi", {
data: searchTerms,
type: "POST", contentType: "application/json",
success: function (result) {
alert(result);
}
}
});
When I submit, what happens is that instead of submitting a nice JSON object as expected, it submits a JSON objected formatted as so: "City=testing&State=AL&StoreNumber=test "
Ideally I would like to use a GET method that passes the object to my server so that I can return the results, but when I use a get method, it simply appends the above to the API call url resulting in a URL request formed as so: http://localhost:57175/api/SearchApi?City=testing&State=AL&StoreNumber=test
Any help would be appreciated.
Make sure you add the dataType of JSON to your $.ajax({ }); object. That should solve the problem!
$.ajax({
// ...
data : JSON.stringify( searchTerms ), // Encode it properly like so
dataType : "json",
// ...
});
2 Things
Add the json content type(not the data type) to your ajax object important to note is the charset your server is using in this case utf-8.
Use the Json2 Library to stringify and parse Json when sending and retrieving it can be found here : https://github.com/douglascrockford/JSON-js/blob/master/json2.js
$.ajax({
url: URL,
type: "POST",
//Stringify the data you send to make shure its properly encoded
data: JSON.stringify(DATA),
//This is the type for the data that gets sent
contentType: 'application/json; charset=utf-8',
//This is for the data you receive
dataType: "json"
}).done(function(data) {
var dataYouGet = JSON.parse(data);
}).fail(function(xhr, ajaxOptions, thrownError) {
}).always(function(data) {
});