Ajax result is getting encoded - ajax

I have a page where onload I issue several POST requests simultaneously in order to load widgets on the page. The request looks something like this:
$.ajax({
type: 'POST',
contentType: 'application/json',
dataType: 'html',
data: JSON.stringify({}),
success: function(htmlResult) {
$div.html(htmlResult);
}
})
Most of the time everything loads fine. However, some of the time one of the widgets will get loaded with a replacement character. It's not one specific widget that this happens to, but it could be any one of them at random.
When I inspect the bad HTTP response, I notice that the Vary header has a value of Accept-Encoding and the body is encoded. All the other responses have a value of * for that header, and the body is text/html. I'm not explicitly setting the Vary header value anywhere.
I can't figure out what's causing this random behavior. Any ideas?
FYI, I'm posting to an ASP.NET MVC action, and returning a partial view.

have you tried dataType:'json' instead of 'html'?

Related

ckeditor insert or update doesnt work in first try

I'm having some trouble in using CKEditor and send it's information to database.
It works really good, I have all functionalities but when I sent it over ajax request to PHP, it doesn't assume the text into CKEditor first time. It only works after I make the ajax request the second time. It seems that CKEditor is not realtime and only after X time it saves the information that I typed, but I can't find anything related to it.
My init:
if (jQuery('#js-ckeditor:not(.js-ckeditor-enabled)').length) {
CKEDITOR.replace('js-ckeditor');
// Add .js-ckeditor-enabled class to tag it as activated
jQuery('#js-ckeditor').addClass('js-ckeditor-enabled');
}
My Function to make the request:
$.ajax({ url: '../inc/call.php',
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
data: formData,
type: 'POST',
beforeSend: function(){
$("#article_btn").html('<i class="fa fa-cog fa-spin"></i>');
$("#article_btn").attr("disabled", true);
},
success: function(output) {...}});
One more question, what's the best way to save this information to database?
Currently I'm using htmlspecialchars and htmlspecialchars_decode, but when using some functions (tables, colors), it really doesnt work well and don't save everything the correct way in database.
I will answer your first question:
If you are using AJAX please update textarea manually before sending data to server by calling https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_editor.html#method-updateElement. This topic is actually known. Please see e.g. https://dev.ckeditor.com/ticket/9913#comment:2.

Render a view while Ajax expects a response

I am building an express project, using ejs as a view engine, and AJAX for front-end http calls.
When I post a request such this:
$.ajax({
type: 'POST',
data: {'nickname' : $('#nickname').val()},
contentType: 'application/x-www-form-urlencoded',
url: 'http://localhost:5000/create',
success: function(data) {
$('#message').text("Unkwon error");
},
error: function(data){
$('#message').text('Something went wrong, check connection!');
}
The Ajax keeps waiting for a response, which I am not willing to give, as I just want to render a view as follows :
app.post('/create', urlencodedParser, (req, res)=>{
let code = unique.generate(rooms);
res.render('chat', {'nickname' : req.body.nickname, 'code' : code}
Any ideas how can I work around this?
After some research, I found a way to do it.
Basically, I can just tell the Ajax to attach the document sent from rendering to the html body
$('body').html(data);
Surprisingly, this works event with Ejs dynamic tags.
I know it's not the best way to do it, but it's the only one I found till now.
EDIT 1:
After few months, I realized the solution is simple as just changing the Location using javascript
window.location.replace(`http://localhost:5000/newRequest`);
Now, I could handle this new request separately on the server.
EDIT 2:
After couple years now, I realized a GET request might have solved the problem in a single round trip.

Using $.ajaxSetup() to append a data object to AJAX calls in Spine

I am using the $.ajaxSetup() function to append some additional params to each of my AJAX calls in Spine. However it isn't working as i'd expect it to.
If i call $ajaxSetup() as follows, my GET requests work fine, but my params are overidden with any POST requests and are not included in the form data as id expect:
$.ajaxSetup
data: "user_email=foo#bar.com&user_token=foobar"
As a result i tried changing my data string to an object to see if that made any difference:
settings =
data:
user_email:'foo#bar.com'
user_token:'foobar'
$.ajaxSetup settings
However that causes my URL's in my requests to appear malformed, like so:
http://dev.myapp.com:5000/api/v1/posts?[object%20Object]
I've tried recreating this in JSFiddle (my fiddle) to test that i wasn't going mad and it seems that my approach works as i'd expect over there. For GET requests, a string of my data object is appended to the end of my URL and with POST requests the data object is appended to the form data sent with the request.
So what am i doing wrong? Is this a bug in Spine or something else?
jQuery Version: 2.0.3
It looks like the problem is that spine sets data as a string:
type: 'POST'
contentType: 'application/json'
data: #record.toJSON()
(from the spine source)
You can use ajaxPrefilter to fix up requests before they are sent. Since the data is a JSON string you have a couple of options:
add your parameters to the JSON (by decoding it, using $.extend, then encoding it again)
add your parameters as custom HTTP headers instead of POST parameters
add the parameters to the URL, even on POST requests

HTML5/JSON : UTF-8 cant read proper characters from json

My HTML5 app is using JSON to fetch data.
The json contact characters like: ö
but the output in my browser is like: �
I used the following in HTML5 header:
<meta http-equiv="Content-Type"content="text/html;charset=utf-8">
and used this in the AJAX to read the JSON:
$.ajax({
url: "items.json",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
..........
But its not helping me out. What will be the solution to it?
I even tried "ISO-8859-1" on both places.
Make sure your font family that you are using for your site supports the extended characters you are attempting to print. Then use firebug or something similar to view what character set your backend json service is sending back. It may not be sending it back. Also, check to see if firebug is showing the correct character in the JSON response. It's possible that the problem is even further back than you thought.

jQuery AJAX JSON dataType Conversion

Hopefully that title isn't too cryptic. What's happening is I have a jQuery AJAX script that I'm trying to use to access an API on a remote server, which returns a JSON response. However, the API returns the JSON as MIME type "text/html" (in the response header) instead of "application/json". It would seem obvious that I simply need to change the returned content type from text to JSON, to make the AJAX call interpret the data correctly.
Unfortunately, this is not the case. I have tried this in a multitude of different ways, all of which fail. The closest I've gotten to getting this API call to work is when the debugger tells me "Resource interpreted as Script but transferred with MIME type text/html". And the AJAX call errors out with my debug message that dumps the jqXHR object in JSON format, which tells me: {"readyState":4,"status":200,"statusText":"parsererror"}
Here is an example of my code (although I have changed the code many various ways, in my attempts at getting it to work, but this version seems to be the closest to correct):
$.ajax({
type: 'GET',
url: 'http://username:api-key#www.kanbanpad.com/api/v1/projects.json',
contentType: 'application/json',
dataType: 'jsonp',
converters: {
'jsonp': jQuery.parseJSON,
},
success: function(data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log(textStatus+': '+errorThrown);
}
});
If anyone can figure out what I need to do differently to make this work, I will be extremely grateful.
It may also be worth noting that if you copy/paste the API URL into a browser address bar and hit go, it gives the proper JSON response with the proper response header ("application/json")
So unless Kanbanpad updates their API, it cannot be directly accessed with JS. You will have to use PHP (or some other) to handle the requests.
It works just as well, it just requires an extra step is all.
Just for anyone that was looking for a solution.
dataFilter(data, type)Function
A function to be used to handle the raw response data of XMLHttpRequest.
This is a pre-filtering
function to sanitize the response. You should return the sanitized data. The function
accepts two arguments: The raw data returned from the server and the 'dataType' parameter.
I would change the content type in the dataFilter interceptor to json. Bear in mind this affects all ajax calls, so use info from data to decide which ones you want to convert.
Verify that your server is sending a jsonp response. This means the json should be enclosed with a string of your callback.
The callback name is passed in the parameters, and if you're not setting it explicitly, looks something like: jQuery15102810791094068532_1300988427891 (As per http://www.json-p.org/)
On your server, you need to format the response:
jQuery15102810791094068532_1300988427891({...json response ...});
Where you use the callback defined in your GET parameter 'callback'.
You might try setting the type to "json" and see if it works. I've had a number of parsererror's with the jquery's jsonp - you might try http://code.google.com/p/jquery-jsonp until it's a bit smoother.
Try changing your content-type to this
contentType: "application/json; charset=utf-8",

Resources