Game project updating database using ajax - php

Im trying to make a realtime game with no page refresh.
The problem is that i dont know what to do next or how to configure ajax script to update the mysql database when the player is movine over the map.
Here is the ajax code im trying to use.
//calling ajax to update player location when he move around
function send(url){
var request;
try{
request= new XMLHttpRequest();
} catch (e){
try{
request= new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
request= new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser broke!");
return false;
}
}
}
request.onreadystatechange = function(){
if(request.readyState == 4){
//I dont know what to add here :-(
}
}
request.open("GET", url, true);
request.send(null);
}
send("update_location.php?newX="+ toX + "&newY=" + toY)
update_location.php
<?php
$new_x=$_GET['newX'];
$new_y=$_GET['newY'];
//echo"$new_x , $new_y";
$update_loc=mysql_query("UPDATE users SET location_x='$new_x' WHERE username='admin'");
?>
The main ideea is that when the player moves anywhere over the map the ajax updates new x and y values into the database.I dont need any button or jquery code added,i think ajax will work fine if somebody get me a hand doing this.
P.S. toX and toY are javascript vars wich i transformed to php vars so i can update them to mysql datavase.If somebody could help me do this i would really appreciate!

First sort out what you are trying to do in this case. From your description I dont think its clear.
If you want to do something based on your ajax response, then onSucess is the right option and not onreadystatechange.
If you want to do something on Ajax response, then you should send the required data from the server side and use it to perform required actions in your javascript code.
E.g..
new Ajax.Request('testurl',{
method: 'post',
parameters: {param1:"A", param2:"B", param3:"C"},
onSuccess: function(response){
//do something here
}
});

Related

How to receive jQuery post response before completing execution of PHP script?

I have a simple jquery function that sends a post request to a PHP file like this:
$.post('/file.php',
{
action: 'send'
},
function(data, textStatus)
{
alert(data);
});
And a PHP file:
<?php
/* Some SQL queries here */
echo 'action done';
/* echo response back to jquery and continue other actions here */
?>
jQuery by default waits till executing the whole PHP script before giving the alert. Is there a way to alert the action done before executing the rest of the PHP file??
Thanks
It is possible with plain Javascript ajax. The onreadystatechange event will fire with a readyState of 3, when data is received before the request is complete.
In the example below, newData will contain the new piece of data. We have to do some processing because the XHR actually gives us the entire data so far in responseText and so if we only want to know the new data, we have to keep a record of the last index.
var httpRequest, lastIndex = 0;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.onreadystatechange = function() {
if(httpRequest.readyState === 3) {
var newData = httpRequest.responseText.substring(lastIndex);
lastIndex = httpRequest.responseText.length;
console.log(newData);
}
};
httpRequest.open('POST', '/file.php');
httpRequest.send('action=send');
As for jQuery ajax, this answer suggests jQuery lets you bind to the readystatechange but I haven't tested it.

change images in clients browser on my demand

I have a friend who call his clients by phone. He want to present his product on his website.
But to be sure they look at the product he want to sell, he want them to go to a page where he can change images by demand. Like running a powerpoint presentation in the clients browser.
If the client for example need other features he can show another image.
During phone call client go to a specific page on my friends website.
The image shown, or html data, change on demand by my friend.
Can this be implemented easily by AJAX?
Sure!
Client side:
<script type="text/javascript">
//The first image to load
CurrentImage="http://images.google.com/intl/en_ALL/images/logos/images_logo_lg.gif";
//The Image, eg: <img id=imgBox src=foo.jpg>
ImgBox = document.getElementById('imgBox');
function CheckForImg()
{
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
try
{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Ajax is kinda disabled :(\n you won't be able to do some stuff around :(");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var str = ajaxRequest.responseText;
if(str != CurrentImage) // we have a new image
{
ImgBox.src = str;
currentImage = str;
}
}
ajaxRequest.open("GET", "getCurrentImagUrl.php", true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
ajaxRequest.send(null);
}
</script>
Now we need a way to keep the client posted, so either we put that to a frequency, or show a button to press which is way better and more efficient:
Method 1(Button):
<Button onclick="CheckForImg();">Check For Image!</button>
Method 2(Periodically check):
Simply call
SetInterval("CheckForImg", 5000);
I'll leave the server side for you :)
Any further help is kindly offered.

How to pass javascript variables to a database

i have an application in javascript. I follow some tutorial to do it, but i really don't have experience with the javascript code. The problem is that i need to pass the variables results from javascript to mysql database. I have found some answers in this site and i try to do what i found with no luck. What i found is that i need ajax and php. I never use ajax and because of that i dont understand what i'm doing wrong.
Maybe if i put the code here, someone can help me with a solution.
This is the javascript code:
function ajaxFunction(){
var ajaxRequest;
try{
Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.myForm.time.value = ajaxRequest.responseText;
}
}
ds = new Date();
e_time = ds.getTime();
var res = new Object();//This are the results variables that i need to pass to my database
res.bytes_transfered =;
res.total_time_seconds = (e_time-s_time)/1000;
res.generatied_in = ;
res.ip = "";
-->
var res1= 'res.bytes_transfered';
var res2= 'res.total_time_seconds';
var res3= 'res.generatied_in';
var res4= 'res.ip';
$.post('insert.php',{res.bytes_transfered:res1,res.total_time_seconds: res2, res.generatied_in: res3, res.ip:res4});
var queryString = "?res.bytes_transfered=" + res.bytes_transfered + "&res.total_time_seconds=" + res.total_time_seconds + "&res.generatied_in =" + res.generatied_in + "&res.ip =" + res.ip;
ajaxRequest.open("POST", "insert.php" + queryString, true);
ajaxRequest.send(null);
new Ajax.Request('insert.php', {
onSuccess : function(xmlHTTP) {
eval(mlHTTP.responseText);
}
});
This is the insert.php:
$fecha= date("Y-m-d H:i:s");
$connnect= mysql_connect("localhost", "root", "xxxxxxxxx");
mysql_select_db("dbname");
$res1= mysql_real_escape_string($_POST['res1']);
$res2= mysql_real_escape_string($_POST['res2']);
$res3= mysql_real_escape_string($_POST['res3']);
$res4= mysql_real_escape_string($_POST['res4']);
$queryreg=mysql_query("INSERT INTO grafico(Cantidad, Tiempo, IP, Bajada, Subida, Fecha) VALUES ('$res1','$res2','$res3','$res4','0','$fecha') ");
if (!$queryreg) {
die('No se ha podido ingresar su registro.');
}
else{
die("Usted se ha registrado exitosamente!");
}
I hope that somebody can help me. I dont know what to do!
It looks like your POST data has the keys and values backwards. In the data passed to $.post the key name needs to come first and the value after the :. So I think it should be:
$.post('insert.php',{res1:res.bytes_transfered,res2:res.total_time_seconds,res3:res.generatied_in, res4: res.ip});
What you need to do is have JavaScript pass your variables to PHP, which in turn will use it in your MySQL statements (most probably via PDO in PHP).
Now, what is AJAX then? Well it is the modern way that will help you send data from JavaScript to PHP and get a response back from PHP to JavaScript WITHOUT the need to refresh or reload the page.
So in conclusion, JavaScript makes an AJAX call, that call will send data to PHP which will do something with MySQL, and then respond back to JavaScript with your results.
You need to comment out a couple of lines so that it won't be interpreted as code
//Opera 8.0+, Firefox, Safari
Your Ajax code only creates the ajax object and sets up an event listener, it never actually makes a request, so of course it cannot work. The request would look something like this
ajaxRequest.open("post", "/myphppage.php", true);
...
ajaxRequest.send("somevariable=" + variable);

Ajax to read PHP

I think I'm getting ahead of myself, but I tried AJAX tutorials to read from a PHP file. The PHP file simply has an echo statement for the time, and I want to pass that to initialize a javascript clock.
But this is my first time trying AJAX and I can't even seem to get it to activate a test alert message.
Here is the code, it's at the bottom of my PHP page after all of the PHP.
<script type='text/javascript'>
function CheckForChange(){
//alert("4 and 4");
//if (4 == 1){
//setInterval("alert('Yup, it is 1')", 5000);
//alert('Now it is changed');
//}
var ajaxReady = new XMLHttpRequest();
ajaxReady.onreadystatechange = function(){
if (ajaxReady.readystate == 4){
//Get the data
//document.getElementById('clocktxt').innerHTML = ajaxReady.responseText;
alert("here");
alert(ajaxReady.responseText);
}
}
ajaxReady.open("GET","ServerTime.php",true);
ajaxReady.send(null);
}
setInterval("CheckForChange()", 7000);
</script>
Can somebody tell me why this isn't working? No idea what I'm doing wrong.
The problem in your code is an uncapitalized letter. (Oops!) You check ajaxReady.readystate; you need to check ajaxReady.readyState.
Because ajaxReady.readystate will always be undefined, your alerts never fire.
Here's your code fixed and working.
As an aside, have you considered using a library to handle the ugliness of cross-browser XHR? jQuery is your friend:
function CheckForChange(){
$.get('ServerTime.php', function(data) {
$('#clocktxt').text(data);
});
}
You should probably have something like:
setInterval(CheckForChange, 7000);
On an unrelated note, it's common naming convension in JavaScript to have function and methods names' first letters not capitalized, and the rest is in camelCase. i.e. checkForChange().
I'm not sure the exact problem with your code; here's what I use -- I'm sure it will work for you. (plus, it works with more browsers)
var xhr = false;
function CheckForChange(){
/* Create xhr, which is the making of the object to request an external file */
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
if(window.ActiveXObject){
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
}
}
/* End creating xhr */
/* Retrieve external file, and go to a function once its loading state has changed. */
if(xhr){
xhr.onreadystatechange = showContents;
xhr.open("GET", "ServerTime.php", true);
xhr.send(null);
}else{
//XMLHTTPRequest was never created. Can create an alert box if wanted.
}
/* End retrieve external file. */
}
function showContents(){
if(xhr.readyState==4){
if(xhr.status==200){
alert(xhr.responseText);
}else{
//Error. Can create an alert box if wanted.
}
}
}
setInterval(CheckForChange, 7000);

inserting javascript variable into php/mysql

I have two file one is index.php another one is dbsubmit.php
In my index.php i got some javascript variable in between script tag..
var address = "Address of some places";
var latitude = 79.00256978;
var longitude = 125.89564725;
i want to pass these variables into my php script (dbsubmit.php) so that i can populate MySQL database. How can i solve this problem?? can anybody help me??
You could use something like this and than in php using $_GET you can retrieve the values
<script>
function send(url){
var request;
try{
request= new XMLHttpRequest();
} catch (e){
try{
request= new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
request= new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser broke!");
return false;
}
}
}
request.onreadystatechange = function(){
if(request.readyState == 4){
//alert(request.responseText); this would be the value we get back, anything php would print would be alerted here
}
}
request.open("GET", url, true);
request.send(null);
}
send("dsubmit.php?address="+address+"&latitude="+latitude+"&longitude"+longitude);
</script>
You can use AJAX to pass the variables to a PHP script, which in turn will be able to write them to a database.
Are you using some sort of javascript framework (jQuery, etc.) ? Because they make it really easy.
You just have to make another php script to get the variables from $_GET or $_POST and save them. AJAX effectively calls the php script passing it those vars.

Categories