I want to send data to a camera, and it only accepts the data when it has no encoding to it.
The data should look like
<?xml version="1.0" encoding="UTF-8"?>
<EventTriggerList version="2.0">
...
</EventTriggerList>
I have a function that creates that string just fine, and when I use it via an application to send to the camera, it works. But when I use Ajax:
$.ajax({
url: target,
type: 'PUT', //type is any HTTP method
contentType: "application/xml",
data: {
data: dataString
},
success: function () {
}
})
;
it sends the above as
<?xml+version="1.0"+encoding="UTF-8"?>
<EventTriggerList+version="2.0">
...
</EventTriggerList>
and the camera won't accept it.
I tried setting processData to false, but then my payload is only 15 bytes, instead of the expected 300 bytes of string.
How do I get the payload to be precisely as the string I generated?
Since your content type is xml and dataString is also xml, just pass it as is
$.ajax({
url: target,
type: 'PUT', //type is any HTTP method
contentType: "application/xml",
data: dataString,
success: function () {
}
})
Related
I have build a image cropper tool from there i wanted to store that base64 image to server. I have sent it through Ajax. Image got stored in jpg format.But the problem is it's got corrupted. Can anyone suggest me what could be the solution?
Here is my ajax call :
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
method: 'post',
url: 'updateProfilePicture',
cache: false,
contentType: "application/json; charset=utf-8",
data: {'image': encodeURIComponent(profileImageUrl)},
success: function (data) {
alert(data);
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
Here is the controller for converting base64 to normal image and stored to server:
public function updateProfile(Request $request)
{
$base64img = str_replace('data:image/jpeg;base64,', '', $request->Input(['image']));
$data = base64_decode($base64img);
$file = public_path() . '/users/' .'123123123.jpg';
file_put_contents($file, $data);
return \Response::json($data);
}
You aren't sending JSON so don't claim you are sending JSON. Remove this.
contentType: "application/json; charset=utf-8",
You are passing an object to data:
data: {'image': encodeURIComponent(profileImageUrl)}
When you pass an object, jQuery will encode it as form URL encoded data.
By running your code through encodeURIComponent you cause the data to be double encoded.
Don't do that.
data: {'image': profileImageUrl }
I am making a basic PATCH call like this one:
.ajax({
url: "/foo/bar/"
type: "PATCH",
dataType: 'json',
data: {
"foo": "foosball",
"bar": "bars on bars"
},
...
});
Jquery automatically encodes the data, which leaves "bars on bars" like "bars+on+bars". Is there a way to change the encoding so that spaces are replaces with %20 rather than pluses?
I've noticed this thread that didn't seem to lead anywhere.
I've also taken note of encodeURI and encodeURIComponent but haven't gotten either to work. Both seem to result in the string being double encoded, leaving me with bars%2520on%2520bars
summary:
What I start with:
... "bars on bars" ...
What the received data looks like after jquery encodes the request:
"bars+on+bars"
What I need the received data to look like:
"bars%20on%20bars"
How about use a variable and pass that to data.
var d={
"foo": "foosball",
"bar": "bars on bars"
}
d.bar=encodeURI(d.bar);
.ajax({
url: "/foo/bar/"
type: "PATCH",
dataType: 'json',
data: d,
...
});
Still wish there was a better way, but I ended up using this plugin from this website.
jQuery.extend({
postJSON: function(url, data, callback) {
return jQuery.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
success: callback,
dataType: "json",
contentType: "application/json",
processData: false
});
}
});
This forces my api to parse the body as a string into a dict/json. Hopefully in a few years someone can come along with a better solution.
I have a simple controller function like this:
<HttpPost>
Function SaveXML(payload As String) As Boolean
If payload IsNot Nothing AndAlso payload.Length > 0 Then
Return True
Else
Return False
End If
End Function
Which I'm calling from JavaScript like this:
function SaveXML() {
var payload = '<?xml version="1.0" encoding="utf-8"?><data>XML_GOES_HERE</data>';
// Calls controller correctly but data is null
$.ajax({
url: "/Data/SaveXML/",
type: "POST",
processData: false,
contentType: "text/xml",
data: payload
})
.done(function () { alert('Application saved.'); })
.fail(function () { alert('Application failed to save.'); });
}
I'm using the example on the JQuery documentation as a base with some advice from here, here, and here. I've tried it with and without processData: false and it makes no difference.
When the call comes in to the Controller method the payload is null. If I post a simple string using some very similar code everything works fine. What precisely needs to be done in order to post XML to a Controller via $.ajax? Is it at the JavaScript or Controller end that the problem lies?
I eventually managed to find some hints on this and ended up with the following code:
$.ajax({
url: "/Data/SaveXML/",
type: "POST",
processData: false,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ payload: payload })
})
.done(function () { alert('Application saved.'); })
.fail(function () { alert('Application failed to save.'); });
The crucial differences are that the contentType is set to application/json, the data is turned into an object which is then run through the JSON.stringify method to make sure that the various characters that are unsuitable for a querystring can be sent without failing.
The default model binding doesn't work with processData set to false. If ServerXml is a string of XML, removing this should make it work:
function SendXmlToServer(ServerXml) {
$.ajax({ url: "/Home/XmlData",
type: "POST",
data: { ResXml: ServerXml }, dataType: "xml",
success: function () {
alert("Successful");
return false;
}
});
}
You'll also have to add the ValidateInput attribute to your action method, because normally "HTML markup" isn't allowed:
[HttpPost]
[ValidateInput(false)]
public ActionResult XmlData(string ResXml)
{
return null;
}
Alternatively, you could use custom model binding to seamlessly deserialize the XML, as explained in this blog post url https://lostechies.com/jimmybogard/2011/06/24/model-binding-xml-in-asp-net-mvc-3/.
I believe you may need to name the parameter you are passing to the controller.
So, something like...
var data = '<?xml version="1.0" encoding="utf-8"?><data>XML_GOES_HERE</data>';
$.ajax({
url: "/Data/SaveXML/",
type: "POST",
processData: false,
contentType: "text/xml",
data: { payload: data }
})
I have a problem. I'm trying to send content of a textarea with an ajax call, but it doesn't seem to be working, and I don't know why.
There's the method called GetStatus(string statusText) which need to receive the content.
Here's the javascript code:
$("#btnSaveStatus").on("click", function () {
var statusText = $(".textareaEdit").val();
$.ajax({
type: "GET",
url: "Default.aspx/GetStatus",
data: "{statusText:'" + statusText + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// $('#littlbioID').text(result.d);
}
});
});
Please advise. You should also know that I'm new into web development.
You can't have a request body in a GET request, you have to use a POST request for that
The string you are constrcting is not valid JSON since:
Property names must be strings
You have no idea what the user will enter in the textarea - it might contain characters with special meaning in JSON
Generate your JSON programatically.
{
type: "POST",
url: "Default.aspx/GetStatus",
data: JSON.stringify({
statusText: statusText
}),
// etc
Obviously, the server side of the process needs to be set up to accept a POST request with a JSON body (instead of the more standard URL Form Encoded format) as well.
Try this:
$("#btnSaveStatus").on("click", function () {
var statusText = $(".textareaEdit").val();
var jsonText = new Object();
jsonText.statusText = statusText;
$.ajax({
type: "POST",
url: "Default.aspx/GetStatus",
data: JSON.stringify(jsonText);,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// $('#littlbioID').text(result.d);
}
});
});
Below is an Ajax request to a static web method at server. I want to send the file and its associated details to the server. Even if I send the data to the server, i'm not able to access the file at the server side using c#.net.
The most difficult part being accessing the FileUpload control in the static WebMethod.
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'UserProfile.aspx/EditProfile',
data: "{'file':'" + document.getElementById('FileUpload1').files[0] + "'}",
async: true,
success: function (response) {
$('#dialog-form').dialog("close");
}
});
Don't attempt to send the data as JSON, send it as formdata with FormData and you can read the file on the server side as if you used a regular form to upload the file.
var data = new FormData();
data.append('file', document.getElementById('FileUpload1').files[0]);
$.ajax({
type: 'POST',
url: 'UserProfile.aspx/EditProfile',
data: data,
async: true,
processData: false,
contentType: false,
success: function (response) {
$('#dialog-form').dialog("close");
}
});