I'd like to pull pictures and / or videos from another website onto my page, and i'd like to edit the looks with css. The website ofc. has rss, but i don't have an idea of how to do this. Someone told be before that i could ping the website and if there is new content, it automatically displays it on my site. How can this be done?
Thanks!
I am not quite sure if this is directly possible as it could theoretically cause a lot of traffic for the third-party website. Maybe you can read the content in your RSS-Reader and use this to update your site indirectly.
After all, aren't we talking about stealing content?
As the Rss feed is XML, the best way to do this is with Ajax, here is a sample
window.onload = initAll;
var xhr = false;
var dataArray = new Array();
var url = "otherSites.xml";
function initAll() {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}
if (xhr) {
xhr.onreadystatechange = setDataArray;
xhr.open("GET", url, true);
xhr.send(null);
}
else {
alert("couldn't create XMLHttpRequest");
}
}
function setDataArray() {
var tag1 = "subject1";
var tag2 = "subject2";
if (xhr.readyState == 4) {
if (xhr.status == 200) {
if (xhr.responseXML) {
var allData = xhr.responseXML.getElementsByTagName(tag1);
for (var i=0; i<allData.length; i++) {
dataArray[i] = allData[i].getElementsByTagName(tag2)[0].firstChild.nodeValue;
}
}
}
else {
alert("the request failed" + xhr.status);
}
}
}
Related
I am using SimpleXMLElement() to obtain data from a website, which is used to embed data. The code I am using is as follows:
$rss = new SimpleXMLElement('http://eliteprospects.com/rss_player_stats2.php?player='.$player_array[0]['embed_stats'], null, true);
foreach($rss->xpath('channel/item') as $item)
{
echo utf8_decode($item->description);
}
This works great, except for one issue, the data loads exceptionally slow from the other site. The page load goes from approximately 0.5-1s to 2.5-3s.
Is there a method that I can use, to load the asynchronously, or is there a faster function I should be using instead?
An idea that came to mind was to load a separate page within an iFrame after the initial page load, or is there a better method?
Is there a method that I can use, to load the asynchronously, or is
there a faster function I should be using instead?
Unfortunately, there is nothing to do about the long response time (trivially assuming that connection speed in not archaic). Also echoing out the results all at once might slow down the browser rendering and thus the page load time.
AJAX fits nicely here - wait for window.onload and trigger the AJAX call to your webservice (holds the snippet from question) to prepare the output buffer and return the response to browser. Afterwards set/replace the innerHTML value of selected DOM element with the response.responseText.
Pseudo-code
window.onload = function()
{
var url = 'http://example.com/webserice';
Ajax.get(url, function(response)
{
var responseText = response.responseText;
document.getElementById('someid').innerHTML = responseText;
}
}
The snippet I am using in pure JS, although jQuery has a lot more appealing way to do it
Ajax = {
request : {},
createRequest : function()
{
var request = false;
if (window.XMLHttpRequest)
{
request = new XMLHttpRequest();
}
else
{
if (window.ActiveXObject)
{
request = new ActiveXObject('MSXML2.XMLHTTP.3.0');
}
else
{
request = false;
}
}
return request;
},
get : function(page, callback)
{
var self = this;
var request = this.createRequest();
if (! page)
{
return false;
}
request.onreadystatechange = function()
{
if (request.readyState == 4 && request.status == 200)
{
delete self.request;
if (typeof callback == 'function')
{
callback(request);
}
else
{
self.update(request, callback);
}
var regex = /<script\b.*?>([\s\S]*?)<\/scri/ig;
var match;
while (match = regex.exec(request.responseText))
{
eval(match[1]);
}
}
}
request.open('GET', page, true);
request.setRequestHeader('X-Requested-With', 'ajax');
request.send(null);
}
}
I try to upload photo with Ajax, have written code that has worked without Problems in Opera (My Standard Browser). Now i have tested it in other browsers, they all shooting with errors back. My PHP script starts with
if(!empty($_FILES)) {
//todo
} else {
exit();
}
So i tried to put var_dump($_FILES); die(); at the start to see whats wrong.
They all give this back array(0) {}. I have tested it on FireFox, Chrome, Safari (All latest version), IE9 on win7 and latest Firefox on Debian. The biggest problem, i don't understand why it don't working, because in developer tools and all browsers above, i can see the file with right name in right position.
Here is my JS to upload:
var photo_input1 = document.createElement('input');
photo_input1.setAttribute('type','file');
photo_input1.setAttribute('class','photo_input');
photo_input1.setAttribute('id','photo1');
photo_input1.addEventListener('change', function() {
upload_photo(this.id,this.files[0])
});
var upload_photo = function(filename,file) {
var data_arr = Array();
data_arr['callback_name'] = 'upload_photo';
upload_file(filename,file,'add_photo.php',data_arr);
}
var upload_file = function(filename,file,url,data_arr) {
var datapack = null;
var ajaxanswer = function() {
try {
if (ajax.readyState == 4) {
if (ajax.status == 200) {
//todo
} else {
alert('Problems:' + "\n" + ajax.statusText);
}
}
} catch(e) {
}
}
try {
var ajax = new XMLHttpRequest();
} catch(e) {
try {
var ajax = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
var ajax = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if(ajax) {
if(typeof url != 'undefined') {
datapack = new FormData;
datapack.append(filename,file);
if(typeof data_arr != 'undefined') {
for(key in data_arr) {
datapack.append(key, data_arr[key]);
}
}
ajax.open('POST',url, true);
ajax.setRequestHeader('Content-type', 'multipart/form-data');
ajax.onreadystatechange = ajaxanswer;
ajax.send(datapack);
}
}
}
It is not possible to upload files using ajax. The normal way to do is to use a iframe internal and submit the form using the iframe. You can read about one of the way here.
Also you can read this answer.
With XHR2, File upload through AJAX is supported. E.g. through FormData object, but unfortunately it is not supported by all/old browsers
FormData only works in Opera v12 and up as other relatively new browsers: http://caniuse.com/#search=FormData
You can try this for Ajax-like file uploading : https://github.com/valums/file-uploader. As Arun P Johny mentioned, there is no uploading with Ajax, but you can use some workarounds, like hidden iframe in this case.
how you doing, i've been working on this for 2 hours now and I can't seem to get my page to dynamically display information when I change it. Would appreciate if someone can tell me what went wrong.
This is my HTML
<h2>Feedbacks</h2>
<form>
<select onchange="viewFeedback(this.value);">
<option value="unread">View Unread</option>
<option value="all" >View All</option>
</select>
</form>
<div id="feedbackview"></div>
This is my ajax
function createObject() {
var request_type;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}else{
request_type = new XMLHttpRequest();
}
return request_type;
}
var http = createObject();
function viewFeedback(condition) {
http.onreadystatechange = function() {
if(http.readyState == 4) {
document.getElementById('feedbackview').innerHTML=http.responseText;
}
http.open("GET",'viewfeedback.php?condition='+condition,true);
http.send(null);
}
}
and here is the php
$condition = $_GET['condition'];
$db = new db();
$query = $db->query("SELECT * FROM feedback");
$rows = $db->countRows($query);
if($rows != 0) {
$results = $db->getRows($query);
foreach($results as $result) {
extract($result);
echo $name;
}
}
The open() and send() calls should not be within the onreadystatechange event, move them outside. You can also move the event outside from the viewFeedback() too because there's no need to keep re-defining it every time your dropdown is changed.
var http = createObject();
http.onreadystatechange = function() {
if(http.readyState == 4) {
document.getElementById('feedbackview').innerHTML=http.responseText;
}
}
function viewFeedback(condition) {
http.open("GET",'viewfeedback.php?condition='+condition,true);
http.send(null);
}
Also note that you don't do anything with $_GET['condition'] on the PHP side, so the response will always be the same regardless of which dropdown item is selected.
First, I don't know if that Ajax creation function is so great. I would comment it out for now and add it back only if it is not working in a supported browser. Instead just do this:
var http = new XMLHttpRequest();
Next, try hitting the PHP web service directly in your browser. Is it working? If so, fix the issues in your Ajax request:
function viewFeedback(condition) {
http.open("GET", 'viewfeedback.php?condition=' + condition, true);
http.onreadystatechange = function() {
if (http.readyState == 4) {
if (http.status == 200) {
document.getElementById('feedbackview').innerHTML = http.responseText;
} else {
console.log(http.response);
}
}
}
http.send(null);
}
Let me know if this doesn't work.
I want to create a edit pop up form using just ajax. i.e when user clicks on a link , a pop up comes up and he edits the data and saves it. can i do this with out any ajax framework ?
Yes you can, you can always create XMLHttpRequest objects yourself, but using a framework will save you hours or days of coding and make sure your service has maximum browser compatibility.
Yes, you can use the following function which I wrote and did several weeks optimizing it.
function ajaxGET(url,span_or_div) {
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
if (httpRequest.overrideMimeType) {
httpRequest.overrideMimeType('text/plain');
}
}
else if (window.ActiveXObject) { // IE ( yeah 200bytes wasted because of IE.. lol
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState == 1) {
window.document.getElementById(span_or_div).innerHTML='Loading...';
}
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
document.getElementById(span_or_div).innerHTML=(httpRequest.responseText);
} else {
window.document.getElementById(span_or_div).innerHTML='<strong>Error 404</strong><br />Page Not Found.';
}
}
};
httpRequest.open('GET', url, true);
httpRequest.send('');
}
How can I use javascript to send a one way message to php? I would like to get the browser information from javascript and just send it to php in the background. I know I can get some of this from php, but I'd rather use javascript. Is there a way to do this without a framework like jquery?
Yes, you can do it with something like this:
function xmlhttpPost(strURL) {
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// IE
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
alert('Here goes something');
self.xmlHttpReq.send('browser info here');
}
}
}
This will send "browser info here" as POST in the php page you pass to the function as url. I didnt test it though
You would have to submit an AJAX request to a PHP script. Yes, you could do it without using a framework but I wouldn't advise it.
You need to make an AJAX call to a PHP page, preferably using POST. Any data you want to send needs to be sent along with the request.
I recommend using a framework such as jQuery, but if you insist on using raw JavaScript, you want to research XMLHttpRequest.
// fix for older IE versions
// see http://blogs.msdn.com/b/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
if( typeof window.XMLHttpRequest === 'undefined' &&
typeof window.ActiveXObject === 'function') {
window.XMLHttpRequest = function() {
try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
return new ActiveXObject('Microsoft.XMLHTTP');
};
}
function postData(url, data, errhandler) {
var req = new XMLHttpRequest;
req.onreadystatechange = function() {
if(this.readyState === 4 && this.status !== 200 && errhandler)
errhandler(this);
};
try {
req.open('POST', url, true); // async post request
req.send(data);
}
catch(e) {
if(errhandler)
errhandler(req);
}
}