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;
Related
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);
So I have this code :
function checkStatus()
{
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)
{
if (xmlhttp.responseText == "1") {
document.getElementById("maincontent").innerHTML = '<br/><br/><center>Please refresh the page to continue.</b></center>';
}
}
}
xmlhttp.open("GET","file.php?id=1",true);
xmlhttp.send();
}
and I'm wondering about the last 2 lines (xmlhttp.open and xmlhttp.send) , what is the function of these ? also when i go to file file.php?id=1 using the browser it only displays "0" whereas the the general function of the code is to redirect me to a website after i do a specific action and i believe the data is stored on file.php?id=1 but how can i see it from browser ?
Note: I'm not HTML/PHP programmer but i recognize the basics
The lines before xmlhttp.open() just create the XMLHttpRequest object that will handle the AJAX connection. Calling xmlhttp.open() is necessary to actually open the connection and xmlhttp.send() to send the request. Only after the request is sent, a response can be received and handled by the onreadystatechange handler.
This code looks rather obsolete, however. I would recommend not using XMLHttpRequest directly but rather use a library for it - see jQuery, for example.
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 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.
Even if I remove the if statements, only one of these following will work at one time. To get the former to work, I have to comment out the latter.
<?
if(isset($_POST['region'])){
echo "<script> showRecords('".$_POST['region']."','region','country') </script>";}
if(isset($_POST['country'])){
echo "<script> showRecords('".$_POST['country']."','country','provice') </script>";}
?>
The script is referring to this:
function showRecords(str,column,nextDiv)
{
if (str=="")
{
document.getElementById(nextDiv).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(nextDiv).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","get"+column+".php?"+column+"="+str,true);
xmlhttp.send();
}
The script leads to a very simple set of pages where that list some values based on some $_GET information.
I just cannot understand why it is only allowing me to do one of these scripts at a time. I even tried cloning the function to showRecords2, and it will still only do showRecords or showRecords2.
Replace xmlhttp=new XMLHttpRequest() with var xmlhttp=new XMLHttpRequest(). Notice the var keyword added. What happened is xmlhttp is becoming a global scope variable and it gets overwritten with new values/argument/parameters everytime you make a request e.g. calling showRecords twice while the first one is still doing stuff the second call overwrites it.
Remember to make all your variables in the function level to avoid overwrites unless they are actually gonna be used in the global scope. It's time consuming to debug this kind of issues especially when you don't know where to find stuff. Hope that helps!