XML Parsing Error: junk after document element when fetching RSS feed - php

I am trying to fetch the RSS feed document from rss.news.yahoo.com/rss/topstories using Ajax, extract the values associated with the 'titles' tags and echo them to the screen. xmlget.htm implements Ajax via GET request.
xmlget.php uses the PHP function file_get_contents to load in the web page at the URL supplied to it in the GET variable $_GET['url'] and display the 'title' tags on the screen.
The error I get is this:
XML Parsing Error: junk after document element Location: moz-nullprincipal:{2f186a54-8730-4ead-9bf9-f82c8d56ad8f} Line Number 2, Column 1:
xmlget.htm
<html>
<head>
<title>Ajax Example</title>
</head>
<body>
<h1 style="text-align: center;">Loading a web page into a DIV</h1>
<div id='info'>This sentence will be replaced</div>
<script>
nocache = "&nocache="+Math.random()*1000000
url = "rss.news.yahoo.com/rss/topstories"
request = new ajaxRequest()
request.open("GET","xmlget.php?url="+url+nocache,true)
out = "";
request.onreadystatechange = function(){
if(this.readyState == 4){
if(this.status == 200){
if(this.responseXML != ""){
titles = this.responseXML.getElementsByTagName('title')
for (j = 0 ; j < titles.length ; ++j)
out += titles[j].childNodes[0].nodeValue + '<br />'
document.getElementById('info').innerHTML = out
}
else alert("Ajax error: No data received")
}
else alert( "Ajax error: " + this.statusText)
}
}
request.send(null)
function ajaxRequest(){
try{
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e1){
try{
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e2){
try{
request = new XMLHttpRequest()
} catch (e3){
request = false
}
}
}
return request
}
</script>
</body>
xmlget.php
<?php
if(isset($_GET['url'])){
function SanitizeString($var) {
$var = strip_tags($var);
$var = htmlentities($var);
return stripcslashes($var);
}
header('Content-Type: text/xml');
echo file_get_contents("http://www.".SanitizeString($_GET['url']));
}
?>

please add the following line in the head
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=UTF-8" />

Found the problem!
The file_get_contents function was unable to find the host because the url was invalid. rofl...
INCORRECT
echo file_get_contents("http://www.".SanitizeString($_GET['url']));
CORRECT
echo file_get_contents("http://".SanitizeString($_GET['url']));

Related

Parsererror when Using Jquery Ajax To Get MYSQL Data From PHP

JQuery
function save() {
imageData = $(".sigPad").signaturePad().getSignatureImage();
consumeData = $('#consume').val();
$.ajax({
type: "POST",
url: "",
data: {'signatureasimage' : imageData, 'consume' : consumeData },
dataType: 'json',
cache: false,
success: function(response){
alert(response.msg);
/*var imageUrl = response['signature_image'];
d = new Date();
$(".signatureImage").attr("src",imageUrl);
if (response.status == true) {
window.location.href = "<?php echo ROOT_URL.'esignup/attendees_list.php?icode='.$icode;?>";
}*/
},
error: function(x,e){
if(x.status==0){
alert('You are offline!!\n Please Check Your Network.');
}else if(x.status==404){
alert('Requested URL not found.');
}else if(x.status==500){
alert('Internel Server Error.');
}else if(e=='parsererror'){
alert('Error.\nParsing JSON Request failed.');
}else if(e=='timeout'){
alert('Request Time out.');
}else {
alert('Unknow Error.\n'+x.responseText);
}
}
});
};
PHP
$data = array();
$confirmationData = array();
$data['attendee_id'] = $attendeeId;
$data['is_consume_the_provided_meal'] = $_POST['consume'];
$data['signature_image'] = $destination;
$data['confirmed'] = 1;
if($confirmedAttendee){
$sql = "SELECT * FROM `".TBL_ATTENDEE_CONFIRMATION."` WHERE `attendee_id` = '.$attendeeId.'";
$confirmationData = selectFrom($sql);
update_array('tbl_attendee_confirmation', $data, array('attendee_id' => $attendeeId));
$confirmationData = selectFrom($sql);
}else{
var_dump("it went through insert array");
insert_array('tbl_attendee_confirmation', $data);
}
$data = array();
$data['msg']="Testing, testing.";
echo json_encode($data);
Jquery ajax does post request with data imageData and consumeData. imageData and consumeData are strings. Copying to file works and the data updates the table. The problem is I get parsererror when I want to get imageUrl so I can update the sigImage with the new image source. I commented the part where I replace the image src with new imageURL. Does anyone know the issue?
Error shows up as "alert('Error.\nParsing JSON Request failed.');" from code. Error still shows up with test code.
Try doing this in your PHP:
echo json_encode($data, JSON_FORCE_OBJECT);
I don't completely understand it, but in my experience if you are returning an array you've built in PHP to be parsed using the ECMAScript JSON object, you need to use the JSON_FORCE_OBJECT constant to ensure that it returns a JSON object instead of a JSON array.
json_encode constants
You also could try outputting the header for JSON before echoing your JSON encoded array, gimme a sec.
header('Content-Type: application/json');
Also here

passing a javascript variable to PHP with xmlhttprequest

Im having problem Posting a javascript variable to a php file. Please would someone tell me what's going on?
// Get Cookies
var getCookies = document.cookie;
cookiearray = getCookies.split(';');
SelectedIds = cookiearray[0];
//take key value pair
name = cookiearray[0].split('=')[0];
value = cookiearray[0].split('=')[1]; // The variable(values) i want to pass
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
hr.open("POST", url, true);
var url = "page.php";
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("Comp").innerHTML = return_data;
}
}
hr.send(value); // Request - Send this variable to PHP
document.getElementById("Comp").innerHTML = "loading...";
PHP
$test = $_POST['value'];
print_r($test); // NULL
Thanks
Instead of
print_r($test);
use the echo
echo $test;
As $test is not an array is a string value. print_r is used to print the array. that's why is given the null value.
And your send function in ajax should be like this:
hr.send("value="+value);
In the send function, the parameter that passed must be a string like this:
"name=value&anothername="+encodeURIComponent(myVar)+"&so=on"
More tutorial is here.
I've been trying work out, for sometime, how to pass quite a long string I have formatted in javascript into php to save in a file and I think I now have the answer. At least it works for me.
The variable 'str' is passed into 'getGame' from another function after it has been formatted. I am using the 'POST' method as the string can get quite long.
The code is:-
function getGame(str){
//Sends data to the php process "save Game".
var test = str;
var xhr = new XMLHttpRequest();
xhr.open("POST", "saveGame.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (this.readyState === 4 ){
alert(xhr.responseText);
}
};
xhr.send("data="+ test);
}
This sends the "data" to "saveGame.php where it is saved to a file as in the following code and returns a messsage in the alert dropdown.
<?php
$outputString = $_POST["data"];
$fp = fopen("C:\\xampp\\htdocs\\BowlsClub\\GamesSaved\\test26.txt","w");
if (!$fp){
$message = "Error writing to file. Try again later!" ;
}else{
fwrite($fp, $outputString);
$message = "File saved!";
}
fclose($fp);
echo $message;
?>
This works for me and I hope it is useful to other newbies.

Get ID from url php

This is my url
http://localhost:8888/App.php#?ID=1S
I needed the 1S as a variable for using it with a query.
If you want to parse URL as string:
$str = 'http://localhost:8888/App.php#?ID=1S';
$temp = explode( "?", $str );
$result = explode( "=", $temp['1'] );
echo $result['1'];
Demo
If you want to get it on server side:
Hash value is not sent to server side. So it impossible to get it on server side but you can use javascript to do some trick.
Can I read the hash portion of the URL on my server-side application (PHP, Ruby, Python, etc.)?
Using JavaScript/jQuery: (tags are not added though)
<script>
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('#') + 1).split('&');
hash = hashes[0].split('=');
alert( hash['1'] );
// you can use jQuery.ajax() here to send this value to server side.
</script>
Get hash value & pass from javascript to php
echo parse_url('http://localhost:8888/App.php#?ID=1S', PHP_URL_FRAGMENT);
OR
echo parse_url($_SERVER['QUERY_STRING'], PHP_URL_FRAGMENT);
If you need to parse it further:
$x = parse_url($_SERVER['QUERY_STRING'], PHP_URL_FRAGMENT);
parse_str($x, $arr);
echo $arr['ID']
$url = "http://localhost:8888/App.php#?ID=1S&another=3";
$a = parse_url($url);
parse_str($a["fragment"],$arr);
print_r($arr);
outputs:
Array (
[?ID] => 1S
[another] => 3
);
if you can live accessing the first parameter with "?ID"
I guess that the only way to do this is by an AJAX request, here is a simplified example:
the index page
<!doctype html>
<html>
<head>
<title>Website</title>
<script type="text/javascript">
var url = document.location;
url = url.toString();
var getVal = url.split("#");
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'App.php'+getVal[1], true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.send();
</script>
</head>
<body>
</body>
</html>
the App.php page
<?php
if (isset($_GET['url'])) echo 'url : ' . $_GET['url'];
?>

Call PHP SOAP web service from JQuery (Ajax)

I have a PHP SOAP web service acting as a relay to call cross domain web services. The problem I'm having is calling my local PHP web service methods from JavaScript (using JQuery/Ajax). I want to call a specific method in my web service; e.g. "LoginToAccount";
I'm NOT interested in appending params in the url and then figuring out which method to call... This is very straight forward in .NET (mywebservice.asmx/LoginToAccount") but can't figure it out how to get this to work in PHP.
I continually get a "500 Internal Server Error" of "Bad Request":
Bad Request
Here is my PHP code:
<?php
function LoginToAccount($email, $passCodeHash) {
//...code calling cross-domain web services
return $jsonEncodedResponse;
}
function CreateAccount($email, $passCodeHash){
//...code calling cross-domain web services
return $jsonEncodedResponse;
}
$server = new SoapServer(null, array('uri' => "http://www.myurl/webservices/"));
$server->addFunction('LoginToAccount');
$server->addFunction('CreateAccount');
$server->handle();
?>
Here is my JavaScript code:
function AjaxCall() {
$.ajax({
type: "POST",
url: "phpRelay.php/LoginToAccount",
data: "{email : 'myEmail#email.com', passCodeHash: '12345'}",
contentType: "application/json",
dataType: "json",
success: succeeded,
error: queryError
});
}
function succeeded(data, textStatus, request) {
var result = $.parseJSON(data.d);
}
function queryError(request, textStatus, errorThrown) {
alert(request.responseText, textStatus + " " + errorThrown);
}
This is all on the same domain. Thanks!
instead of of using php soapserver you can replace it with the following code:
echo $data = (function_exists($_SERVER['QUERY_STRING'])) ? json_encode(array('d'=>$_SERVER['QUERY_STRING'](file_get_contents('php://input')))) : 'error: function does not exists';
what it does is use the query_string as the function name. it first check if the function exists, if not the error is printed, but if et exists it calls the function with the posted data as criteria, in string format. and in the end, the returned data from the function is printed as a json array with the result set as d.
so your javascript should be as follows (note the url call should be with ? instead of / before the function):
function AjaxCall() {
$.ajax({
type: "POST",
url: "phpRelay.php?LoginToAccount",
data: "{email : 'myEmail#email.com', passCodeHash: '12345'}",
contentType: "application/json",
dataType: "json",
success: succeeded,
error: queryError
});
}
function succeeded(data, textStatus, request) {
var result = $.parseJSON(data.d);
}
function queryError(request, textStatus, errorThrown) {
alert(request.responseText, textStatus + " " + errorThrown);
}
hope this can help you! I know it is a bit late to post this, but i posted it if there is anybody else that needed something like this! I needed it and could not any solution like this, so i had to make the solution myself.
cheers
c_bb
I have tried SOAP PHP server with ajax client and found working code
First Download nusoap library from Here
then create server.php
<?php
//call library
require_once ('lib/nusoap.php');
// Define the TriangleArea method as a PHP function
function TriangleArea($b, $h) { return 'The triangle area is: ' .(($b*$h)/2); }
// Define the RectangleArea method as a PHP function
function RectangleArea($L, $l) { return 'The rectangle area is: ' .($L*$l); }
// create the function
function get_message($your_name)
{
if(!$your_name){
return new soap_fault('Client','','Put Your Name!');
}
$result = "Welcome to ".$your_name .". Thanks for Your First Web Service Using PHP with SOAP";
return $result;
}
//using soap_server to create server object
$server = new soap_server;
// Initialize WSDL support
$server->configureWSDL('mathwsdl', 'urn:mathwsdl');
// Register the TriangleArea method
$server->register('TriangleArea', // method name
array('b' => 'xsd:int', 'h' => 'xsd:int'), // input parameters
array('area_t' => 'xsd:string'), // output parameters
'urn:mathwsdl', // namespace
'urn:mathwsdl#TriangleArea', // soapaction
'rpc', // style
'encoded', // use
'1=> : Calculate a triangle area as (b*h)/2' // documentation
);
// Register the RectangleArea method to expose
$server->register('RectangleArea', // method name
array('L' => 'xsd:int', 'l' => 'xsd:int'), // input parameters
array('area_r' => 'xsd:string'), // output parameters
'urn:mathwsdl', // namespace
'urn:RectangleAreawsdl#RectangleArea', // soapaction
'rpc', // style
'encoded', // use
'2=> : Calculate a rectangle area as (L*l)' // documentation
);
// Register the RectangleArea method to expose
$server->register('get_message', // method name
array('nm' => 'xsd:string'), // input parameters
array('area_r' => 'xsd:string'), // output parameters
'urn:mathwsdl', // namespace
'urn:get_messagewsdl#get_message', // soapaction
'rpc', // style
'encoded', // use
'3=> : Print a Message as name' // documentation
);
if ( !isset( $HTTP_RAW_POST_DATA ) ) $HTTP_RAW_POST_DATA =file_get_contents( 'php://input' );
$server->service($HTTP_RAW_POST_DATA);
// create HTTP listener
//$server->service($HTTP_RAW_POST_DATA);
exit();
?>
after that create client.php
<?php
require_once ('lib/nusoap.php');
//Give it value at parameter
$param = array( 'your_name' => 'Monotosh Roy');
//Create object that referer a web services
$client = new soapclient('http://localhost:81/WebServiceSOAP/server.php?wsdl', true);
// Check for an error
$err = $client->getError();
if ($err) {
// Display the error
echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
// At this point, you know any calls to
// this web service's methods will fail
}
// Call the TriangleArea SOAP method
$result = $client->call('TriangleArea',
array('b' => 10, 'h' => 15));
// Check for a fault
if ($client->fault) {
echo '<h2>Fault</h2><pre>';
print_r($result);
echo '</pre>';
} else {
// Check for errors
$err = $client->getError();
if ($err) {
// Display the error
echo '<h2>Error</h2><pre>' . $err . '</pre>';
} else {
// Display the result
echo '<h2>Result</h2><pre>';
print_r($result);
echo '</pre>';
}
}
// Call the RectangleArea SOAP method
$result = $client->call('RectangleArea',
array('L' => 40, 'l' => 20));
// Check for a fault
if ($client->fault) {
echo '<h2>Fault</h2><pre>';
print_r($result);
echo '</pre>';
} else {
// Check for errors
$err = $client->getError();
if ($err) {
// Display the error
echo '<h2>Error</h2><pre>' . $err . '</pre>';
} else {
// Display the result
echo '<h2>Result</h2><pre>';
print_r($result);
echo '</pre>';
}
}
// Display the request and response
/* echo '<h2>Request</h2>';
echo '<pre>' . htmlspecialchars($client->request,
ENT_QUOTES) . '</pre>';
echo '<h2>Response</h2>';
echo '<pre>' . htmlspecialchars($client->response,
ENT_QUOTES) . '</pre>';*/
//Call a function at server and send parameters too
$response = $client->call('get_message',$param);
//Process result
if($client->fault)
{
echo "<h2>FAULT:</h2> <p>Code: (".$client->faultcode."</p>";
echo "String: ".$client->faultstring;
}
else
{
echo $response;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8">
<title>Web Service SOAP and AJAX</title>
</head>
<script type="text/javascript" src="ajaxSOAP.js"></script>
<body>
<div style="position:relative;left:0px;
top:-12px;background-color:#1D3968;margin:0px;">
<h2 align="center"><font color="#ffffff">
Consume WebServices through SOAP-AJAX calls</font></h2></div>
<table align="center" cellpading="0px" cellspacing="3px"
bordercolor="#000000" border="0"
style="position:relative;width:300px;height:200px;">
<tr>
<td colspan="2" align="center"><h1>Rectangle Area</h1></td>
</tr>
<tr>
<td valign="center"><font color="#cc0000" size="3">
Insert value for l:</font></td>
<td><input id="l_id" type="text"></td>
</tr>
<tr>
<td><font color="#cc0000" size="3">Insert value for L:</font></td>
<td><input id="L_id" type="text"></td>
</tr>
<tr>
<td><input type="button" value="Calculate Area" onclick="myAjax();"></td>
</tr>
<tr>
<td colspan="2">
<div id="resultDiv"></div>
</td>
</tr>
</table>
</body>
</html>
ajaxSOAP.js file contains
var xhrTimeout=100;
function myAjax(){
var l_var = document.getElementById("l_id").value;
var L_var = document.getElementById("L_id").value;
var soapMessage ='<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="urn:mathwsdl"> <SOAP-ENV:Body><tns:RectangleArea xmlns:tns="urn:mathwsdl"><L xsi:type="xsd:int">'+L_var+'</L><l xsi:type="xsd:int">'+l_var+'</l></tns:RectangleArea></SOAP-ENV:Body></SOAP-ENV:Envelope>';
var url='http://localhost:81/WebServiceSOAP/server.php';
if(window.XMLHttpRequest) {
httpRequest=new XMLHttpRequest();
}
else if (window.ActiveXObject) {
httpRequest=new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.open("POST",url,true);
if (httpRequest.overrideMimeType) {
httpRequest.overrideMimeType("text/xml");
}
httpRequest.onreadystatechange=callbackAjax;
httpRequest.setRequestHeader("Man","POST http://localhost:81/WebServiceSOAP/server.php HTTP/1.1")
httpRequest.setRequestHeader("MessageType", "CALL");
httpRequest.setRequestHeader("Content-Type", "text/xml");
httpRequest.send(soapMessage);
}
function callbackAjax(){
try {
if(httpRequest.readyState==4) {
if(httpRequest.status==200) {
clearTimeout(xhrTimeout);
resultDiv=document.getElementById("resultDiv");
resultDiv.style.display='inline';
resultDiv.innerHTML='<font color="#cc0000" size="4"><b>'+httpRequest.responseText+'</b></font>';
}
}
} catch(e) {
alert("Error!"+e);
}
}

IE8 and reading XML via AJAX

I have a store locator, built using Google Maps, PHP/Mysql and jQuery here:
http://tinyurl.com/4w8nwwp
Everything is dandy in FF, Safari,Chrome and Opera.
IE7, 8 cannot read the XML that is dynamically generated by parse_location.php
The AJAX code:
function reloadMap(map, dataString) {
markersArray = [];
var infoWindow = new google.maps.InfoWindow({content: "loading...", maxWidth:100});
var storeListHtml = '<h2>Name <span style="margin-left:252px;">Address</span></h2><ul>';
$.ajax({
type: "GET",
url: "parse_location.php",
data: dataString,
success: function(text){
count = -1;
$(text).find("list").each(function()
{
count++;
if(count == 0)
{
var burnsvilleMN = new google.maps.LatLng($(this).attr("lat"),$(this).attr("lng"));
map.panTo(burnsvilleMN);
}
var store = [$(this).attr("name"), $(this).attr("address"), $(this).attr("lat"), $(this).attr("lng"), count];
var name = $(this).attr("name");
var address = $(this).attr("address");
var point = new google.maps.LatLng($(this).attr("lat"),$(this).attr("lng"));
var html = "<span class='info'><b>" + name + "</b> <br/>" + address + "</span>";
var image = new google.maps.MarkerImage('images/icon_dot2.png');
var shadow = new google.maps.MarkerImage('images/icon_dot_shadow.png');
var marker = new google.maps.Marker({
map: map,
position: point,
icon: image,
shadow:shadow
//shadow: icon.shadow
});
//markersArray.push(marker);
storeListHtml += "<li class='store'><a href='javascript:myclick("+count+")'><div class='store-name'>"+name+"</div><div class='store-add'> "+address+"</div></a></li>";
bindInfoWindow(marker, map, infoWindow, html);
});
storeListHtml += '</ul>';
$("#store-list").html(storeListHtml);
}
});
}
As you can see, this involves calling parse_location.php, getting the XML generated by this code:
// uncommenting the following line causes ff, safari et al to not show anything.
// header('Content-Type: text/xml; charset=UTF-8');
$responce = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
$responce .= "<location>\n";
$city = $_GET['city'];
$category = $_GET['category'];
[SQL Query here ]
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
$responce .= "<list name=\"".$row["name"]."\"
address=\"".$row["street_address"]." ".$row["city"]." ".$row["state"].", ".$row["zip"]."\"
lat=\"".$row["lat"]."\"
lng=\"".$row["lng"]."\" />";
}
$responce .= "</location>";
$responce8 = utf8_encode($responce);
echo $responce8;
Any pointers???
Rishi
Add a Content-Type header to your php code like this:
header('Content-Type: text/xml'); // Try "application/xml" too
Also, adding another IE-specific header might help:
header('X-Content-Type-Options: nosniff');
You need to do this before outputting anything else of course, since they are headers.

Categories