I have a comments board on my page, to which I load different topics according to the page the user is on with XMLHttpRequest in a changeTopic() function. I originally had this at the end of my submit form php:
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_POST['page']);
The problem is that I don't want to refresh the whole page, only the DIV that contains the messages. I tried running the changeTopic() function by inserting it inside script tags with echo. For one, I couldn't get .$_GET['topic']. working inside echo even if I made a variable of it first, but also I tried running the function by hard inserting one of the possible values with the following results:
1) While the messages section refreshed right, I lost the form as it's contained in the index.html while I only load the messages from an external gettopic.php with query string.
2) I got a weird result where I lost an external file that was loaded into a completely different div altogether. This file changes the hash of the main page, which is checked with every refresh and the right file is loaded according the hash, so using the whole page refresh never resulted in this.
// EDIT
function changeTopic(topic) {
if (topic=="") {
document.getElementById("messagelist").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("messagelist").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST", "gettopic.php?t="+topic,true);
xmlhttp.send();
}
The main application on my page is a SVG map which I've done with RaphaelJS. The user can load information pages into another div 'info' from this SVG map. The pages are loaded with a similar function which in addition changes the #hash and runs the changeTopic() as well to change the message board so people can have a conversation about each topic.
The PHP form takes the normal filled info as well as the hidden 'pageid' which is set by the current page the user is browsing, and sends it to the database. The different messages are sorted by this pageid so the changeTopic() function only brings the right messages: gettopic.php?t=topic ('pageid').
After submitting the form I'd like only the messagespart to refresh and the form to clear. At the moment it's either a whole page refresh (user looses their position on the SVG map) or partial refresh where I lose the form (get a blank spot instead) and that weird information-page missing.
you can do something like this:
var ajaxfoo = function(obj) {
var xmlHttp = null;
try {
xmlHttp = new XMLHttpRequest();
}catch(e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e) {
xmlHttp = null;
}
}
}if (xmlHttp) {
obj.method = obj.method.toUpperCase();
xmlHttp.open(obj.method, obj.url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
if(obj.method == 'POST') {
if(typeof(obj.params) != 'undefined') {
xmlHttp.setRequestHeader("Content-length", obj.params.length);
}
}
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
var json = eval(xmlHttp.responseText);
if(json.success) {
if(typeof(obj.success) == 'function'){obj.success(xmlHttp.responseText);}
}
else {
if(typeof(obj.failure) == 'function') {obj.failure(xmlHttp.responseText);}
}
}
};
if(obj.method == 'POST' && typeof(obj.params) != 'undefined') {
xmlHttp.send(obj.params);
}
else {
xmlHttp.send(null);
}
}
};
function callfoo(topicname) {
ajaxfoo({
method: 'GET',
url: 'gettopic.php?t='+topicname,
success: function(response) {
var json = eval(response);
alert('success callback function! '+json.data);
},
failure: function(response) {
var json = eval(response);
alert('failure callback function! '+json.data);
}
});
}
and in
success: function(response) {
var json = eval(response);
alert('success callback function! '+json.data);
},
you can add your innerHTML stuff :)
the gettopic.php
should then echo something like:
{success: true, data: [{id: 1, "title": "test title", "description": "moo"},{id: 2, "title": "test title", "description": "moo"},{id: 3, "title": "test title", "description": "moo"}]}
And the you can access this by calling
json.data[0].title
json.data[1].title
json.data[2].title
json.data[0].description
...
so you can simply build your innerHTML stuff by doing something like
doc....innerHTML = '<h2>'+json.data[0].title+'</h2>';
Use jQuery - great tool. It could look like
$(function(){
//when you want to reload your div, just put this line
$("#div_element").load('your_new_page.php');
});
and that's it !
I'm quite confused about what you are doing, but XMLHttpRequest should be the one running changeTopic() in the readystatechange handler.
Related
I am doing a blog with PHP, AJAX, MySQL, etc. As usual, each post has its ID and inside the posts you can see the comments.
What I am trying to do is refresh the comment's div by calling the comments.php document with AJAX and putting it in the div with $('#comments').html(data);.
Doing this every 5 seconds for maintaining the comments like in real time, but the problem is that when the div does the first refreshing, the div loses the ID of the post and say that is undefined.
How can I refresh any div without losing the ID of the post?
If I call the comments.php file with the typical include(file.php) inside of the post file, I have no problem, but using this way I just can't refresh the content.
Here's the code:
post.php:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'support/comments.php',
success: function(data) {
$('#comments').html(data);
}
});
});
</script>
div where the result is going to be showed:
<div id="comments">
</div>
Script for refreshing the div:
<script language="Javascript" type="text/javascript">
function refreshDivs(divid, secs, url) {
// define our vars
var divid,secs,url,fetch_unix_timestamp;
// The XMLHttpRequest object
var xmlHttp;
try {
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
} catch (e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("your browser doesn't support ajax.");
return false;
}
}
}
// Timestamp para evitar que se cachee el array GET
fetch_unix_timestamp = function () {
return parseInt(new Date().getTime().toString().substring(0, 10))
}
var timestamp = fetch_unix_timestamp();
var nocacheurl = url+"?t="+timestamp;
// the ajax call
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById(divid).innerHTML=xmlHttp.responseText;
setTimeout(function(){refreshDivs(divid,secs,url);},secs*1000);
}
}
xmlHttp.open("GET",nocacheurl,true);
xmlHttp.send(null);
}
window.onload = function startrefresh () {
//update content on real time
refreshDivs('comments',10,'support/comments.php');
}
</script>
You can pass the post id in the URL, like so:
url: 'support/comments.php?id=<?= $post_id ?>'
Then wrap the call with a setTimeout, like so:
window.setInterval(function(){
$.ajax({
url: 'support/comments.php?id=<?= $post_id ?>',
success: function(data) {
$('#comments').html(data);
}
});
}, 5000);
And discard refreshDiv.
This is assuming that comments.php retrieves the comments, and some other code posts them.
ok guys I solved it... I am gonna leave the code here in case of somebody could has the same problem... what I did was build a hidden input and put this input to use its value like the id of the post, then I sent the value of this input to the script with #('div').val and finally I sent that value to the comments.php file, once there.... I used the value in the query sentence for doing the comparative and finally can get the comments in the right post
Here's the code
<script>
$(document).ready(function() {
window.setInterval(function(){
//Comentarios
var id = $("#idcomment").val();
$.get("support/comments.php", { idpost: id }, function(LoadPage){
$("#comment").html(LoadPage);
});
}, 5000);
});
</script>
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 have a problem with my web about title tag <title></title>. I want to connect it to database so that the value of my web title is from database, it worked. But another problem happened when I want to make my web title (not whole page) auto refresh. I have found the script from ajax but it doesn't really succeed just like in facebook title tag, just assume, I enter new data from another browser (ie, Opera, etc) and after I go back to my main browser (Firefox) the title tag does not change at all or does not auto refresh and change the value. I really need your help guys..!? This is the script that I've tried..
setInterval(function() {
$.ajax({
url: '{BASE_URL}/system/back-end/main.php',
url: 'main.html',
//data: {name: 'username', password: 'userpass'},
success: function() { document.title = '$value';},
dataType: 'text'
});
}, 1000);
function getXHR() {
if (window.XMLHttpRequest) {
// Chrome, Firefox, IE7+, Opera, Safari
return new XMLHttpRequest();
}
// IE6
try {
// The latest stable version. It has the best security, performance,
// reliability, and W3C conformance. Ships with Vista, and available
// with other OS's via downloads and updates.
return new ActiveXObject('MSXML2.XMLHTTP.6.0');
} catch (e) {
try {
// The fallback.
return new ActiveXObject('MSXML2.XMLHTTP.3.0');
} catch (e) {
alert('This browser is not AJAX enabled.');
return null;
}
}
}
function setPageTitle(newValue) {
document.title = '$value';
}
function messageCountAsPageTitle(msgCount) {
// TODO: determine where 'another text in the page title' should be defined
msgCount = '{PESAN_ENTRY} {BERKAS} {BERKAS}';
setPageTitle('(' + msgCount + ') - another text in the page title');
}
<!--</tpl:tmpl>
function getMessageCount(callback) {
var url = 'main.html?' + 'main.php?' + (new Date()).getTime(), // prevent caching
xhr = getXHR();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(xhr.responseText);
}
};
xhr.timeout = 2000; // Set the timeout to be less than the frequency we call this
xhr.open("GET", url, true);
xhr.send();
}
setInterval(function() {getMessageCount(messageCountAsPageTitle);}, 3000);
please help?
If you are using jQuery (the top $.ajax() call) then you should only use this, not the bottom part. Make sure you include jQuery in the source of the HTML (google jQuery on how to do that)
You need to create a php file that returns the new title.
// script.php
echo 'My New Title';
exit();
Then use jQuery in your source to access the new title:
setInterval(function() {
$.ajax({
url: 'http://UrlToGetTheTitleFrom/script.php',
success: function(data) { document.title = data; },
dataType: 'text'
});
}, 10000);
(Note: that 1000 in SetInterval EVERY SECOND - it's milliseconds. Pretty sure you don't want it hammering your server that quickly!)
I am fluent with HTML, and mostly PHP.
I can do the scanning part with PHP.. I'm just not sure how to call a function in PHP with JavaScript, because I don't know JavaScript.
My PHP code will connect to my MySQL database and see if the text currently in the textbox (Not clicked enter yet, still typing) is in the database..
Do you know how to do this, or at least know a link that tells you how to do it?
This sounds like a problem for jQuery. I'd give you a long-winded example, but there are many people that would give you a much better one: like this guy.
Consider using jQuery in conjunction with jQuery UI, specifically something called autocomplete. I'm fairly certain it does what you're wanting, and it's completely themable for your site.
I see everybody likes jQuery so much, wow!
I'd tell you just need some very basic Ajax script to call your PHP script and receive the response.
Here's the simple Javascript function (actually two):
function getXMLObject() {
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");// For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");// For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false;// No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();//For Mozilla, Opera Browsers
}
return xmlHttp;// Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject();//xmlhttp holds the ajax object
//use this method for asynchronous communication
function doRequest(scriptAddressWithParams, callback) {
if (xmlhttp) {
xmlhttp.open("POST", scriptAddressWithParams, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
callback(xmlhttp.responseText);
}
else {
alert("Error retrieving information (status = " + xmlhttp.status + ")\n" + response);
}
}
};
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
and here's an example of usage:
<input type="text" onchange="doRequest('myphpscript.php?checkvalue='+this.value, function (returnedText) { alert(returnedText);});"/>
Hello I have two dependants select box, the second one is popularited after onchange event.
The first one is loaded with a selected value (selected=selected), what I'm asking, it is possible to send the requested while the page is loading, ie as I have the the selected option, just send the request.
Javascript
function getXMLHTTP() {
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getSubCat(catId,incat) {
var strURL="../Includes/subcatAds.php?SubCat="+catId+"&incat="+incat;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('subcat').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
The PHP will be provided if needed
You really need to use jQuery and replace all of the above with:
function getSubCat(catId, incat)
{
$('#subcat').load("../Includes/subcatAds.php?SubCat="+catId+"&incat="+incat);
}
// Run on load:
$( function(){
getSubCat(4, 5);
});
It will do the same thing. It's set up to run on load, and you don't have to worry about cross browser compatibility.
You will find yourself using jQuery selectors all the time and your code will be very lightweight. If you link the jQuery library to Google servers people will not even have to download it. Most people have it in cache already.
You could use the onload event like this:
window.onload = function(){
var selectbox = document.getElementById('select box id');
if (selectbox.value !== ''){
// your code to send ajax requests...
}
};
The code runs as soon as page loads. It then checks if the value of the specified select box is not empty meaning something is selected; in that case you put your code for the ajax request which will execute.
Since you are doing this before getting any input from the user, you could immediately make the call to the server, before the DOM is finished, before the page is fully loaded, and then just wait until the onload event takes place, or you get informed that the DOM tree is finished, and you can then safely change the value of any of the html elements.
This way you don't have the user wait for the browser to finish loading before you even start your request, which will improve the user experience.