Ajax request with Javascript - php

I have a page on which I want to show a couple of MySQL tables.
There is one table on the right that may only change when a different person is selected.
De second table is the main table in the center. I have a dropdown box with contains every person. The results from the selected person is showed in the middle table. There are multiple results for each person so there is a second dropdown box to choose which of these results you want to show. This is al done by a Ajax XMLHTTP request.
The problem is that the right table uses some javascript. I know this is not possible with Ajax in combination with a XMLHTTP-request. But without the javascript I can't make what I want. Is there a way, to show the right table after the javascript is finished doing his work?
I now use frames. This is not very nice. Because I have to style both pages to look nice together, and that's not so easy as said. But this way it is doing as I want it to be.
So I searched the internet (a long time) and just a few minutes before I wanted to give up i found this piece of code (coming from http://www.javascriptkit.com/dhtmltutors/ajaxincludes.shtml):
function HttpRequest(url){
var pageRequest = false //variable to hold ajax object
/*#cc_on
#if (#_jscript_version >= 5)
try {
pageRequest = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try {
pageRequest = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e2){
pageRequest = false
}
}
#end
#*/
if (!pageRequest && typeof XMLHttpRequest != 'undefined')
pageRequest = new XMLHttpRequest()
if (pageRequest){ //if pageRequest is not false
pageRequest.open('GET', url, false) //get page synchronously
pageRequest.send(null)
embedpage(pageRequest)
}
}
function embedpage(request){
//if viewing page offline or the document was successfully retrieved online (status code=2000)
if (window.location.href.indexOf("http")==-1 || request.status==200)
document.write(request.responseText)
}
}
HttpRequest("external.htm") //include "external.htm" onto current page
This code works perfectly... The first time. As soon as you change the person the whole page disappears and only the table shows up and firefox keeps "loading" the page (you see that circle going round). I do know how to edit the code above to fit my needs but I have no understanding of Ajax or how to fix this problem. Hopefully someone can help me and give me a good solution! And tell me why the code above isn't working properly?
Thanks in advance!
Milaan

document.write only works when the page is loading for the first time, Once the page rendering is done, calling document.write will clear the page first.
https://developer.mozilla.org/en/document.write
What you might want to do instead is:
if (window.location.href.indexOf("http")==-1 || request.status==200) {
var elm = document.createElement('div');
elm.innerHTML = request.responseText;
document.getElementsByTagName('body')[0].appendChild(elm);
}

It´s been a long time since I´ve seen code like this, but one problem I can see, is that you don´t include any kind of variable in your XMLHttpRequest; no user ID or anything. Is it just supposed to load a static page?
And is there any reason you can´t use a library like jQuery? It´s no magic bullet but it will make your life and ajax requests a lot easier.

You might want to use dom functions to add your downloaded content to the existing document, like:
document.getElementById('mypanel').innerHTML = '<html code goes here>';
The best idea probably would be to use a slim javascript framework lie jquery which helps you with browser compatibility.

jQuery should make things easier for you. Your code should look something like this.
$.post("somepage.php", function(data){
$("#divID").html(data);
});
<div id="divID"></div>
And somepage.php could be something like this:
<?php
// get table content
echo "<table>...</table>";
?>

Related

How can I make a button-link, as Like in Facebook?

Firstly, sorry for my bad English (I'm Italian).
Anyway, I'm making a web-site project for school, so I'm using HTML, CSS and PHP languages.
I'd like to put a sort of button-link (for example the "Like" one, as in Facebook) but how can I do it?
In Facebook, when I click on "Like", I won't be redirected to another page, so it can't be something like:
Like
In fact, I want the user to be in the same page at the same position
I thought I could write something like this (I'll call this file home.php):
<a name="5">
<a href="like.php?position=5&user=Paul>Like</a>
So, I will write in PHP something like:
<?php
// Database connection
// Adding a like in database. The user who liked the object is in $_GET['user']
// ...
header("location:home.php#$_GET[position]");
?>
But I don't want the user to be redirected to a page call like.php which redirect, in turn, the user at the beginning page...
How can I do it? And how can I connect to database?
Thanks in advance ^^
I can't provide code because what you're asking is too much. All I can do is steer you the right way to get your answers.
You're asking how to do at least 3 different things here that all require an explanation. So look up the following, and how they function:
AJAX. This will let your page send a message (like a button click to a PHP page).
PHP. You will need this to intercept the message and return the result.
MySQL. You will need this to create a table, hold your data, modify your data, and retrieve data to respond back to your main page.
Here is a simple example:
HTML graphic for buttonbutton
<img src="button.png" alt="playButton" border="0" onclick="countClick('1','Google')">
Javascript for the AJAX
function countClick(id,host) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
//document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "/includes/appCounter.php?appid="+ id +"&hostIs="+ host, true);
xhttp.send();
}
What this does is, when the user clicks the button, it goes to whatever link is there. But it also triggers the "onclick". This fires the Javascript.
The Javascript function makes a simple AJAX call to the server, passing in an ID and a Host. The PHP page knows what to do with those parameters.
In this case, there isn't any need for the page to even care about the response.
It happens in the background. In the end, a counter in my database is updated to let me know they clicked that button.
In the real world, it looks like this: http://android.dpoisn.com/

How to refresh a div everytime a database is updated?

I am trying to make a chat room on my website, I am using php and mysql to store the messages and all the info. How could I automatically refresh the page every time someone updates the database? example:
If I am on my site, the messages show up on my screen but I can only see more recent messages after I refresh the page. Is there a way to make it real-time?
Also I do not know much javascript/ajax/jquery or any of that. Any help is appreciated!
There will be low amount of traffic on my site. Probably around 10-15 people at a time, if that even.
Your best bet is to make an AJAX request every sec or so and see if there are new messages.
You probably do not want to be reloading the page every time. My recommendation, and there are many ways to do this, is to make a ajax call every so often and check/pull the new information from the database.
I would research AJAX and do a tutorial.
This would be accomplished through ajax by calling a function and updating the div. I would not suggest making people refresh a page everytime they send a message it would get ugly. Another option would be using HTML5 web workers
http://msdn.microsoft.com/en-us/hh549259.aspx
You are going to need to learn AJAX in order to make this work well, and jQuery is probably the easiest way to do it. If we can assume that the DIV you want to update has the ID PonyRides, you would want to do:
$("#PonyRides").ajax({url: "/chat.php?getupdates=true"});
This will get the contents of chat.php and stick it into the #PonyRides DIV. This assumes that chat.php will get the contents of the database and format them into HTML.
The remaining challenge is to make it update whenever your database does, but the simplest way is just to reload the whole chat regardless of whether an update has been made or not.
That will impact performance, but if you have less than a hundred chatters you'll probably be fine. If you have more than that, you'd do well to sense inactivity and decrease the checking period, or only send updates instead of the whole chat. Those are more complicated topics, though, and you can build them in as needed once you get these basic concepts down.
To do this, simply wrap the ajax() call in an interval like so:
setInterval(function(){ //the following code runs repeatedly
$("#PonyRides").ajax({url: "/chat.php?getupdates=true"}); //update our chat div
},5000); //repeat every five seconds
The other, awful method would be to load chat in an iFrame, set to reload periodically using the meta refresh technique. This would be dreadful, and can only be recommended if you are trying for some reason to support incredibly old browsers.
You can use AJAX request to update the values
<script type='text/javascript'>
// function for making an object for making AJAX request
function getXMLHTTPRequest() {
try {
req = new XMLHttpRequest();
} catch(err1) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (err2) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (err3) {
req = false;
}
}
}
return req;
}
var http899 = getXMLHTTPRequest();
function searchFabIndia() {
var myurl = "http://my2nddomain.com/yebhi.php";
myRand = parseInt(Math.random()*999999999999999);
var modurl = myurl+"?rand="+myRand;
http899.open("GET", modurl, true);
http899.onreadystatechange = useHttpResponse899;
http899.send(null);
}
function useHttpResponse899() {
if (http899.readyState == 4) {
if(http899.status == 200) {
// do all processings with the obtained values / response here
// after doing the stuff, call fn again after 30 s say
setTimeout("searchFabIndia()", 30000);
}
}
}
</script>
<body onload='searchFabIndia();'>
I would suggest making an AJAX request to a file on your server which will update the database. If the update to the database is successful then return the message which was updated. Back on the client side you wait for the response and if you get one then append the message to the end of the content. This way you're loading all the messages every time (which would be expensive), you're only loading new messages.
There must be something similar to SignalR(.net) for php. It lets you add code when an event occurs, I think that is what you are looking for.

How to reference an ID from another page as a variable in Javascript

So I've finally made some progress on my gallery site through a lot of help from everyone here, so thanks. Now I have one last, hopefully very easy question. To begin, here's the scenario:
Since I'm new to Javascript I'm trying to learn javascript BRFORE I delve into jquery so I'm trying to do everything in (I believe the term is) vanilla javascript. Without going into all the code, I've made a gallery for my artwork that has a thumb slider at the top of the page and a field where the selected artwork (including additional views, description, title, etc) will display. Rather than take on multi arrays right now I've built a page called 'gallery/php' that house all of the prebuilt divs that will be called into the field (titled 'generic'). Using innerHTML, I am making a simple call so that when the desired thumbnail is selected it calls the corresponding div by id and writes it in place of the 'generic' div.
Simple enough...
The problem is that I have about 40 of these and if I do a php include and hide the include in a hidden div while the artwork doesn't display it takes FOREVER to load the page and this seems like a very bad idea. What I would like to do is modify the function I am using right now so that instead of calling the id on the current page it will know which external page to reference and which div (based on id) to pull and populate the 'generic' div with. The script currently looks like this:
function changeDiv(art) {
viewer = document.getElementById('generic'),
targetInfo = document.getElementById(art);
viewer.innerHTML = targetInfo.innerHTML;
}
What I would like to do is (disregarding syntax):
function changeDiv(art) {
viewer = document.getElementById('generic'),
targetInfo = ***src = gallery.php, #(art);***
viewer.innerHTML = targetInfo.innerHTML;
}
The only thing I've seen that is similar to what I want to do is .load() in jquery but I don't know how to translate that back to javascript.
Ok! Here goes my attempt. Please note that while this should probably be vetted through an AJAX library (like jQuery), that's not what the OP asked for.
**Also, I didn't know the gallery.php set up so I went for my best attempt.
**Also I know that this is horrible and has no validation or anything else good about it, but this is more of a proof of concept. (Tracer code for those Pragmatic Programmers)
Assuming you have a gallery.php set up as the following:
<?php
$pull = $_GET["pull"];
$gallery[0] = "<div>Your art work img tags here</div>";
$gallery[1] = "<div>Some more art work</div>";
//Pull from the changeDiv parameter in the JavaScript below.
echo $gallery[$pull];
?>
We'll go with some JavaScript like the following:
var changeDiv = function(pull) {
//Pull parameter indicates an array
//index within the gallery.php $gallery array
var ajaxObj;
//Our AJAX objet shall be declared
if(window.XMLHttpRequest) {
ajaxObj = new XMLHttpRequest();
}
else {
ajaxObj = new ActiveXObject("Microsoft.XMLHTTP");
}
//When the ajaxObj changes it's ready
//state, do this stuff below
ajaxObj.onreadystatechange = function() {
//But only if the ready state is
//really ready and the status is good to go
if(ajaxObj.readyState==4 && ajaxObj.status==200) {
var response = this.responseText;
document.getElementById("viewer").innerHTML=response;
}
}
//Open the async connection to
//gallery.php and send your GET
//global (pull)
ajaxObj.open("GET","gallery.php?pull="+pull,true);
//Send it and pray
ajaxObj.send();
}
http://www.smashingmagazine.com/2008/10/16/50-excellent-ajax-tutorials/ - Some tutorial listings for AJAX

make dynamic webpage from html

I have a webpage that retrieves data (via ajax/php) and shows it in an html div (id='parent'). I'd like to add a print feature, which will take the contents of parent and show it in another page.
I've never made a dynamic webpage before. All the information I show is just pulled onto the main page via ajax. So I don't know where to begin really. I assume it has something to do with those long character strings I see in the urls of lots of internet sites, but I don't know! do I just use the url character string to store information about the current state of the page so the user can go back to what they were looking at with the back button. will the back button automatically work, or do i have to listen for it and reload the page based on what i pull from that string?
Very appreciative if someone can point me to some good articles or work out a little pattern of what steps I should take to
pull data from the page
put it on another page (or is it another page? do I just clear the page i'm on and re-fill it with other data??)
enable the back button to go back to the first page.
Thank you so much!
Those long character strings you are talking about sound like SessionIDs. The idea is that you store all the data you need to share between website requests on the server and identify the user by this ID to retreive the correct dataset when she requests the next website.
PHP already supports this out-of-the-box. The documentation of the PHP session handling functionality can be found here:
http://www.php.net/manual/en/book.session.php
To take data from ajax into another tag you can do something like this
<script>
var page_request = false;
function ajax_request(url)
{
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject)
{ // if IE
try
{
page_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
page_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
else
return false
page_request.open('GET', url);
page_request.send(null);
return page_request.responseText;
}
function ChangeDiv(id, url)
{
document.getElementById(id).innerHTML = ajax_request(url);
}
</script>
then just call ChangeDiv with the url you want (e.g 'http://website.com/page.php?params=1')

Calling Javascript Function In PHP Not Working

I'm new to Google Documents and have set up a spreadsheet that accesses the amount of "Likes" on three different Facebook pages. The code is part of the library on Google Documents but I'm trying to take the resulting total and pull it up on my site which is PHP. I'm starting simply with one site just because I can't get it working.
Here is the Javascript that was written to compile the likes:
function FacebookFans(aPageId)
{
if (aPageId === undefined || aPageId === null)
{
throw "No parameter specified. Write Facebook PageID as parameter."
}
if (typeof aPageId != "number")
throw "Parameter must be number.";
// See http://developers.facebook.com/docs/reference/fql/page/ for API documentation
var url = "http://api.facebook.com/method/fql.query?query=SELECT%20page_id,page_url,fan_count%20FROM%20page%20%20WHERE%20page_id=%22" + encodeURIComponent(aPageId) + "%22";
var response = UrlFetchApp.fetch(url);
if (response.getResponseCode() != 200)
throw "Unexpected response code from Facebook.";
var responseText = response.getContentText();
if (responseText == null || responseText == "")
throw "Empty response from Facebook.";
var fan_count = 0;
try
{
var xml = Xml.parse(responseText, false);
var page = xml.getElement().getElement();
if (page == null)
throw "Wrong PageID.";
fan_count = parseInt(page.getElement("fan_count").getText());
}
catch (e)
{
throw "Problem with response from Facebook: " + e;
}
return fan_count;
}
Now, to preface, I am very new at Javascript so don't kill me if my code is way off, I'm still trying to understand. I tried to run this in the body:
<script type="text/javascript">
document.write(FacebookFans(40796308305));
</script>
I figured the function returns a value and this would print that value out (the number btw is Coca Cola's Facebook page ID, figured it was a good one to test with). Is this a conflict between Javascript and PHP? I know that's a mixture of client-side and server side scripts. The reason I'm not sure what's wrong though is that I set a var inside the Javascript and then used to document.write to call it back just to test that my code was valid and it recalled the var fine. Anyways, any help is greatly appreciated. Thanks.
I used the Google Docs script debugger to step through your script.
The first arrow is what starts the script. In the dropdown for Select Function, choose the "doit" function I created (see bottom of screenshot). Finally, you can click where the second arrow is pointing and create a breakpoint, so the debugger stops.
After stepping through all of your code, you'll be glad to know it works just fine.
Your problem must be related to your understanding of how/when the code will be run. Note there is NO PHP in any of this code, so I'm not sure why you were asking about PHP.
You need certain "Actions" to run your scripts. You can read more about how scripts are run in Google docs. But your document.write doesn't apply here because you aren't writing a script for a webpage. You are inside the Google Docs environment.
If you want to run your script outside of Google Docs, you have a problem with the UrlFetchApp call, since that is a Google specific thing. If you load that script (and put it inside tags) in a .html doc, you can use Google Chrome to find out the errors. Select Wrench Icon->Tools->Javascript Console and it will show you the error right away. Now, normally you could just translate this to something else, but Javascript does its best to prevent you from making cross domain requests (learn more).
To translate this into server side code, it's pretty simple in PHP. You are basically just calling one url and then parsing it with XML. To load the contents of the url, use file_get_contents and then parse the xml.
If FacebookFans(40796308305) really works and returns result, so the problem is somehow in document.write.
Try:
<script type="text/javascript">
alert(FacebookFans(40796308305));
</script>
To be sure that the function works. And:
<script type="text/javascript">
var a=FacebookFans(40796308305);
document.write('a='+a);
</script>
To check the different types of issues.
If nothing helps, so we need more info, how do you invoke this function.

Categories