Read XML from RSS using JavaScript - javascript

I'm trying to read a RSS from this URL http://www.vworker.com/RentACoder/misc/LinkToUs/RssFeed_newBidRequests.asp?blnAllOpen=true using JavaScript. I'm trying to XMLHttpReq to do it but its not working.
url="http://www.vWorker.com/RentACoder/misc/LinkToUs/RssFeed_newBidRequests.asp?blnAllOpen=true";
var xmlhttp = null;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
if ( typeof xmlhttp.overrideMimeType != 'undefined')
{
xmlhttp.overrideMimeType('text/xml');
}
}
else if (window.ActiveXObject)
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert('Perhaps your browser does not support xmlhttprequests?');
}
xmlhttp.open('GET', url, true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
alert("success");
}
else
{
alert("failure");
}
};

You're being limited by same origin restrictions. Could you build an intermediary (like a php script on your domain that would pull in the RSS?) then you'd change your url to that script
<?php
$x=file_get_contents('http://www.vworker.com/RentACoder/misc/LinkToUs/RssFeed_newBidRequests.asp?blnAllOpen=true');
echo $x;
?>

Related

How to send a string to php with POST [duplicate]

This question already has answers here:
Send POST data using XMLHttpRequest
(13 answers)
Closed 8 years ago.
I'm sending a string via xmlhttp in javascript using the following code:
function SendPHP(str, callback) {
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callback(xmlhttp.responseText); //invoke the callback
}
}
xmlhttp.open("GET", "testpost.php?q=" + encodeURIComponent(str), true);
xmlhttp.send();
}
and some test php:
$q = $_GET['q'];
echo $q;
That worked fine until I started sending a larger string in which case I get the "HTTP/1.1 414 Request-URI Too Long" error.
After a bit of research I found out I need to use "POST" instead. So I changed it to:
xmlhttp.open("POST", "sendmail.php?q=" + str, true);
And:
$q = $_POST['q'];
echo $q;
But this does not echo anything when using POST. How can I fix it so it works like when I was using GET but so it can handle a large string of data?
edit I'm now trying it with:
function testNewPHP(str){
xmlhttp = new XMLHttpRequest();
str = "q=" + encodeURIComponent(str);
alert (str);
xmlhttp.open("POST","testpost.php", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
alert (xmlhttp.responseText);
}
}
};
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(str);
}
You should not provide your href with URL parameters, instead of this you should send() them. For addition, you should always encode your parameters with encodeURIComponent() (At least when your request is using the Content-type "application/x-www-form-urlencoded").
your javascript function :
function testNewPHP(){
var str = "This is test";
xmlhttp = new XMLHttpRequest();
str = "q=" + encodeURIComponent(str);
alert (str);
xmlhttp.open("POST","testpost.php", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
alert (xmlhttp.responseText);
}
}
};
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(str);
}
javascript :
function testNewPHP(){
var str = "This is test";
xmlhttp = new XMLHttpRequest();
str = "q=" + encodeURIComponent(str);
alert (str);
xmlhttp.open("POST","testpost.php", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
alert (xmlhttp.responseText);
}
}
};
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(str);
}
testpost.php in your home directory :
<?php
var_dump($_POST);
OUTPUT :
array(1) {
["q"]=>
string(12) "This is test"
}

How can I send more than one variable to a php file using ajax and a get request?

I am trying to send an I.D. value and a name value to a php file using ajax. I can send just the I.D. variable just fine but when I try to add the name variable, the function stops working. How can I send both?
This works:
function click() {
var name = clickedelement.getElementsByTagName('input')[0].value;
var id = clickedelement.getElementsByTagName('input')[1].value;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("popupBox").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "friends2.php?id="+id, true);
xmlhttp.send();
};
But when I try to add the name variable, it dosnt work.
function click() {
var name = clickedelement.getElementsByTagName('input')[0].value;
var id = clickedelement.getElementsByTagName('input')[1].value;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("popupBox").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "friends2.php?id="+id"&name="+name, true);
xmlhttp.send();
};
change to "friends2.php?id="+id+"&name="+name you just have a missing +
"friends2.php?id="+id+"&name="
// missing plus sign here ^

AJAX retrieving xml response

I have 2 .jsp pages.
The 1. one contains just a xml structure for applicants:
<% response.setContentType("text/xml") ; %>
<applicant>
<citizenship>GERMANY</citizenship>
<residence>Inc.</residence>
<street>9500 Gilman Drive</street>
<city>La Jolla</city>
<state>USA</state>
<countryTelCode>Vandelay Industries</countryTelCode>
<zipCode>Inc.</zipCode>
<areaCode>9500 Gilman Drive</areaCode>
<telNumber>La Jolla</telNumber>
<major>USA</major>
<awarded>Vandelay Industries</awardeds>
<gpa>Inc.</gpa>
<specialization>9500 Gilman Drive</specialization>
</applicant>
The second one tries to retrieve GERMANY from the tag and print it in the "..." field of:
<span id="Citizenship">...</span>
using this code after calling showCustomer():
<script type="text/javascript">
function showCustomer() {
var xmlHttp;
xmlHttp = new XMLHttpRequest();
if (xmlHttp == null) {
alert("Your browser does not support AJAX!");
return;
}
var url = "getApplicant_xml.jsp";
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
var xmlDoc = xmlHttp.responseXML.documentElement;
document.getElementById("Citizenship").innerHTML = xmlDoc.getElementsByTagName("citizenship")[0].childNodes[0].nodeValue;
}
}
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
}
</script>
Unfortunately it does not print anything....
I would be really thankful if someone finds my mistake.
Thank you
Your problem is that xmlHttp.responseXML is null. You need to parse a new DOM object from xmlHttp.responseText. I fixed the code.
<script type="text/javascript">
function showCustomer() {
var xmlHttp;
xmlHttp = new XMLHttpRequest();
if (xmlHttp == null) {
alert("Your browser does not support AJAX!");
return;
}
var url = "getApplicant_xml.jsp";
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
var xmlDoc = xmlHttp.responseText;
xmldom = (new DOMParser()).parseFromString(xmlDoc, 'text/xml');
text = xmldom.getElementsByTagName("citizenship")[0];
document.getElementById("Citizenship").innerHTML = text.childNodes[0].nodeValue;
}
};
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
};
</script>

Using XMLHttpRequest for Mozilla Extension development

I have some problems of calling a php file using Ajax in my
Mozilla Extension.
The javascript (Ajax) and php are both located at directory /myextension/content, I am call the php using
function ajaxFunction(){
var req = new XMLHttpRequest();
req.open('GET', 'myphp.php', true);
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if(req.status == 200)
alert(req.responseText);
else
alert("Error\n");
}
};
req.send(null);
}
, and my php looks like
<? php
echo "Server Received with thanks!";
?>
I keep geting "alert("Error\n");".
Did i do anything wrong?
Well formatted Ajax code for Firefox:
var URL="http://yourdomain.com/Work.php?val=Test";
var objXmlHttp = null;
try
{
objXmlHttp = new XMLHttpRequest();
}
catch(e)
{return;}
objXmlHttp.onreadystatechange=function()
{
if ((objXmlHttp.readyState == 4 || objXmlHttp.readyState == "complete") && objXmlHttp.status == 200)
{
//Write code for success
}
else if (objXmlHttp.status == 404)
{
//OnError
}
else
{
//OnWait
}
}
objXmlHttp.open("GET", URL, true);
objXmlHttp.send(null);

How can I re-write this code without jQuery?

How can I rewrite this code without using jQuery? I need to do it in a mobile app where I can't use jQuery.
$.ajax({
type: "POST",
url:"../REST/session.aspx?_method=put",
data: JSON.stringify(dataObject, null,4),
cache: false,
dataType: "json",
success: onSuccessLogin,
error: function (xhr, ajaxOptions){
alert(xhr.status + " : " + xhr.statusText);
}
});
You can try this:
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status != 200) {
// What you want to do on failure
alert(xmlhttp.status + " : " + xmlhttp.responseText);
 }
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// What you want to do on success
onSuccessLogin();
}
}
xmlhttp.open("POST", "../REST/session.aspx?_method=put", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Cache-Control", "no-cache"); // For no cache
xmlhttp.send("data=" + JSON.stringify(dataObject, null,4));
As for how to do more stuff with only javascript without jQuery library take a look at W3Schools AJAX Tutorial or Mozilla - Using XMLHttpRequest
And as duri said, you will have to find a way to convert dataObject to string, as not all browsers support JSON object.
try this
var xmlHttp = createXmlHttpRequestObject();
//retrieves the xmlHttpRequest Object
function createXmlHttpRequestObject()
{
//will store the refrence to the xmlHttpRequest Object
var xmlHttp;
//if running in internet explorer version below 7
if(window.ActiveXObject)
{
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
xmlHttp = false;
}
}
else
{
try{
xmlHttp = new XMLHttpRequest();
}
catch(e){
xmlHttp = false;
}
}
if(!xmlHttp)
alert("Error Creating the xmlHttpObject");
else
return xmlHttp;
}
function callThisFunction()
{
if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
{
var queryString = JSON.stringify(dataObject, null,4);
var url = "../REST/session.aspx?_method=put";
xmlHttp.open("POST", url, true);
//Send the proper header information along with the request
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", queryString.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = checkHandleServerResponse;
xmlHttp.send(queryString);
}
}
function checkHandleServerResponse()
{
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200)
{
var JSONFile = 'jsonFormatData = '+xmlHttp.responseText;
eval(JSONFile);
if(jsonFormatData.description == 'Success')
{
//showDialog('Success','Login Successful','success',3);
location.href='default.aspx';
//setTimeout(function(){location.href='myGrupio.php';},3000);
}
else
showDialog('Error','You Need a Valid Login.','error',3);
}
else if(xmlHttp.status == 400)
{
setTimeout( function()
{
alert('you have error');
},3000);
}
else
alert("Error Code is "+xmlHttp.status)
}
}
For the Ajax request itself, have a look at the XMLHttpRequest object (special treatment for IE).
To parse the JSON response (dataType: 'json'), use JSON.parse (you might need the json2.js library).
jquery is already javascript. It's a library, entirely written in javascript. So you can use it within every javascript project. If you want to write a rest client yourself, you might look at this article
You may also consider using jQuery Mobile edition - very light - 17KB minified. 1.0 is alpha now, but I think it will be more stable and portable than self-baked code.

Categories

Resources