Why is this Javascript not triggering an Ajax event? - php

I have a forum of sorts, and I want to automatically refresh the posts every so often. I am using Ajax when the page loads to start and later I will implement the auto refresh. The problem I am having is (I believe) inducing a Ajax request. I have an event handler for the Ajax request to take place when I click my header (for purposes of debugging). I won't post all of my code, just the most relevant sections here, but if you want you think there is probably a problem in my code elsewhere, feel free to check out www.ethoma.com/testhome.php which sends a request to www.ethoma.com/getposts.php.
Ajax requesting function:
function getPosts(category, page, sort)
{
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("postcontainer").innerHTML=xmlhttp.responseText;
}
}
var queryString = "?category=" + category + "&page=" + page + "&sort=" + sort;
xmlhttp.open("GET","getuser.php" + queryString,true);
xmlhttp.send();
}
My PHP page should return the correct html code through an echo call. On a side note, it is okay to embed html tags within the code I return through my PHP page (novice question)?
If you think the problem is not in this code snippet, again feel free to browse those two pages. Thanks to everyone who views/answers this question -- everyone here is very helpful.

I've looked at the live version of your site and ran it with a breakpoint in onreadystatechange. The reason you don't see anything is that getuser.php 404's.
In particular the called URL is http://www.ethoma.com/getuser.php?category=[object%20HTMLAllCollection]&page=1&sort= (I'm quite sure the category is a bug) and yields 404, onreadystatechange is then called with readyState=2 and status=404

Related

Updating database without form data in CakePHP

This may be a no brainer for some of you but I'm really scratching my head on this one. I started using CakePHP and got hooked on it but it is different than regular PHP (they use some shorthand for a lot of coding). At any rate, I'm trying to update my database when a button is pressed without having the user to enter in new data in a form. Currently I'm using AJAX and a button tag that calls the javacript function. It's supposed to be as if you are registering for a class that will be added to "My Courses"later (populated by the enrolment [sic] table in the database). This is the AJAX code:
<script>
function loadXMLDoc()
{
var xmlhttp;
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("alert").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","/Enrolments/register.php",true);
xmlhttp.send();
}
</script>
In hindsight it seems silly to need the if statement that checks for IE6 and below but that was just the W3 recommendation. This is what what follows for the button:
<button onclick="loadXMLDoc()">Register</button>
And of course there is some content on the page (a video to preview the course). This is what the register.php looks like:
<?php
$user = $this->Session->read('Auth.User');
$id = $user['user_id'];
$this->Status->read(null, $id);
$this->Status->set('course_id', 1);
$this->Status->save();
echo "You are now registered for this course";
?>
I didn't add a look up for the correct course_id to be added. I was just trying to test it by passing a "1" for that field (currently the enrolment [sic] table has only two columns- user_id and course_id) to see if it would actually update the database. Presently, it does not. Any advice would be great.
Edit: To be clear, I'm trying to make it where the enrolments table is updated with the following information upon clicking "Register": user_id = the current user_id, course_id = 1.
From #Guillermo comment this seems not to be cakephp's way to do it, however when using post:
xmlhttp.open("POST","/Enrolments/register.php",true);
you need to at least set this header also:
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
But if you can live with the character limits of a simple get, just use it:
xmlhttp.open("GET","/Enrolments/register.php",true);

Using AJAX for GET data from other server on Mouse Over

I am searching for this from yesterday, Do not know, I am unable to implement, or going in wrong direction.
My currently ajax function which is working with local server
function tooltipajax(r_ID)
{
var str ;
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('span'+ r_ID).innerHTML = xmlhttp.responseText ;
}
}
xmlhttp.open("GET","accounteditajax.php?key=" +r_ID,true);
xmlhttp.send();
}
PHP code:
print("<tr bgcolor=\"#EEEEEF\">");
print("<td class='normal' id=\"serialno\" onMouseOver='tooltipajax(this.id)'>
<a class=\"tooltip\" >Serial Number <span id=\"spanserialno\"
class=\"custom info\"></span> </a></td>");
print("<td bgcolor = \"#FFFFFF\" ><b>$serial</b></td>\n");
print("</tr>\n");
How can I get data from another server?
xmlhttp.open("GET","accounteditajax.php?key=" +r_ID,true);
I want to get from
http://iphere/filename.php
If you use use jQuery like so, this works.
function tooltip_ajax(r_ID) {
$.ajax({
url: "http://iphere/filename.php?id=" + r_ID,
context: document.body,
success: function(data) {
if(data) {
$('span' + r_ID).html(data);
}
}
});
}
That's tested with a different server and it works.
In order to retrieve data from another server using AJAX, you will need to utilize JSONP. This is due to Cross-Domain restrictions on AJAX requests. To expand on this further, if you wanted to make an AJAX request from a page located at http://test1.com, to a page / script located at http://test2.com, you would not be allowed.
Check out this article for more information: http://www.jquery4u.com/json/jsonp-examples/
Basically, JSONP involves adding a temporary SCRIPT tag to the page, which CAN load external content. The URL for this SCRIPT tag contains data, and a callback function name. The JSONP should then respond with the data, enclosed in a call to that function. Of course, the one downside is that the target server must support JSONP requests.
One alternative is using a bridge PHP script locally, that utilizes CURL to make the request, and return the information to your page, via AJAX.
For a bit more information regarding utilizing CURL in PHP, take a look at this article: http://codular.com/curl-with-php

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?

Embedded XMLHttpRequest (AJAX calling a page which also uses AJAX)

I have an embedded XMLHttpRequest problem;
The flow of data should go like this:
Interface.php uses modifyRecords.js (XMLHttpRequest) to call information from modifyRecords.php, which in turn uses showRecords.js (XMLHttpRequest) to call information from showRecords.php.
If I could somehow accomplish this, it would save a ton of code copying and/or rewriting.
When I backtrack to find where the errors are, there doesn't appear to be any problem showRecords.php and modifyRecords.php both load fine individually, just when AJAX calls another AJAX it totally breaks.
The nitty gritty is this:
My user interface is calling modifyRecords.js which is as follows;
function modifyRecords(cell,report,column,oldValue)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
var xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById(cell).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","modifyRecords.php?report="+report+"&column="+column+"&oldValue="+oldValue,true);
xmlhttp.send();
}
modifyRecords.php is calling another AJAX function called showRecords.js;
function showRecords(str,column,nextDiv,oldValue)
{
if (str== null)
{
document.getElementById(nextDiv).innerHTML="----------------------------------------";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
var xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById(nextDiv).innerHTML=xmlhttp.responseText;
document.getElementById(nextDiv).value = oldValue ;
}
}
xmlhttp.open("GET","showRecords.php?"+column+"="+str,true);
xmlhttp.send();
}
The problem is that each one of these works in isolation, however, when I use one AJAX function to call a page that is dependent on the second AJAX function, the records do not load.
I know this has something to do with synchronicity, because my only guess is that the referenced page has not finished loading when the referencing function is calling it.
I have tried setting the parameters to "false" for synchronous, instead of the usual asynchronous, however that breaks either function.
What would be the best solution?
I have considered combining all my AJAX functions, which would require a ton of rewrite to make them more generic, and functional for both environments.
Unless I'm much mistaken, you are trying to call your second AJAX script by setting the innerHTML of an element with the first?
Scripts aren't executed when added with innerHTML. Don't know why, it's been an annoyance to me, but you'd probably be better off separating HTML and JS, then putting the HTML in the innerHTML, and eval'ing the JS.

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!

Categories