PHP (or something else) adding unwanted HTML to my output [duplicate] - javascript

I've got a strange problem where I'm trying to write a PHP page that returns some JSON to a Jquery AJAX call. Problems is that despite setting the content type to application/json, the response always seems to include the HTML header.
Here's the PHP code:
// some code that generates an array
header("Content-type: application/json");
echo json_encode($return);
Then in Javascript:
$.ajax({
url: '/VAPHP/services/datatable.php',
dataType: 'json',
data:
{
type: 'invoices'
},
success: function(data)
{
// show a message saying it's been sent!
alert('Success!');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('Error!');
}
});
The response always seems to be something like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title></title>
</head>
<body>
{"aaData":[["2007-08-01","91109507","Invoice","10.000000","AUD"],["2007-08-02","91110103","Invoice","5.000000","AUD"],["2007-08-02","91110122","Invoice","305.000000","AUD"],["2007-08-02","91110129","Invoice","320.000000","AUD"],["2007-08-03","91111146","Credit
for Returns","10.000000","AUD"],["2007-08-06","91111895","Credit
for Returns","320.000000","AUD"],["2007-09-03","91128486","Credit
Memo","5.000000","AUD"],["2007-09-03","91128487","Credit
etc, etc
And according to the response header it certainly thinks it's JSON:
HTTP/1.1 200 OK
Content-Type: application/json
Server: Microsoft-IIS/7.5
X-Powered-By: PHP/5.3.3
Whenever I run the code and it alert "Error!" gets fired every time, which is understandable...
Anyone got any ideas why the HTML is being included in the response?

Calling header() actually has nothing to do with HTML-code being returned in the response.
header() is used to set HTTP-headers, while HTML-code (<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">) is sent in the body of HTTP response.
So the line of code
header("Content-type: application/json");
does his job correctly because response contains correct content type:
Content-Type: application/json
So what's wrong? Probably you have code that is executed before the code that deals with json. You should send only json encoded message in your response without any HTML tags and terminate the script using exit or die. Try to locate the code that sends HTML tags and put your code before it.

Ok, I found my own answer, looks like I had tidyhtml turned on inside my PHP.ini file, and had a
ob_start("ob_tidyhandler");
inside one of my global packages. Commented that out and it all works fine. Thanks for your time everyone!

Have you tried commenting the whole "header(...)"-part? It should work without it. The AJAX-call gets everything the PHP-program outputs, in this case including the header.

I feel somepart of your code is emitting the HTML DTD and the head part automatically for all responses from the php codebase. Are you using a framework ? If so which one ? The fact that the json.txt works is indicative that nothings wrong with js, browser or any proxies in between.
I suggest you debug the php code flow to see where this part is getting added to the html response.

There is probably something posting headers before you do. Can you provide more of the php code for this?Remember that a single white space outside of the php tags forces the output of headers ( http by default).

Related

Issue with displaying the Jquery Ajax response in HTML

I need to load a page where that page needs to display some values with a dynamic pagination. So to load the values I have a rest call, In that rest call I am returning a json object. In the browser console I am able to see the json output. Now My issue is I am getting the response on $document.ready() function. Now I am trying to display the json object values in the HTML which is not happening.
JavaScript:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url : "http://localhost:8080/school-service/school/list/students/1/1",
type: "GET",
dataType: "json",
}).done( function(studentList) {
console.log("AJAX request success:" +studentList.pageNumber);
}).fail( function(jqXHR, textStatus) {
console.log("AJAX request failed with status:" + textStatus);
});
});
</script>
HTML:
<img onclick='previousPage("${studentList.pageNumber}", "${studentList.pageCount}")' src="${context}/images/previous.png">
<c:forEach var="i" begin="1" end="${studentList.pageCount}">
${i}
</c:forEach>
<img onclick='nextPage("${studentList.pageNumber}", "${studentList.pageCount}")' src="${context}/images/next.png"/>
Can anyone please help me that how can I display the json response object value in HTML.
I think you can't because the code you want to replace in your page is belong to a server-side language (i guess asp) and server-side code will be compiled before javascript execution so you'll not found the tags those tags.
So, if I understand what you are trying to do, you are trying to get the value from your AJAX request and include the returned value from .done in the html?
If that is the case, check this link out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
If you are returning a JSON object from .done, you will need to parse the JSON object into a string in order to place it in the DOM. From that point, you will need to decide where it should be placed. For example, you can create a div and say $('that-div').append(returned value).
Another approach could be having a default value in the html, and on .done, replace the html by calling .html on your response. But to do that you will need to grab a reference of $(this).
I hope this helps, if not let me know where my gaps are and we can go over this in a different way.
The code which you write is a server side code with JSTL, and it is not available when the AJAX response is returned.
JSP page will be converted to HTML.
The HTML page will call the server by using AJAX.
The returned response is a JSON which is received in a Javascrip Object.
You need to do some javascrip work to make your a tags
You need to write some Javascript code to render the returned response.
Try this instead
int pageCount = studentList.pageNumber;
Then in your html simply do this
<c:forEach var="i" begin="1" end=studentList.pageNumber>
i
</c:forEach>

Parsing Json data in JQuery/Javascript

I saw a similar discussion here. But my returned data format is a bit different.
I have a Json string returned from server as shown below
<!DOCTYPE HTML>
<html>
<head>
<style>
</style>
</head>
<body>
{"error":false}</body>
</html>
I need to extract data "error":false from the Json string.
I tried as below
(1)Say the Json message is in result variable, then I checked as
if(result.error == false)
It doesn't work.
(2) I also used jQuery.parseJSON as discussed in this link.
It doesn't work also.
How can I parse Json data?
Json data is parsed in Jquery.ajax for the returned message as follow
jQuery.ajax({
url: "registrationdatavalidationatserver.php",
type: "POST",
data: $("form").serialize(), /*grab all elements in your form and serialize them */
success: function(result){
//To parse result
},
error: function(){
// the AJAX request failed as in timed out / bad url etc.
}
});
(3) How to return message from server just Json data without
<html>, <head>, <style>, etc. tags?
I returned from server as echo json_encode($data);
I have a Json string returned from server as shown below.
No, you need to have only the following returned from the server:
{"error": false}
Say the Json message is in result variable, then I checked as if(result.error == false)
It will never work because it is a HTML. Not a JSON.
How to return message from server just Json data without <html>, <head>
Even before you send the output, please make sure you are not sending anything to browser. Have these defined in the PHP headers:
<?php
header("Content-type: application/json");
die(json_encode($arrayData));
?>
There must not be anything other than this. It is wise to have a dedicated file for JSON output too, if you are confused in making this kind of setup.

Converting a PHP script into a JavaScript script which reads and prints XML data

I am trying to replace all of my PHP with JS (Node and ajax (and jQuery library)) but am having trouble converting the following PHP script into an ajax engine.
<?php
$xmlDoc=new DOMDocument();
$xmlDoc->load("Administration/data/people.xml");
$xx=$xmlDoc->getElementsByTagName('person');
$hintt="";
for($ii=0; $ii<($xx->length); $ii++)
{
$yy=$xx->item($ii)->getElementsByTagName('id');
$zz=$xx->item($ii)->getElementsByTagName('fullName');
if ($yy->item(0)->nodeType==1)
{
echo "<button type='button' class='mybutton' name='users'>" .
$zz->item(0)->childNodes->item(0)->nodeValue . "</button>";
}
}
?>
Here is my ajax attempt:
<div id="loadMe">
<h1>Reading..</h1>
</div>
<script>
$.ajax({
type: "GET",
url: "Administration/data/people.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('person').each(function(){
var fullName = $(this).attr('fullName');
$("<button type=button class=mybutton value='+fullName+'></button>").html("<h3>'+fullName+'</h3>").appendTo('#loadMe');
});
}
});
</script>
To me, it looks pretty similar, but the JS is not working. Anyone see an inconsistency or can tell me why my XML elements are not appending to the indicated div tag? Thanks a lot in advance guys and gals!
EDIT (1/24/14 1:24 AM):
I thought providing my XML would be helpful, perhaps I am referencing the data wrong?
<people>
<person>
<id>10</id>
<fullName>Philadelphia Collins</fullName>
<firstName>Philadelphia</firstName>
<lastName>Collins</lastName>
<age>62</age>
<hometown>Sunnyvale</hometown>
<job>Restraunt Owner</job>
</person>
<people>
I've set up a test page that you can try and play around with if at any time you need to do more exploring. So here comes the solution.
First, I tried doing an AJAX request, which always came back as failed because the XML was invalid. If I just tried to access the XML, it said it was not valid and could not be displayed. The issue was the closing <people> tag was missing a /. It should be </people>'. So that fixed the AJAX request failing. The next part was parsing the XML response. I did this by using the.children()method in jQuery and then getting the text of the element with.text()`. It ends up looking something like this:
var fullName = $(this).children('fullName').text();
So with all that and anything else I may have missed but is available at the test page, I hope you can fix your issue and get a successful AJAX request going. If I missed anything or I wasn't clear, let me know and I'll try to explain a little more.
By the way, doing console.log(); in Chrome DevTools and using breakpoints to access the data myself always helps me see what I'm working with, that way I know how to go about getting what data I want from a request.
Good luck!

Handling dynamic HTTP Content-Type with jquery Ajax

I have a perl script URL which gives me a ZIP file, it processes the data and dynamically set the Content-Type to 'application/zip' in the http-header.
Perl code looks like this:
WPHTTPResponse::setHeader( 'Content-disposition', 'attachment;filename="test.zip"');
WPHTTPResponse::setHeader( 'Content-type', 'application/zip');
print $result;
In frontend, I am using this script direct in HREF:
Download
But I have a requirement of showing an alert message if $result is NULL in perl script.
What I am thinking is: I will send the file with Content-Type=>application/zip if the $result if not null, otherwise I will send the JSON response with error message that there is no file to download.
For this I would need to dynamically check the content type using JS:
$.ajax({
url: '/script',
data: {....},
success: function(response) {
if(response.contentType == 'application/zip'){
//download using javascript
}
else{
$.parseJSON(response);
alert(response.msg);
}
}
});
I'd appreciate any help.
Although your method should work, this is a case where using using HTTP error codes would probably be a good choice.
Depending on why $result is null one of these should be appropriate.
400 Bad Request
406 Not Acceptable
410 Gone
This would make your code slightly more 'obvious' as you would be using the HTTP status for exactly what it was meant for, rather than re-implementing the exact same thing in a proprietary way in your code. IMHO it would also make your code a bit easier to maintain as it would separate the success from the error.
You can still include JSON as part of the error response, to be able display information about exactly why the request didn't result in any data being returned to the client.
btw I'd avoid using 404 as the error code, even though it is technically the most 'appropriate' code just because it would cause confusion if a real 404 error occurred.
Use HEAD-request for check content size before download.
Client-side:
Attach click-event handler to <a>-element.
On click-event send HEAD-request throw XHR.
On XHR-response check content size.
If size is zero, then show alert and prevent default event handler.
If size is not zero, nothing to do.
Server-side:
Compute content size on HEAD-request.

Jquery Ajax doesnt work

I have the following div in my html
<div class="result">loading</div>
And my javascript is as follows.
$(document).ready(function() {
$.ajax({
accept: 'application/rss+xml',
url: 'http://www.madhyamam.com/taxonomy/term/19/rss.xml',
success: function(data) {
$('.result').html(data);
}
});
});
But for some reasons.. it doesnt seems to work.
In jsfiddle
XML returned(firebug):
XML Parsing Error: no element found Location:
moz-nullprincipal:{9ec69805-af82-4f95-979a-f8e68d415124} Line Number
1, Column 1:
^
Solution
*I bye-passed the problem using yahoo pipe. And it worked fine.*
You can't make Ajax requests to URLs that have not the same domain, port and protocol as the current page. The Same Origin Policy forbids it.
The most common workaround is having a server-side script that pulls the content, and serves it through Ajax.
As Pekka mentioned, we guess your problem is that Ajax cannot make request on other domain URLs. You have to use server-side script for that.
Example of small php server-side script for testing (from Jquery Minime Feed library):
<?php
header('Content-type: text/xml; charset=utf-8');
$url = htmlspecialchars($_GET['url']);
echo file_get_contents('http://'.$url,0);
?>
Then you can call something like
$.ajax({
accept: 'application/rss+xml',
url: 'http://youserver/getfeed.php?url=http://www.madhyamam.com/taxonomy/term/19/rss.xml',
});
However, it seems you want to show rss feed in your page. I went to same issue and ended using Jquery Minime Feed library, which help you doing the job:
$('#test1').minimeFeed('http://index.hu/24ora/rss/');
Automatically use server-side script if needed, and produce quite nice output. See demo here

Categories

Resources