Internet Explorer strips HTML from JSON response - javascript

I'm using the jQuery Form plugin to submit a form via AJAX and receive a JSON response:
$('#'+searchFormView.form.form.id).ajaxForm({
dataType:'json',
success:This.renderSearchResults,
error:This.error
});
The HTTP response body:
{
"grid":{
"headers":[
"Image","Additional","data","button"
],
"rows":[
["<img src=\"\Path_to_image\" alt=\"picture\">",
"Additonal",
"data",
"<button>Button text<\/button>"
],
[Some more of these arrays]
]
}
}
Chrome and FF are totally OK with this. It renders fine. IE strips the HTML out of the data value by the time it hits the success method:
renderSearchResults:function(data){
console.log(data.grid.rows[0][0]);
// Render the grid.
}
The result of the console log in IE:
Log:
If I watch the local variables while the success method runs:
"{
\"grid\":{
\"headers\":[
\"Image\",
\"Additional\",
\"data\",
\"Button\"
],
\"rows\":[
[\"\",\"Additional\",\"data\",\"Button text<\\/button>\"],
...
As you can see, the HTML tags are gone (curiously, the tag is still there).
Is this supposed to be an XSS protection?
How do I get around it?

Related

Datatable Invalid JSON response

I have a problem with Datatables.
Until now, everything worked like a charm, now, from reasons unknown to me, datatables stopped working on my app.
My datatable ajax call is returning:
DataTables warning: table id=section-list - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
My datatables init:
sections.find('table#section-list').dataTable({
"ajax": '/admin/page/get-section-list',
"columns": [
{"data": "SectionID"},
{"data": "SectionAlias"},
{"data": "Edit"},
{"data": "Delete"},
], aoColumnDefs: [
{
bSortable: false,
aTargets: [-1, -2, -3] // disable sorting on last three columns (icons)
}
]
});
and my page/get-section-list action
....
return new JsonModel(["data" => $sections]); // this is equivalent to echo json_encode() in basic php
I tested my JSON in Json Parser AND it is 100% ok and there is no previous output before this json.
Im using DataTables 1.10.3 with jQuery v1.10.2
I ran into a similar problem working with a data.json file and found the information from here very helpful. Specifically the recommendation to open chrome dev tools, click the network tab, and then try the request again so you can see it in the network timeline.
In my case it looked like the json file in my "ajax": '/path/to/data.json' was still being written to at the same time the reload request was trying to access the data. Adding a delay around the reload request to give data.json time to complete solved the issue:
setTimeout(
function() {
$('#tableid').DataTable().ajax.reload(null, false);
}, 125);
But its hard to know what the optimal delay setting should be. So instead of doing the settimeout() (which works btw), I changed how I was writing my data from nodejs asynchronous fs.writeFile() to the synchronous fs.writeFileSync() when writing to the file.
Every case will be a little different but if you know the data source normally returns valid json, you may want to inspect if that source is changing at the same time datatables is trying to access it.

POST data truncated between browser and PHP

I'm running into an issue where large data sets sent over POST using AJAX are not making it to the $_POST variable in PHP.
The user uploads an Excel/CSV file through a webform and is parsed via AJAX. This particular example has 775 records with 13 fields/elements each. Adding additional fields being submitted and there are less than 11,000 elements in the dataset. From the research I've done on the subject, 32-bit browsers (i.e. Firefox, Chrome, etc.) should be able to handle 4.29 billion elements, so I don't see the data size as an issue, especially as the response from the file upload contains all the elements.
The issue only rears its head when the entire form is submitted to be validated and entered into the database. The issue is that the console on both Firebug and Chrome Developer Tools shows that the whole data set is submitted:
Doing a var_dump on the $_POST gives this:
The php.ini has 'post_max_size' set to 200M. Even 'upload_max_filesize' is set to 100M. This issue occurs in both Firefox 32.0.3 and Chrome 37.0.2062.103 m that I have tested personally and other older versions (including IE 10) that UAT has tested.
The AJAX call is:
new wrapper.ajax('/t1.php', {
type: 'POST',
data: data,
form: $('form[name=oppForm]'),
success: function (response)
{
if (response.result)
{
window.location = response.result;
}
},
complete: function ()
{
$("#submit").loading('done');
}
});
The PHP is:
<?php
var_dump($_POST);
Any thoughts?
EDIT
After talking with some other developers, I also checked the output of php://input and found that it DID contain the entire POST data that the browsers were sending, but that the data was not getting translated into $_POST properly. However, it does work properly if I remove 10 keys from the post data, and submit 765 instead of 775.
The issue ended up being that 'max_input_vars' in the php.ini file was not set high enough. The value was set to 10,000 and the user was submitting data of near 11k, thus some of it was getting truncated. Changing this value to be greater is what solved the issue.

$('body').html() gave blank content from response data that come from $jQuery.post in Firefox

I got this javascript code in a JSP:
$('#myForm').submit(function(event) {
event.preventDefault();
var act = $('#myForm').attr('action') + '&act=' + $('#submitBtn').val();
var dataStr = $("#myForm").serialize();
$.post(act, dataStr, function(data, status) {
$('body').html(data);
});
return false;
});
The facts:
I'm using jquery v1.3.x (and I can't replace with newer version because of company policy).
The jsp is in a pop-up window.
There is a submit button with id=submitBtn
When the submit button is clicked, it will execute above code and send the data into struts action.
The action url:
someAction.do?someParam=blabla&someNo=213354345&mode=POP&act=Update Your Data
(note: I had replaced some sensitive data, but the argument pattern is same)
The problem is at this line:
$('body').html(data);
It produces Error: NS_ERROR_FAILURE: Failure in error console. I heard it's related with cross domain request, but my application is at localhost, how could it happened?
In IE 8, it successfully replaced the current page content with the data value (which is html string). But in firefox (v22), it gave blank page, I checked with right click -> View Source, it's really empty. Then I checked with firebug, the response data indeed contains the result html page string. If I debug with alert(data); before the $('body').html() call, it also show the html string.
So the $.post() function successfully returns the response data but it seems the $('body').html() function failed to render the data.
So what is actually happened? I'm really have no clue.
What is the solution for this?
UPDATE:
I checked the error console, I got this error after submitted the page:
Error: NS_ERROR_FAILURE: Failure
Source File: http://localhost:8080/myapp/script/jquery.js
Line: 19
UPDATE 2:
I debug the java code, I found out that the input html tag in the JSP that has indexed array name like this:
myItem[0].name
myItem[1].name
...
were not successfully submitted to the ActionForm class. I investigated the source of problem might come from a 3rd party javascript library.
try something like this
$.post(act, dataStr, function(data) {
document.body.innerHTML = data;
});

IE7 JSON Response: Object Expected.. Works in Chrome and FireFox

This is the last thing I have to do before I can send my beloved webapp into the wild, but of course IE7 is being difficult with me!!
I am using the JQuery Form plugin to upload data to my server. A servlet class will then run some operations with the file and shoot back some JSON to the client. As always, Chrome and Firefox handle the response like champs and give me the output I expect.
Internet Explorer 7 does not. I get an "Object Expected" error.... I have narrowed down my problem to a single function. I have made an educated guess that IE7 is not handling the response properly, but I really don't know. Here is the actual code that causes problems:
function uploadScript() {
$("#uploadScript").ajaxSubmit({
beforeSend: function() {
$("#uploadScript").attr("disabled", true);
},
dataType: "json",
cache: false,
success: function(response, status, xhr) {
if(response != undefined) {
commandArray = ([]).concat(response.command);
paramsArray = ([]).concat(response.params);
IDArray = ([]).concat(response.id);
commandID = response.commandID;
updateScriptView();
}
}
})
}
I have already tried explicitly setting the response header content type to 'application/json' to no avail. I have even read somewhere that such a header will even cause IE to bug out, so that front has certainly been confusing.
Perhaps it is the JSON syntax? Nope! I checked it, double checked it, then ran it through JSONLint just to be sure.
Any ideas on what I'm doing wrong?
EDIT: The JSON response literally is this:
{ "command" : ["sequential","wait","tune","endsequential"],"params" : [["5"],["00:00:03"],["202","RA29B[*]"],["100000"]],"id" : [100000,100002,100003,100001],"commandID" : 100004}
Eye-friendly is this:
{
"command": [
"sequential",
"wait",
"tune",
"endsequential"
],
"params": [
[
"5"
],
[
"00:00:03"
],
[
"202",
"RA29B[*]"
],
[
"100000"
]
],
"id": [
100000,
100002,
100003,
100001
],
"commandID": 100004
}
ANSWERED! Apparently, my $.attr() call in the beforeSend option of the ajaxSubmit() was causing problems in IE7. I do not know why this is the case, and my Googling yielded no results (Gotta Google the right question to get the right answer). Anyway, removing this code block solved my issue. I appreciate ALL the help that was given to me. Thanks guys!
Looks like you're using malsup plugin. If that's the case then the git repo has some known issues with this plugin:
https://github.com/malsup/form/issues
Check that your issue is not one already reported. Also check you jQuery version
this is the one for you: https://github.com/malsup/form/issues/179

AJAX callback not handling data properly

I have a PHP script that I'm calling with the .post() function in jQuery. If everything goes well, it outputs "WIN", otherwise it outputs whatever database errors or whatever else it gets.
$.post("myscript.php", {key: "value"}, function(data) {
if(data=="WIN") {
// the stuff that I want it to do that it won't do
} else {
alert(data);
}
});
When it runs however, I get "WIN" in a JS alert, and the stuff that I want it to do doesn't happen. Since "WIN" shows up in the alert, the PHP script is clearly outputting what I had expected. I had even made sure to set the Content-Type of the PHP script to text/plain, so why doesn't data=="WIN". Why does my WIN FAIL?
Have you checked for whitespace? Any whitespace before or after echo "WIN" will affect the output, also, check for whitespace before and after your <?php tags.
You are most likely trying to access the returned data from 'data' directly. Try
alert(data.d);
I think that you will find that the returned data is in a property. If I remember correctly, that property's name is 'd'. Use the FireFox plugin FireBug to view the returned data. It is very helpful for AJAX debugging.
Good Luck!

Categories