I have a website that I want it to fire a PHP file that's hosted somewhere else, without using any redirects. I think is the only possible solution, right?
<iframe src=“google.com” frameborder="0" style="overflow:hidden;height:100%;width:100%" height="100%" width="100%"> </iframe>
This is the code I have so far.
But this seems to slow down the loading speed when its firing the PHP file.
You should research into XMLHttpRequest.
With JavaScript, you can do the same thing but without the iFrame tricks.
Here's an example that will "tell the browser to load another page in the background"
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "filename", true);
xhttp.send();
</script>
Do keep in mind that browsers have security restrictions, so make sure the php file is on the SAME domain or it will return an error. If you're getting from another website you don't have control of, you'll need to ask the website owner to enable CORS.
If you want to do this from the server (php talking to php), you should then just use cURL (as stated in the comments by #MarkSkayff)
Related
I'm building a website where people can leave comments on each event created by me. Each event has its own page eg. showthread.php?t=1, showthread.php?t=2 and so on..
I managed to create a comment section for each event but I got a problem with loading comment for each event. I used $_SESSION['id'] to pass the $_GET['t'] value to another php script
My code is like this:
showthread.php
$id=$_GET['t'];
$_SESSION['id']=$id;
main_function.php
$thread=$_SESSION["id"];
SELECT * FROM comment WHERE thread='$thread' ORDER BY timestamp DESC,
these codes are working fine but I need to refresh the page in order to load the right comment for each thread, is there a way for me to load it properly without refreshing each time I load an event? thanks in advance!
AJAX is javascript used to make requests to the server. You can use it to change your page without refreshing.
Learn more here.
An example of what it looks like:
//create the request object
var xhttp = new XMLHttpRequest();
//activates when you hear back from the server
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//xhttp.responseText is filled with what we get back from the server
document.getElementById("my-element-thing").innerHTML = xhttp.responseText;
}
};
//Type of request, url you're sending to, asyncronous
xhttp.open("GET", "www.google.com?p=myparam", true);
//Send your request to the server
xhttp.send();
Edit: The idea is you would also build a PHP page to accept this request. PHP would analyze it and then echo a response. Be sure that the PHP only contains what you want and nothing else (no tags etc).
Have you tried to use javascript AJAX?
https://www.w3schools.com/xml/ajax_intro.asp
I have a problem with my chat system on my website. It keeps sending XHR Finished loading in the console. I know that i can disable it in chrome but other users who are using the site should not need to go through that process. It sends the message every one second as you see in setinterval and i want it to only send it when something in database has been added/deleted/changed
I link my js here:
function ajax() {
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if(req.readyState == 4 && req.status == 200) {
document.getElementById('chatbox').innerHTML = req.responseText;
}
}
req.open('GET', 'includes/chatbox.php', true);
req.send();
}
setInterval(function(){ajax()},1000);
That should be the only thing that needs to be edited but let me know if you need to see the php code or html code too.
UPDATE: Interwebs suggests people seeing that XHR Finished loading are just you and those who are logging ajax requests. Uncheck Log XMLHttpRequests in the console's context menu. See here. Don't worry; it doesn't impact user experience at all for your users: logging of ajax requests is disabled by default so 99% of users won't actually log it, the console is hidden by default and the cost of a console.log is insignificant even on a Pentium machine from the 1990s.
Even if you would disagree, actually all you can do is worry; if Facebook can't stop those logs from showing up, neither can you :) You're fine.
Not sure what you mean, but try this; maybe it will make your problem more evident and you can ask better:
server.php
<?php
header("Access-Control-Allow-Origin: *");
echo "hi!";
client.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id='chatbox'></div>
<script>
function ajax() {
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if(req.readyState == 4 && req.status == 200) {
document.getElementById('chatbox').innerHTML = req.responseText;
}
}
req.open('GET', 'http://localhost:1234/', true);
req.send();
}
setInterval(function(){ajax()},1000);
</script>
</body>
</html>
Run the server with
php -S localhost:1234 server.php
Open client.html on your browser and see if your problem is still happening.
Some ideas:
When you say "It keeps sending XHR Finished loading in the console", do you mean "in the networking tab"? If so, there's nothing you can do; if you send a request every second, it will appear there every second.
The client-side (html code) doesn't know about the DB state change, so that's why you are polling every second. If instead, you want the server-side (php code) to tell you when the DB state changes, you need to use some form of WebSockets. PHP is not ideal for that, but you can try something like Ratchet.
EDIT:
Apparently they add this to free hosting pages to prevent abuse. But I got rid of it by adding "exit;" on the end.
ENDofEDIT
I made a function called ajax, so I wouldn't have to write the code everywhere I need it and it works great.
But now as response I always get the data I expected as the response plus this:
<!-- Start of StatCounter Code for Default Guide -->
<script type="text/javascript">
var sc_project=6961715;
var sc_invisible=1;
var sc_security="1ca8e3ee";
</script>
<script type="text/javascript"
src="http://www.statcounter.com/counter/counter.js"></script>
<noscript><div class="statcounter"><a title="tumblr stats"
href="http://statcounter.com/tumblr/" target="_blank"><img
class="statcounter"
src="http://c.statcounter.com/6961715/0/1ca8e3ee/1/"
alt="tumblr stats"></a></div></noscript>
<!-- End of StatCounter Code for Default Guide -->
I check the data with if (xmlhttp.readyState == 4 && xmlhttp.status == 200){alert(xmlhttp.responseText);}
I'm sure the code is ok because it is the same code I used before. Here it is:
function ajax(adress, thenDo)
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
thenDo(xmlhttp.responseText);
}
}
xmlhttp.open("GET",adress,true);
xmlhttp.send();
}
Does anyone know how to get rid of this?
And I just checked it is on bottom on every page of mine on that server. (I'm using free hosting on hourb hosting)
This is almost certainly being added by your hosting provider, and its usage is one of the things that helps keep your free hosting free.
On the plus side, they would only be adding this for certain content-types, so you may want to check that your data is being returned as text/xml. If it is, then I would recommend contacting them directly, and asking if the configuration can be altered to exclude XML files.
It may sound odd, but I've been programming games in PHP. The main problem I've found was that the only way to update PHP is to load a page. That makes real-time slow. Javascript can interact with a page without reloading it. Is it possible to load PHP pages on a page using Javascript? So that it would allow PHP to be loaded over and over without reloading.
I've seen it done with Chat rooms but not sure how it works.
We mostly use Ajax, which consists in a client-side Javascript code that calls a server-side page, with out leaving the page.
Here's an example that will get the displayed content of a page, using the GET method (JSFiddle):
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
xhr.onreadystatechange = function(){
if(xhr.readyState==4 && ((xhr.status>=200 && xhr.status<300) || xhr.status==304)){//Checks if the content was loaded
console.log(this.responseText);
}
}
xhr.open('GET','myPHPPage.php?foo=foo&bar=bar',true);
xhr.send();
And here using the POST method (JSFiddle):
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
var data = 'foo=foo&bar=bar';
xhr.onreadystatechange = function(){
if(xhr.readyState==4 && ((xhr.status>=200 && xhr.status<300) || xhr.status==304)){//Checks if the content was loaded
console.log(this.responseText);
}
}
xhr.open('POST','myPHPPage.php',true);
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.setRequestHeader('Content-length',data.length);
xhr.send(data);
Note that here we use the setRequestHeader method to change the headers of this HTTP request and, in this case, to change the Content-type and the Content-length (this header has a default value of 4096 bytes). Also, the setRequestHeader method must be called after the open method.
These links should help you:
https://developer.mozilla.org/en/Ajax
http://code.google.com/intl/pt-BR/edu/ajax/tutorials/ajax-tutorial.html
Yes it's incredibly common.
Read up on Ajax.
We call that AJAX!!!
Just Read The documentation on internet about ajax
I'm trying to do my own bookmarklet and I already tried to read some response in SO but nothing to answer the weird reaction I got from my script.
I'm doing an AJAX call from my bookmarklet, so I do the little trick :
var newScript = document.createElement("script");
newScript.type = "text/javascript";
newScript.src = "http://example.com/urlToMyJS.js";
document.body.appendChild(newScript);
void(0);
And the urlToMyJS.js is like this :
var u = 'http://example.com/scriptToCall.php';
var request = new XMLHttpRequest();
request.open("GET", u, true);
request.onreadystatechange = function() {
var done = 4, ok = 200;
if (request.readyState == done && request.status == ok) {
if (request.responseText) {
alert(request.responseText);
}
}
};
request.send(null);
The weird part is :
The javascript is always launched and scriptToCall.php is always called too (it logs every hit)
The alert shows the responseText when I click on the bookmarklet on example.com
Sometimes, on other sites, the alert shows nothing (but still appears)
Some other times, the alert doesn't even show... (but I still have the log hit...)
Do you have any idea why it does that? And if yes, do you have any idea how I could make it always show the responseText?
status won't be ok unless you are testing the bookmarklet on your own site (example.com).
When you run the bookmarklet on a different site to example.com (which is after all the whole point of having a bookmarklet), it will be doing a cross-origin XMLHttpRequest to example.com. Depending on what browser you're using, that might do the request, but you won't be able to read the response due to the Same Origin Policy. It's an essential security feature that you can't make user-impersonating XMLHttpRequests to other servers.
If you want to make an XMLHttpRequest back to your server, you must do it from a document on your server, typically by having the bookmarklet create an <iframe> pointing to example.com.
Alternatively, use JSONP (<script> inclusion) to call scriptToCall.php.
Well, finally, I used another trick :
var newScript = document.createElement("script");
newScript.type = "text/javascript";
newScript.src = "http://example.com/scriptToCall.php";
document.body.appendChild(newScript);
void(0);
This way (the PHP is sending a javascript header), no more AJAX. It was nonsense in my case since both file were in the same server/folder, 1 movement instead of 2!
Anyway, thanks bobince for all the details I might use in the future !