Fetching file with AJAX, can't read PHP - php

I have checked the suggestions that came up before posting, hope I didn't miss anything now.
I have a piece of code that I use to get txt-files for my website but now I need to redo the code so it gets both txt and php-files, but it just won't read the php-script. I'm a bit afraid to mess up the code at this moment so I'm walking on the safe side of the road and ask here if anyone knows a good add to the code. It's quite embarrasing that I still have codes for IE 5&6 in it, so if you wish to remove that at the same time, go ahead. I won't hate you for it, I promise.
UPDATE:
I have four files:
html - Calling the .js-file with the ajax-script.
js - With all my javascript(and simular)-codes.
php - That contains... Well, you get the point.
I have to call the php-code somehow, like I call my txt-files, but of course so the php works as it should. I am very new to AJAX, so I don't dare to mess around with this code at the moment, but I figured that I might be able to add some kind of if-statement that calles the php-file as it is intended to be.
But I have no clue what that code might be and where to put it for things to work accordingly. Any help would be appritiated and credited in the code, of course.
Heres the AJAX-code that is contained within the .js-file:
/*Load the link.*/
function loadXMLDoc(url)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("leftCol").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
/*Highly unnecessary, but I wanted to see if it worked and it looks better on the .html-page.*/
function get_link(url)
{
loadXMLDoc(url);
}

As the above commenter said, it is best to use a 3rd party tool for such things - if for no other reason than to greatly increase cross-browser compatibility.
if you were to use jQuery, the code would be reduced to.
function get_link(url)
{
$.ajax({url: url, success: success:function(result){
//the code / resulting string will be in the result variable.
}});
}
jQuery CDN Hosted: http://code.jquery.com/jquery-1.5.min.js
Let me ask this... if you change your code to
function get_link(url)
{
window.location=url;
}
Does your web browser successfully navigate to the page you are trying to retrieve via AJAX? If not, there is likely a problem with your PHP syntax.

it just won't read the php-script
It's a rather vague statement, but here are few pointers that could be the solution :
PHP file are interpreted on the server so when you do an Ajax call to that page what you receive on the client side is the result of that php script, not his content.
You are assigning the result of the query directly in the HTML, if the result contains data that does not render anything, you won't see anything. For example the content <script>Text here bla bla bla</script> will just show nothing.
If you want to make sure you get some data back from a file, you can just alert the content when you receive it.
Make sure your path to your PHP page is correct. To detect if the file is not giving a 404 error code or any other error code, you can use this :
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
document.getElementById("leftCol").innerHTML = xmlhttp.responseText;
} else {
alert("Error " + xmlhttp.status);
}
}
}

Related

What is ajax returning to me? (ajax call to php file)

I am pretty much brand new to ajax. This is an ajax call which I am using to retrieve information from a sql database using a php document called "bridge.php". I just cannot seem to understand what I am getting back from this, if anything at all. Is it an array? an object? Am I not getting anything back because I'm using a get when I should be using a post? The amount of info that I'm trying to get back would not fit in a get, but the amount I'm sending through the call is small enough to fit.
<script type="text/javascript">
function refreshPro(namex){
alert(namex);
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("port_work").innerHTML=xmlhttp.responseText; //what is xmlhttp.responseText?
}
}
xmlhttp.open("GET","../bridge.php?pro="+namex,true);
xmlhttp.send();
}
</script>
and now for the php(bridge.php) which takes the get var from the url and queries the database, which I know this part works okay by itself...
<?php
$pro = $_GET["pro"];
$sql = "SELECT * FROM portfolio WHERE title LIKE \"%$pro%\"";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
?>
<div id="portfolio_item">
<h2><?php echo $row['title']; ?></h2>
<img src="<?php echo $row['image_paths']; ?>" alt="<?php echo $row['title']; ?>" />
<p id="portfolio_desc"><?php echo $row['description']; ?></p>
</div>
<?php
}
?>
And yes, I've done my homework. I've studied these two other posts but one starts talking about JSON which I know nothing about, and the other didn't quite seem to match my problem, but I still found the answer kinda useful. Returning AJAX responseText from a seperate file and Ajax call not returning data from php file
You are getting back plain HTML from the server. The responseText variable is a string containing the plaintext response to the GET request.
A GET request is like any other browser request you normally perform when visiting a given URL. Thus you can test what the bridge.php script sends for a given input by visiting http://url/to/bridge.php?pro=<someValue> using your browser of choice.
It doesn't matter the amount of data you get back, what matterns WRT using a POST or a GET is how much data you want to put in (GET request can only take 255 chars of data, POST is technically unlimited).
If you get nothing visiting the bridge.php script directly, this indicates that this script may be failing resulting in a 500 Internal Server Error code. This doesn't get caught by your javascript code since you're explicitly checking that the code is 200 (success) before doing anything with the response.
I would add:
... snip ...
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("port_work").innerHTML=xmlhttp.responseText;
}
else
{
alert('There was a ' + xmlhttp.status + ' error :(');
}
}
... snip ...
Using jQuery for this makes it rather simple:
<script type="text/javascript" src="path/to/jquery.js">
<script type="text/javascript">
function refreshPro(namex)
{
$.ajax({
type: "GET",
url: "../bridge.php",
data: {
pro: namex
}
}).done(function( msg )
{
$("#port_work").html(msg);
});
}
</script>
First of all just echo 0 or 1 or any damn keyword 'Hello world' from bridge.php.
the code
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
}
says that if everything is goes fine. I.E if the path to the bridge.php then it would go inside this if condition. and will alert response.
If this works perfectly then your code shold work too.
also see the answer mentioned by #ccKep. It is easy to use.
In addition use the tool like Mozilla firebug. So that you can understand that what is going on. Hope this helps.
The Ajax runs on the client not on the server, so you need to provide the url of your server. This is not going to work:
xmlhttp.open("GET","../bridge.php?pro="+namex,true);
What might work is:
xmlhttp.open("GET","http://yourhost.com/bridge.php?pro="+namex,true);

Why am I having ajax communication issue?

I've trying to send some infromation to a php file and display the result returned. First of all I'm not receiving any results from php file i.e. no value in xmlhttp.responseText. Instead of responseText, I tried putting 'something else' which made no difference. But when i comment out //if (xmlhttp.readyState==4 && xmlhttp.status==200), the result briefly appears.
What have I done wrong?
Ajax code looks like this:
var div = 'display';
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
writeBack (div, xmlhttp.responseText+'something else', 'red');
}
}
xmlhttp.open("POST","update_profile2.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("rr="+id);
Php code:
..
if(isset($_POST['rr']))
{
die('connection made');
}
..
Every problem I've ever had with AJAX is usually caused by trying to submit an AJAX request using a 'submit' button in a form. If you are doing that, make sure you stop the .submit() .... Also, if you use jQuery, your AJAX code will look sooooo much better :)
As others users say with jquery the code looks much better.
However I am quite sure your problem is with this line:
xmlhttp.open("POST","update_profile2.php",true);
The request above access directly the update_profile2.php and gets back the entire content of the php page, not the output elaborated by the page.
This is way you access the page without asking the web server (with the php engine) to serve it for you. And of course the http call fails so the condition && xmlhttp.status==200 blocks the execution of the next instruction that fills in the div.
use instead:
xmlhttp.open("POST","http://localhost/update_profile2.php",true);
This will send a ajax http request to apache, il will run the php page and returns the answer of the page!

Constructing a more efficient javascript user-based chat

I am going to bed soon, so I will not be on until the morning, but I have been struggling with trying to find a javascript/jquery method that solves my problem. I am trying to make a chat box feature where once a post is submitting it is then echoed back out and users on both ends can see it. I know that I need to use javascript and or jquery. Right now I am using a very inefficiency system:
<script language='javascript' type='text/javascript'>
setInterval( function() {
$('#responsechat').load('echogetconversation.php?username=<?php echo $username; ?>&otherchatuser=<?php echo $otherchatuser; ?>');
}, 100);
</script>
The only reason that I am using it is because it is the only way I know how to project new posts to both users. I was wondering if someone knew a way to do this. Once a post is submitted, it fades into a div and both users can see it, not only the user who submitted it, so it is like a facebook chat in a way. I have no idea about any possible solutions, and have done research, but I could not find any that i could get to work. Any help and/or insight to what I should do next would be appreciated.
What you are looking for is ajax long pulling, also called Comet (it's a silly pun). The basic idea is simple--instead of polling the server, you send your ajax request and the server blocks on it until it gets a new message.
"Blocking" here simply means it does not send a response. You get your request then first up a thread (is that what you would do in PHP? I've only ever used node.js for this) and wait until something changes before sending the response back to the client.
Once the client has a response, it sends another request immediately.
There is one other trick: requests can time out. This means that the server should send a response back after a certain time even if nothing has updated.
This methodology is good if you have to support older browsers; if you can ignore those and stick to newer ones, you can use "websockets".
There are libraries that help you use websockets or fall back on Comet. I think the most popular one is socket.io.
Coincidentally, if you're not tied to PHP, I really suggest using a different server. node.js is a great option--it is a natural fit for this sort of problem and you can write the server-side code in JavaScript, which you already know. Even Facebook--the bastion of PHP--used a different language (Erlang) for their chat backend.
So, in summary: use socket.io. If you can, try using a different backend, although PHP is fine too.
If you don't want to use another language you can simply do it by AJAX..
Just set an interval and update the PHP-generated div's html.. and when you send a message then the reply would be the updated div -html so that both you and the user can assure that their message is posted successfully.. There's a snippet of my own chat system code : look:
function updMsg() {
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
var objDiv = document.getElementById('chatwid');
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("chatwid").innerHTML=xmlhttp.responseText;}
}
xmlhttp.open("GET","Msg.php?pg=1",true);
xmlhttp.send();
}
function sendMsg()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
msg=document.getElementById('msgfrm').value;
sender='<?php echo $name;?>';
xmlhttp.open("GET","Msg.php?msg="+msg+"&sender="+sender+"<?php if(isset($_GET['a']) && $_GET['a'] = 1) { echo "&a=1"; } ?>" ,true);
xmlhttp.send();
document.getElementById('msgfrm').value="";
xmlhttp.onreadystatechange=function()
{
var objDiv = document.getElementById('chatwid');
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("chatwid").innerHTML=xmlhttp.responseText;}
}
}
function interval() {
updMsg();
t=setTimeout(interval(),500);}
interval();
This code is actually only PHP and Javascript. It's not sufficient to include the whole jQuery Library just for using the AJAX capability. right?

simultaneously calling 2 functions via ajax with "onclick"

I have a problem using AJAX. I'm new to this so the answer could be simple!
So, i have this piece of code.
echo '<input type="button" onclick="opinion(1,\''.$v.'\'); op_status(1,\''.$v.'\');"/>';
which is written in php.
The 2 functions that are called via the onclick event, toggle AJAX in 2 different html divs. What i get is the outcome of the second function on both divs.
Any ideas why this could be happening?
Thanks!!
sorry for the inconvenience but this is my first post. so this is one of the 2 (identical, just with different variables) js scripts.
function op_status(op,pid)
{
if (op=="")
{
document.getElementById("opstatus"+pid).innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("opstatus"+pid).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","post_op_stat_disp.php?ajxpid="+pid,true);
xmlhttp.send();
}
the file that is called makes some checks and outputs a text depending on that checks at a certain html div. the other js script does exactly the same, making some other tests and outputting some other text on another html div. :) however the outputs are the same text echoed in both the divs
First I'd add "var xmlhttp = null;" at the top of your function - that will locally scope the variable instead of making it global in nature - as #David Dorward points out. That would end up assigning the response handler of the ajax request in the second declared function (which ever that happens to be second) as the response handler for both ajax requests and you'd get the behavior you describe.
If you're still getting the same text in both div's then I'd suspect that both javascript functions are calling post_op_stat_disp.php instead of the opinion function calling what I would guess to be post_opinion_disp.php and as a result it is returning the same data to each div. Or (even more unlikely) that both post_opinion_disp and post_op_stat_disp are returning the same result.
Since this problem isn't really germain to AJAX but instead is likely a coding problem - I would suggest navigating manually to http://[server]/post_op_stat_disp.php?ajaxid=test and your other url and see what should be populated in both divs.
Then I would highly suggest that you abstract your ajax code to some common function so that you are not duplicating the http status code and xmlhttp instantiation logic. And though it may not help you solve this particular problem, it would reduce your code size to something along these lines if you followed #Jared Farrish's advice and used jquery:
function op_status(op, pid) {
if (!op) return $('#opstatus' + pid).html("");
$.get('post_op_status_disp.php?ajaxid=' + pid, function(r) {
$('#opstatus' + pid).html(r);
});
}
My money is on the var key word which will ensure you get two different xmlhttp objects instead of one global one.
But as most have already commented - you might want to post the generated results to help us out in helping you track this bugger down.
Thanks, let us know how it turns out!

Updating a MySql database using PHP via an onClick javascript function

I am creating a web game for learning new words aimed at children.
I have a set of four links each displaying a specific word retrieved from my database and a clue, I need to check that the word which has been selected matches the correct word for that clue.
I know that I need to use javascript because of the onClick function and I can successfully check whether the word selected matches the correct word. However, I then need to update a score held in the database if the word is matched correctly, therefore I would need to use php.
From what I can gather this means I must use AJAX but I can't find a good example of anyone using AJAX onClick of a link to then update a database.
I have attempted to do this...but its probably completely wrong as I couldn't get it to work properly:
//This is my link that I need to use in my game.php file where $newarray[0] is that answer I want to check against $newarray[$rand_keys]
<a onClick=originalUpdateScore('$newarray[0]','$newarray[$rand_keys]')>$newarray[0]</a>
//my attempt at ajax in a score.js file
var xmlHttp;
function originalUpdateScore(obj,corr){
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
if(corr == obj){
var url="getscore.php";
//url=url+"?q="+str;
//url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
//xmlHttp.open("GET",url,true);
xmlHttp.open(url,true);
xmlHttp.send(null);
alert('Correct');
}
else
{
alert('AHHHHH!!!');
}
window.location.reload(true);
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
//Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
//attempting to update the database in a getscore.php file
<?php
//$q=$_GET["q"];
include("dbstuff.inc");
$con = mysqli_connect($host, $user, $passwd, $dbname)
or die ("Query died: connection");
$sql= "UPDATE `temp` SET `tempScore`= `tempScore`+1 WHERE (temp.Username='$_SESSION[logname]')";
$showsql = "SELECT `tempScore` FROM `temp` WHERE (temp.Username='$_SESSION[logname]')";
$result = mysqli_query($con, $showsql);
echo "$result";
mysqli_close($con);
?>
I would highly recommend learning AJAX properly - it won't take you ages but will help you understand what you can and can't do with it.
Updating a DB from a web page via AJAX is very common. I would suggest simplifying your JavaScript development using jQuery (a JavaScript library). There is a good introduction to jQuery and AJAX here.
Basically what jQuery will do is write a lot of the boilerplate code for you. What you will end up writing is something like this:
function updateScore(answer, correct) {
if (answer == correct) {
$.post('updatescore.php');
}
}
...
<a onclick="updateScore(this, correct)" ...> </a>
What you're doing here is sending a POST request to updatescore.php when the answer is correct.
Then, in your updatescore.php, you just need to have PHP code like you already do which will update the score in the database.
You can obviously do many more complicate things than this, but hopefully that will be enough to get you started.
I noticed you have "window.location.reload(true);" in your code. Why? That seems like it would make things not work.
You should try to analyze your program to find out where the problem is happening. Then you will be able to ask us a very specific question like "why does Firefox not fire the onClick handler when I click on this link" instead of just posting three pages of code. When you paste so much code, it's pretty hard for us to find your bug.
So here are the questions you should ask:
Is my HTML being parsed correctly? To me, it looks like it might not be parsed correctly because you did not put quotes around the value of onClick. You should use quotes, like: onClick="..." To find out if your HTML is being parsed nicely, you can use Firefox's View->Source feature and look at the colors it prints.
Is my onClick handler getting called? It looks like you are using alert()'s effectively so that's good.
Does the request actually get sent to my server? To determine this, you should use Firefox, and install the Firebug extension. In the "Net" panel, it will show you all the AJAX requests that are being made by your page, and it will show you the results that were returned from the server.
Is the script on my server doing the right thing? So on the server side, you can now add lines like "echo 'hello world';" and you will see that output in the Firebug Net panel, which will help you debug the behavior of your server-side script.
Is my stateChanged function getting called? Once again, use alert() statements, or write to Firebug's debug console.
Once you've narrowed your problem down, try to reduce your code to the simplest possible code that still fails. Then show us the code and tell us exactly what the symptoms of the error are.
On another note, I recommend getting this book: Javascript: The Deinitive Guide, 5th Edition by O'Reilly. It covers lots of cool stuff like AJAX and closures. It costs $50 but it's definitely a good investment because it explains things in a much more coherent way then you'll ever get from free websites.

Categories