I've been pulling my hair out trying to use jQuery.get() to pull in my dynamically generated RSS feed and I'm having nothing but issues, is my RSS feed the wrong format? If so can I convert it to the correct format using javascript?
Here's my feed: http://dev.chriscurddesign.co.uk/burns/p/rc_rss.php?rcf_id=0
Here's my code:
function get_rss_feed() {
$(".content").empty();
$.get("http://dev.chriscurddesign.co.uk/burns/p/rc_rss.php?rcf_id=0", function(d) {
var i = 0;
$(d).find('item').each(function() {
var $item = $(this);
var title = $item.find('title').text();
var link = $item.find('link').text();
var location = $item.find('location').text();
var pubDate = $item.find('pubDate').text();
var html = '<div class="entry">' + title + '</div>';
$('.content').append(html);
i++;
});
});
};
Any input would be greatly appreciated!!
Thanks
I tried this in IE and it worked ok.
$(document).ready(function() {
$.get('http://dev.chriscurddesign.co.uk/burns/p/rc_rss.php?rcf_id=0',
'xml' , function(data) {
alert(data);
});
});
This wont work in other browsers because of cross site scripting issues. The above code will only work if the page in which its residing is in the same domain.
So, you have many options none of which is standard though.
Best is make an ajax call to a url from your domain and then call the feed url from there ie; from server side.
For more see this
https://stackoverflow.com/search?q=calling+webservice+from+another+domain+using+jquery
Thanks to pokrate for pointing out that it was a cross-domain issue.
For future reference I'm using a php proxy now to grab the rss and then jquery to process it.
Here is the proxy (you need curl turned on in php):
<?php
$session = curl_init($_GET['url']);
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$xml = curl_exec($session);
header("Content-Type: text/xml");appropriately
echo $xml;
curl_close($session);
?>
And here's my new javascript:
function get_rss_feed() {
$(".content").empty();
var feed = "http://dev.chriscurddesign.co.uk/burns/p/rc_rss.php?rcf_id=0";
$.get("feedproxy.php?url=" + feed, function(d) {
$(d).find('item').each(function() {
var $item = $(this);
var title = $item.find('title').text();
var link = $item.find('link').text();
var html = '<div class="entry">' + title + '</div>';
$('.content').append(html);
});
});
};
Me = Happy Bunny :)
Just use jFeed instead, this will make you code a lot simpler.
Related
Working example below, hopefully this will help others learn!
I'm using AJAX in javascript to send a JSON string to PHP.
I'm not familiar with AJAX, javascript or php, so this is taking me a while to get started.
I have a html file with a username field, password field, and login button.
Then I have a javascript file that takes the username pass and sends it to a php file.
I know the php file is being accessed because I am seeing the test echo in console.
I just cant figure out how to access the data I'm sending to the php.
script.
function attemptLogin(){
var inputUserName = JSON.stringify(document.getElementById("userName").value);
var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', 'ajax.php', true);
ajaxData.onreadystatechange = function(){
var DONE = 4;
var OK = 200;
if (ajaxData.readyState === DONE) {
if (ajaxData.status === OK) {
console.log(ajaxData.responseText);
}else{
console.log("ERROR : " + ajaxData.status);
}
}
};
ajaxData.send(inputUserName);
}
ajax.php
<?php
echo"TestInPHP";
?>
For now all I want to do is echo the username back to console, I'm sure the syntax is something simple, I just cant figure out what it is.
Here is an edit for the working code thanks to SuperKevin in the
comments below. This code will take the string in the username and
password fields in HTML by the JS, send it to PHP and then sent back
to the JS to output to the browser console window.
index.html
<input type="text" name="userID" id="userName" placeholder="UserID">
<input type="password" name="password" id = passW placeholder="Password">
<button type="button" id = "button" onclick="attemptLogin()">Click to Login</button>
script.js
function attemptLogin(){
var inputUserName =
JSON.stringify(document.getElementById("userName").value);
// console.log(inputUserName);
var inputPassword = JSON.stringify(document.getElementById("passW").value);
var cURL = 'ajax.php?fname='+inputUserName+'&pass='+inputPassword;
var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', cURL, true);
ajaxData.onreadystatechange = function(){
var DONE = 4;
var OK = 200;
if (ajaxData.readyState === DONE) {
if (ajaxData.status === OK) {
console.log(ajaxData.responseText);
}else{
console.log("ERROR : " + ajaxData.status);
}
}
};
ajaxData.send();
}
ajax.php
<?php
echo $_GET['fname'];
echo $_GET['pass'];
?>
Here's a simple example of how you would make a vanilla call.
This is our main file, call it index.php.
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "delete.php", true);
xhttp.send();
</script>
Here's our server script. delete.php
<?php
echo "HELLO THERE";
Now, if you wanted to pass data to your script you can do the following:
xhttp.open("GET", "delete.php?fname=Henry&lname=Ford", true);
xhttp.send();
To access this data you can use the global $_GET array in php. Which would look like this:
$fname = $_GET['fname'];
$lname = $_GET['lname'];
Obviously, you have to sanitize the data, but that's the gist of it.
For a much more in depth tutorial visit W3Schools Tutorial PHP - AJAX.
You can see all the data sent to your php with :
<?php
print_r($_GET); //if it's send via the method GET
print_r($_POST); //if it's send via the method POST
?>
So, in your case it will be something like :
<?php
echo $_GET['username'];
?>
If you're not using jQuery then don't pay attention to my answer and stick to the pure javascript answers.
With jQuery you can do something like this:
First Page:
$.ajax({
url: 'sportsComparison.php',
type: 'post',
dataType: 'html',
data: {
BaseballNumber = 42,
SoccerNumber = 10
},
success: function(data) {
console.log(data);
});
which will send the value 42 and 10 to sportsComparison.php with variable names BaseballNumber and SoccerNumber. On the PHP page they can then be retrieved using POST (or GET if that's how they were sent originally), some calculations performed, and then sent back.
sportsComparison.php:
<?php
$BaseballValue = $_POST["BaseballNumber"];
$SoccerValue = $_POST["SoccerNumber"];
$TotalValue = $BaseballValue * $SoccerValue;
print "<span class='TotalValue'>".$TotalValue."</span>";
?>
This will return a span tag with the class of TotalValue and the value of 420 and print it in the console.
Just a simple way to do ajax using jQuery. Don't forget commas in the parameter list.
I am trying to do this on client side using JavaScript.
Question: How to access JSON stored within https://www.instagram.com/xsolvesoftware/media/ with JavaScript and turn it into Object?
I tried xmlHttpRequest
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
var data = httpGet("https://www.instagram.com/xsolvesoftware/media/");
console.log(data);
I have tried loading it with src but it obviously doesn't work as it works only on content inside of tags:
var jsonData = JSON.parse(document.getElementById('data').textContent)
<script id="data" type="application/json" src="https://www.instagram.com/xsolvesoftware/media/">
</script>
I have tried editing this example but it uses JSONP not JSON as a reply and i think i would get JSONP only if i would use registered with access to users content:
var token = '1362124742.3ad74ca.6df307b8ac184c2d830f6bd7c2ac5644',
num_photos = 10,
container = document.getElementById( 'rudr_instafeed' ),
scrElement = document.createElement( 'script' );
window.mishaProcessResult = function( data ) {
for( x in data.data ){
container.innerHTML += '<li><img src="' + data.data[x].images.low_resolution.url + '"></li>';
}
}
scrElement.setAttribute( 'src', 'https://api.instagram.com/v1/users/self/media/recent?access_token=' + token + '&count=' + num_photos + '&callback=mishaProcessResult' );
document.body.appendChild( scrElement );
<ul id="rudr_instafeed"></ul>
have you already tried it?
What is you concrete problem?
If you have already tried, you could provide some code snippets and explain what you are struggeling with? (edit: you edited the question and added some code snippets, I'll have a look at them now)
From the distance it sounds like you are running into the CORS trap.
You need a backend service that fetches the json for you running on the same origin as you page is served from. This answer is a good starting point :)
Hope this helps.
edit: Had a look at your snippets and it is like I assumed: you have a problem with CORS. Your javascript is not allowed to load data from any arbitrary URL.
I'm trying to send data to a php file to save in database, but I don't have any response. If a checkbox is check, the [obj][idCheckbox] = 1, else [obj][idCheckbox] = 0.
File that sends
var i=0;
var objetoTodasPermissoes = function(){};
var objTodasPermissoes = new objetoTodasPermissoes();
$.each($(".classePermissoes"), function(){
objTodasPermissoes[$(this)[0].id] = 0
i++;
});
$.each($(".classePermissoes:checked"), function(){
alert('ok');
objTodasPermissoes[$(this)[0].id] = 1;
});
console.log(objTodasPermissoes);
$.each($("#userList tr"),function(){
alert(this.id);
var iduser = this.id;
$.ajax({
url:'../json/usuarioperm/savePermissions.php',
data:({
idusuario:iduser,
objTodasPermissoes:objTodasPermissoes,
}),
success:function(a){
Alert("Saved!");
}
});
});
}
the savePermissions.php file.
$iduser = $_POST["iduser"];
$perm_usuarios = $_POST["objTodasPermissoes"]["perm_usuarios"];
$perm_importar = $_POST["objTodasPermissoes"]["perm_importar"];
$perm_log = $_POST["objTodasPermissoes"]["perm_log"];
$perm_proto = $_POST["objTodasPermissoes"]["perm_proto"];
$perm_limpeza = $_POST["objTodasPermissoes"]["perm_limpeza"];
$perm_lixeira = $_POST["objTodasPermissoes"]["perm_lixeira"];
$perm_relatusuarios = $_POST["objTodasPermissoes"]["perm_relatusuarios"];
$perm_deptos = $_POST["objTodasPermissoes"]["perm_deptos"];
$perm_deptospastas = $_POST["objTodasPermissoes"]["perm_deptospastas"];
$perm_empresas = $_POST["objTodasPermissoes"]["perm_empresas"];
mysql_query("UPDATE hospital.users set
perm_usuarios=".$perm_usuarios.",
perm_importar=".$perm_importar.",
perm_log=".$perm_log.",
perm_proto=".$perm_proto.",
perm_limpeza=".$perm_limpeza.",
perm_lixeira=".$perm_lixeira.",
perm_relatusuarios=".$perm_relatusuarios.",
perm_deptos=".$perm_deptos.",
perm_deptospastas=".$perm_deptospastas.",
perm_empresas=".$perm_empresas." where id=".$iduser) or die (mysql_error());
Thank you.
PHP is kind of interesting in that it doesn't pull from $_POST like other forms when Ajax is involved. You actually will need to read the input from php://input
Here is a tiny example
$data = file_get_contents("php://input");
$response = json_decode($data, true ); // True converts to array; blank converts to object
$emailAddr = $response["email"];
Hopefully you can apply that successfully.
Edit: You can add the filter_var command to strip bad characters and sanitize the input.
$emailAddr = filter_var($response["email"], FILTER_SANITIZE_EMAIL);
$firstName = filter_var($response["firstName"], FILTER_SANITIZE_STRING);
While debugging this I would highly recommend using Chrome's Developer mode with the 'network' tab. Find your ajax call near the bottom and you can view exact header info.
To simplify the problem, all I want is passing 3 variable from javascript to PHP. So let say I have 4 varible : a,b,c,message.
I have tried the following ways:
1)The code below is in my javascript file
window.location.href="somewebsite.php?x=" + a + "&y=" + b + "&z=" + c + "&msg=" + message;
I saw that it actually passing the values to URL, it jump to the PHP website that specifies in the code above but somehow nothing is getting from $_POST['x'] ( I even try $_GET['x'] and $_REQUEST('x') but none of them works at all)
2) Then I tried with ajax
$.post("somewebsite.php",{x:a, y:b, z:c, msg:message})
And same as above nothing are passed to the PHP website.
3) I tried with form submit
I put everything into a form and submit it to the PHP website but what I get from $_POST is an empty array.
So I conclude that something is wrong with azurewebsites server. This is the first time I used window azure so I don't know how it even works. Any suggestion would be appreciated.
you can try out ajax function
$.ajax({
url:"url",
method:"post",
data:{x:a, y:b, z:c, msg:message},
success:function(data)
{
// success code
},
error:function(error)
{
// error code ;
}
});
Should work:
Your js file:
$(document).ready(function(){
var aval = "testas";
var bval = "testas2";
var cval = "testas3";
var msg = "testas4";
$.post('test.php',{a:aval,b:bval,c:cval,message:msg},function(resp){
alert(resp);
});
});
php file should look like:
<?php
$resp = "";
foreach($_POST as $key => $val){
$resp .= $key.":".$val." \n";
}
echo $resp;
?>
After post alert should give response of all sent post values.
I hope it helped you. If yes, don't forget resp. Thanks.
Try sending an array to your somewebsite.php write this inside a function on jquery code.
It must work if you place it on a good place on your code.
var x=new Array();
x[0]='field0';
x[1]='field1';
x[2]='fieldN';
$.post('somewebsite.php',x,function(x){
alert(x);
});
Your somewebsite.php could be like this.
<?php
if(!isset($_POST['x']))$x=array();else $x=#$_POST['x'];
for($i=0;$i<count($x);$i++)
echo "X ($i) = ".$x[$i];
?>
Happy codings!
I am trying to use this PHP API in Javascript. How can I use file_get_contents and json_decode in Javascript?
PHP API Code
$content=#file_get_contents("http://doma.in/api/?url=http://www.google.com&api=APIKEY");
$url=json_decode($content,TRUE);//Decodes json into an array
if(!$url["error"]){ // If there is no error
echo $url["short"]; //Outputs the short url
}else{
echo $url["msg"]; //Outputs the error message
}
Javascript
(function( $ ) {
$(document).ready(function() {
var url = window.location.href;
var host = window.location.hostname;
var title = $('title').text();
title = escape(title);
var twitter = 'http://twitter.com/home?status='+title+'%20'+url;
var facebook = 'http://www.facebook.com/sharer.php?u='+url;
var tbar = '<div id="sicons">';
tbar += 'Twitter';
tbar += 'Facebook';
tbar += '</div>';
});
})(jQuery);
Edit: Thanks to the replies
data.php
$content = #file_get_contents('http://doma.in/api.php?api=asd4sdf5634d&url=' . urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']));
echo $content;
I have added this to the Top of the Javascript
$.getJSON('data.php', function(data) {
if(!data.error){ // If there is no error
alert(data.short) //Outputs the short url
}else{
alert(data.msg)
}
});
The Javascript is now looking like this
(function( $ ) {
$(document).ready(function() {
var shorturl = data.short;
var title = $('title').text();
title = escape(title);
var twitter = 'http://twitter.com/home?status='+title+'%20'+url;
var facebook = 'http://www.facebook.com/sharer.php?u='+url;
var tbar = '<div id="sicons">';
tbar += 'Twitter';
tbar += 'Facebook';
tbar += '</div>';
});
})(jQuery);
I am sure I am doing something wrong. Sorry but I am beginner in Coding (C, C++)
Loading data via AJAX is asynchronous. Your first call ($.getJSON) is executed as soon as the page is loaded, but the callback function that you pass as a parameter, is executed only as soon as the underlying HTTP request is finished. This means that your program does not block to wait for the HTTP request; after calling $.getJSON(...) your program runs on, and the callback method is called at some time when the HTTP request finished.
You evaluate your data (in your second function) as soon as the page is loaded. But, since your data is loaded asynchronously, it is not yet loaded when the document is rendered and your function is executed.
The solution for your problem would be to move the code that evaluates your data into the callback function of $.getJSON(...):
$.getJSON('data.php', function(data) {
if (!data.error) {
// Process your data here!
} else {
alert(data.msg)
}
});