inserting javascript variable into php/mysql - php

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.

Related

Game project updating database using ajax

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
}
});

Able to receive data using $_GET but not $_POST [duplicate]

This question already has answers here:
Send POST data using XMLHttpRequest
(13 answers)
Closed 9 years ago.
Using Ajax to communicate with server,
I am trying to pass a value to dat.php using AJAX and get another value from dat.php back. The below code works fine when I use GET but doesn't work work with POST. I need to use POST as this is sensitive information I am trying to pass. Any idea hwy this is happening.
This is my code on test.php
<html>
<body>
<form action="<?php echo $_SERVER['$PHP_SELF'];?>" method="post">
<input type="text" name="value" onchange="ch_email1(this.value)"></input>
</form>
<script>
function ch_email1(str){
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
} catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
var xl=xmlhttp.responseText
alert("Something Went wrong");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var xl=ajaxRequest.responseText;
alert (xl);
}
}
ajaxRequest.open("POST","dat.php?q="+str, true);
ajaxRequest.send(null);
}
</script>
</body>
</html>
This is dat.php
<?php
$q=$_POST['q'];
echo $q;
?>
Please note that above code works fine when I replace POST with GET. Any ides why this is happening.
This might help:
ajaxRequest.open("POST","dat.php", true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.send("q="+str);
Take a look at this page.
http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
Right now, you're sending a post request with nothing in it. Appending to the url just changes the $_GET variables.
You are mixing POST Ajax call with GET way
When you send an AJAX call with POST, you don't have to put parameter on the URL, but you must send parameters using the .send() method.
exemple:
ajaxRequest.open("POST","dat.php",true);
ajaxRequest.send("q=" + str);
You should use a JS librairy like jQuery or other, that will make it for you, instead of re-inventing the wheel and have common problems.

PHP, run code without opening windows on the webbrowser

If I have a list of elements, and via javascript the user moves the elements in another order, can I, after each move, launch a php code (like a php page) but without having to call it in the browser?
Create an XmlHttpObject for the URL, send() it, check results to see if the call was successful, and discard the responseText. As an example, suppose you have the new order in a variable testUrl, e.g., "http://domain.com/script.php?order=1,4,3,2"
var xmlHttpObject = new XMLHttpRequest();
xmlHttpObject.open("GET", testUrl, false);
xmlHttpObject.send();
var xmlText = xmlHttpObject.responseText;
if (xmlText == 'Success')
// do nothing
else
alert (xmlText);
An addition to the above answer - for the sake of posterity, in case someone has to debug your code some day :) I use the following function call to get that object: (I believe it makes the JS more readable and portable). You can check the return value and if null, alert the user that AJAX is not supported by the browser.
function getXmlHttpObject () {
var xmlHttpObject = null;
try {
xmlHttpObject = new XMLHttpRequest();
} catch (ex) {
try {
xmlHttpObject = new ActiveXObject('Msxml2.XMLHTTP');
} catch (ex) {
xmlHttpObject = new ActiveXObject('Microsoft.XMLHTTP');
}
}
return xmlHttpObject;
}

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);

Calling PHP Function within Javascript

I want to know is it possible to call a php function within javascript, only and only when a condition is true. For example
<script type="text/javascript">
if (foo==bar)
{
phpFunction(); call the php function
}
</script>
Is there any means of doing this.. If so let me know. Thanks
PHP is server side and Javascript is client so not really (yes I know there is some server side JS). What you could do is use Ajax and make a call to a PHP page to get some results.
The PHP function cannot be called in the way that you have illustrated above. However you can call a PHP script using AJAX, code is as shown below. Also you can find a simple example here. Let me know if you need further clarification
Using Jquery
<script type="text/javascript" src="./jquery-1.4.2.js"></script>
<script type="text/javascript">
function compute() {
var params="session=123";
$.post('myphpscript.php',params,function(data){
alert(data);//for testing if data is being fetched
var myObject = eval('(' + data + ')');
document.getElementById("result").value=myObject(addend_1,addend_2);
});
}
</script>
Barebones Javascript Alternative
<script type="text/javascript">
function compute() {
var params="session=123"
var xmlHttp;
var addend_1=document.getElementById("par_1").value;
var addend_2=document.getElementById("par_2").value;
try
{
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("No Ajax for YOU!");
return false;
}
}
}
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4) {
ret_value=xmlHttp.responseText;
var myObject = eval('(' + ret_value + ')');
document.getElementById("result").value=myObject(addend_1,addend_2);
}
}
xmlHttp.open("POST", "http://yoururl/getjs.php", true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(params);
}
</script>
No that's not possible. PHP code runs before (server-side) javascript (client-side)
The other answers have it right.
However, there is a library, XAJAX, that helps simulate the act of calling a PHP function from JavaScript, using AJAX and a particularly designed PHP library.
It's a little complicated, and it would be much easier to learn to use $.get and $.post in jQuery, since they are better designed and simpler, and once you get your head around how they work, you won't feel the need to call PHP from JavaScript directly.
PHP always runs before the page loads. JavaScript always runs after the page loads. They never run in tandem.
The closest solution is to use AJAX or a browser redirect to call another .php file from the server.

Categories