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);
Related
i build system notifications and have me problem.
i want update table 'notifications' after onclick from 'new=1' to new='0' for a user logged.
how i update at database after onclick with ajax or something other.
if i send request server with ajax as this:
function readNotifications(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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","controlpanel.php?notification=readNews",true);
xmlhttp.send();
}
The server does not know which USER ID to update the alerts.
And if I send USER ID at time be possible to change the USER ID and everyone can update the notifications of each other and this a not security.
I'm sorry for my English, if I do not understand you can ask a question.
Thank you!
I think its better for you to save the user_id in a session variable once the user logs in.
<?php
session_start();
// store session data
$_SESSION['user_id']=100001;
?>
and access it from your code behind during the processing of your ajax request.
$_SESSION['user_id']
AND
if you use cookies, you can still accept that from your server side code.
$_COOKIE["user_id"];
will do it.
just make sure that, you set the withCredentials property to true.
var req= new XMLHttpRequest();
req.withCredentials = true;
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?
I have a database where a Facebook User ID, Facebook User Name and mail address is written. When the document loads I want to check if a given ID (stored in a javascript value) already exists in the database. So what I would have to do is check with PHP if my Javascript variable (value) exists in the database. Any ideas how to do this?
Probably the easiest way would be to fire a XHR (AJAX) request to your server (PHP script) that contains the ID, and then check for the existence of that ID on the server.
You can do this using ajax.
using jQuery for example:
$.post("check.php",{id: your_var},function(data){
alert(data);
});
check.php holds your php code that checks the db.
I think you need AJAX.
For example:
<script>
//user id
var uid = '100';
//AJAX create
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");
}
//GET request create and send
xmlhttp.open("GET","checkuser.php?uid="+uid,false);
xmlhttp.send();
//Good. in "xmlhttp.responseText" will store true or false (user exist or not)
alert(xmlhttp.responseText); //check answer from PHP
</script>
Ok. Now PHP script.
//this is checkuser.php
<?php
$uid = int()$_GET['uid'];
echo (bool)functionForCheckIdInDB($uid);
?>
p.s. of course with jQuery it easier.
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
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!