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.
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);
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 want to implement twitter like user flow interface, i.e. when user goes to
http://twitter.com/#!/abc the page is loaded.
I have tried to implement this at:
http://forum.abhibhatia.co.cc/ajax/
What I try to do is that as soon as page loads, the url is splitted by "#!/" and secon part is loaded so that http://forum.abhibhatia.co.cc/ajax/posts.php can be accessed at http://forum.abhibhatia.co.cc/ajax/#!/posts.php . The problem I am facing is that the page does not change after I redirect user using window.location
it does not work. I have not tried any other way to redirect users yet.
here is the javascript function used:
function geturl(){
var url=window.location.toString();
var a=url.split("#!/");
if(a.length==1)
a[1]='data.php';
return a[1];
}
function fetchPage(){
var url=geturl();
var xmlhttp;
if (url.length==0&&m==1)
{ url='data.php';
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==1) document.getElementById("data").innerHTML="Loading...";
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var file=xmlhttp.responseText;//alert(file);
var contents=file.split("<head>");//alert(contents[0]);
var useable=contents[1].split("</head>");
var head=useable[useable.length-2];//alert(head);
var body=useable[useable.length-1].split("</body>");
document.getElementById("data").innerHTML=body[0];
document.head.innerHTML=document.head.innerHTML+head;
//document.getElementById("data").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
fetchPage();
look closer at the window.location object you can use window.location.hash but as mentioned before hashbangs are a bit old these days I'd be much more inclined to use the html5 state management with standard hashes # as a fallback.
some further reading:
https://developer.mozilla.org/en/DOM/window.location
http://www.adequatelygood.com/2010/7/Saner-HTML5-History-Management
If you really want to make a twitter style interface you should look to put the whole app on a framework which does all of this for you like backbone.js which will mean that you just need to use a REST/CRUD style data source and then will implement all of the state managemet and hash fallbacks for you.
I am using AJAX in form of jQuery for my client side scripting and twitter bootstrap for the layout, also using php for my server side scripting.
But the problem is the application runs fine on all other web explorers apart from Internet Explorer, does anyone have an idea to why this is happening, I cant even open a drop down in IE and I've tried both version 8 and 9.
here is a basic example of my jquery call to the server
function check_module() {
var option = $('#modules option:selected').attr('value');
$.post('modulesDropDown_1.php', 'option='+option,
function(data){
var obj = jQuery.parseJSON(data);
console.log(obj);
var name = $("#modules option:selected").text();
$("#moduleCode").html(obj.allInfo.code);
});
return false;
}
i have a lot of these in my code, where the im calling to the server and returning it as json to the client... for instance i have a drop down which populates another drop down below soon as a value first drop down is chosen (AJAX), but the second drop down should then update the page based on the value but it just does not work in IE.
Older versions of IE use a different mechanism for creating AJAX requests. Try something like this:
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");
}
although since it doesn't run on IE 8 and 9 that might not solve it.
It would help to see a snippet of code.
(Example from http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first)
My problem is the following:
I have a real simple PHP file called "writeSettings2.php" that has:
<?php
$text=$_GET["text"];
setcookie("MG_FileTree_Opener_SelPath", $text);
?>
And then I have my PHP page, in which I have a JavaScript function called "makeChanges", this function is called in a input type submit function and gets the combobox selected value and calls through xmlhttp the PHP function above like so:
<input type="submit" id="choice" value="Escolher" name="Esc" onClick="makeChanges()">
And the function "makeChanges" is like:
function makeChanges( )
{
var selObj = document.getElementById('opiniao');
var selIndex = selObj.selectedIndex;
var str = selObj.options[selIndex].text;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","writeSettings2.php?text="+str,true);
xmlhttp.send(null);
history.go(0);
}
Basically what I'm doing is use the JavaScript on the client fo call PHP function to rewrite the client cookie, and then refresh the page to get PHP to rewrite the page with the new info on the cookie.
This code works fine, but only for the fist 2 times! For instance my combox has item 1 and 2.
I load it and is item 1.
Change to item 2.
Change back to item 1.
Change to item 2 again ---- FAILS never changes again, it always remains on 1.
Any suggestions?
Your browser is caching the ajax response. You need to add a random value to the ajax request, or put the no-cache header in the called page.
You can change the javascript like so to fix it:
var str = selObj.options[selIndex].text+'&random='+(new Date()).getTime();
And/Or use the following php header:
header("Cache-control: no-cache");