I'm trying to execute a PHP script that updates a MySQL DB on click of an image. I'm using a snippet I found online to do so:
function execute(filename,var1,var2)
{
var xmlhttp;
if(window.XMLHttpRequest)
{
//Code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
//Code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support AJAX!");
}
var url = filename+"?";
var params = "id="+var1+"&complete="+var2;
xmlhttp.open("POST", url, true);
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
//Below line will fill a DIV with ID 'response'
//with the reply from the server. You can use this to troubleshoot
//document.getElementById('response').innerHTML=xmlhttp.responseText;
xmlhttp.close;
}
}
//Send the proper header information along with the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
}
With this link: <a href="javascript:void(0);" onclick="execute(games_do.php,<?=$game['appid']?>,<?=$complete?>)" > </a>
And games_do.php contains:
$appid = $_GET['id'];
$complete = $_GET['complete'];
mysql_query("UPDATE ownedgames SET complete='".$complete."' WHERE steamid='".$steamid."' AND appid='".$appid."'") or die(mysql_error());
However, nothing seems to happen on click. Any suggestions would be greatly appreciated! :)
The parameter values for the execute function in the <a> tag should be enclosed within quotes as the function expects a string as the value.
In addition, the point mentioned in D. Schalla's answer should also be considered.
There are several prolems with your code:
First of all, you should always escape or type-cast your code, because you have SQL Injections made possible in your code:
$appid = $_GET['id'];
$complete = $_GET['complete'];
to:
$appid = intval($_GET['id']);
$complete = mysql_real_escape_string($_GET['complete']);
Also I would change the mySQL Driver from mysql_ to PDO later, since it might be that it will be unsupported in a later version of PHP.
But however, to find the problem in your code I would debug the request using Firebug (an Firefox Addon) or the Chrome Developer Console. Check what the Request Returns, it might be an mySQL Error relating to your Database Design.
To do so, check in Chrome under the Tab Network in the Console the "Answer" of the AJAX Request, when there is an error, it will be displayed there.
I would also switch to jQuery if you plan to work more heavy with AJAX, since it handles the fallback solutions for some browsers and offers an more easy integration, you can find a doc relation this there:
http://api.jquery.com/jQuery.ajax/
Change mysql_query("UPDATE ownedgames SET complete='".$complete."' WHERE steamid='".$steamid."' AND appid='".$appid."'") or die(mysql_error());
to this:
mysql_query("UPDATE ownedgames SET complete='$complete' WHERE steamid='$steamid' AND appid='$appid'") or die(mysql_error());
Further, you can make your ajax call easier with jQuery, if you're not using it, I strongly suggest you do. It would make it as this:
function execute(filename,var1,var2){
$.ajax({
type: "POST",
url: filename,
data: {id:var1, complete: var2}
}).done(function( result ) {
//do whatever you want to
});
}
as for your link, you should try this:
<?php
$id=$game['appid'];
echo('<a onclick=execute("games_do.php","'.$id.'","'.$complete.'")>Click Here </a>');
?>
Related
Right up front...I am very new to using Ajax.
I'm working on a web site where I want the results of one Select object to determine the options in the second Select object(from a database query). I'm using PHP and it appears that the only way to do this is to use Ajax. I've written a short html page to test my Ajax knowledge and it seems to work just find on Firefox but not on Chrome or IE. I've done a lot of research and found all sorts of folks with similar problems but no real solution.
I'm making the XMLHTTPRequest call to a local file in the same folder even so I should not be experiencing any cross-domain problems. Any help would be greatly appreciated.
Here's my Javascript function that gets called when the Select box is changed:
...
function getData(str)
{
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.open("GET","ajax_info.php?color=",true);
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.send();
alert(xmlhttp.responseText);
}
********ajax_info.php
+++++++++++++++++++++
//this is the php file that runs in response to the xmlhttprequest. It just generates a string of number at this time.
<?php
$str = "";
$i = 0;
for($i; $i<1000; $i++)
{
$str = $str.$i."-";
}
echo $str;
?>
You need to attach an event handler to your xmlhttp object to catch the onreadystatechange event. Note that when you alert your value, the asynchronous ajax call has just fired and has not finished yet (you are not checking for that anyway):
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET","ajax_info.php?color=",true);
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.send();
Well in that case you should try jQuery. It will be lot easier for you to make ajax request.
Here is an example for your problem
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
// FOR GET REQUEST
$.get("ajax_info.php",{color:'value'},function(data) {
alert(data); // RETRIEVE THE RESULT
});
</script>
Here I have a script which help me to get places from google places API. So now I want to store all this into mysql but how? I'm new to mysql and php, and how to store data that I get from google places to database?
What I need to do here? Can someone show me on my example...
How to combine php and javascript;
CODE: http://jsbin.com/AlEVaCa/1
So I need to store data which I got from google:
google.maps.event.addListener(marker,'click',function(){
service.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var contentStr = '<h5>'+place.name+'</h5><p>'+place.formatted_address;
if (!!place.formatted_phone_number) contentStr += '<br>'+place.formatted_phone_number;
if (!!place.website) contentStr += '<br><a target="_blank" href="'+place.website+'">'+place.website+'</a>';
contentStr += '<br>'+place.types+'</p>';
infowindow.setContent(contentStr);
infowindow.open(map,marker);
} else {
var contentStr = "<h5>No Result, status="+status+"</h5>";
infowindow.setContent(contentStr);
infowindow.open(map,marker);
}
});
});
I want to store all place.name,website ... etc. data to mydatabase. How to do that?
Is there any way to store this data?
Use AJAX to send data to PHP file.
Use jQuery $.post()-AJAX method to send data to php file
data = "name="+name+"&place="+website;
$.post('file_to_store.php', data, function(data) {
//Here you can get the output from PHP file which is (data) here
});
Pure javascript way
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("myDiv").innerHTML=xmlhttp.responseText;
}
}
data = "name="+name+"&place="+website;
xmlhttp.open("POST","file_to_store.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(data);
}
In file_to_store.php receive all data from $_POST[] global array
if(isset($_POST)){
$name = $_POST['name'];
$website = $_POST['website'];
//Do same for all other variables
//Steps to insert Data into Database
//1. Connect to database
//2. Select Database
//3. Generate Database Insert Query
//4. Run mysql Query to insert
// Return appropriate return back to Javascript code - Success or Failure
}
Use serialize($data) then put it into database, use unserialize() after getting data from db.
Addition: this will store raw data, you'll probably need a parser also.
Addition 2: sorry I assumed that you got an array.
Alternative solution if you got non-array data:
you can use base64_encode($raw_data) to store and base64_decode($encoded_data) to use the encoded data coming from SQL.
Fundamentally, your JavaScript program, executing on the client side, does not have direct access to the SQL database on the host. You must use AJAX to issue requests to the host, and the host-side software must be programmed to handle them. Lots(!) of existing tutorials on this subject are already out there ... everywhere.
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);
This is my function:
<script type="text/javascript">
function loadXMLDoc() {
var x = document.getElementById("trazi_drzava");
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("trazi_grad").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "gradovi.php?selected=" + x.value, true);
xmlhttp.send();
}
</script>
and I call it like this:
<select name="td" id="trazi_drzava" onchange="loadXMLDoc()">
<option value="">Država</option>
<?php
$sel_grad_arr=array();
$sel_grad_arr[]="<select name='tg' id='grad0'>
<option value=''>Grad</option</select>";
if($q=mysql_query("SELECT drzava_id,drzava FROM drzava")){
while($r=mysql_fetch_assoc($q)){
echo '<option value="'.$r['drzava_id'].'">'.$r['drzava'].'</option>';
}
}else echo mysql_error().__LINE__;
?>
</select><select name="tg" id="trazi_grad">
//code that ajax should load
</select>
It works fine with most browsers, but with Internet Explorer 9 it doesn't work at all. Anyone have any idea why?
UPDATE: I didn't manage to do this then. So I changed logic of working totaly. Thanks everyone for answers.
I know this is a very old question, but still, one with no actually correct answer....
The correct order of operations is:
Create your request object
open a connection
Set onreadystatechange listener
send request
You have steps 2 and 3 in the wrong order, which causes problems in certain browsers.
Maybe it's a cache problem. Parameter test set as a timestamp value, something like:
xmlhttp.open("GET","gradovi.php?selected="+x.value+"&t="+parseInt(new Date().getTime().toString().substring(0, 10)),true);
xmlhttp.send();
Regards!
Check how your request is sent to server. What does the double quotes look like? IE9, at least with jQuery, doesn't encode double quotes correctly according to this post:
Why does this jQuery Ajax call fail ONLY in IE9 (Even works fine in IE8 and IE7)
This is too late to answer but here's the solution that should solve this problem.
I had a similar problem this week. Change the
xmlhttp.open("GET", "gradovi.php?selected=" + x.value, true);
to
xmlhttp.open("POST", "gradovi.php?selected=" + x.value, true);
This solved my problem.
Check here:
This PHP script doesn't work in Internet explorer and Microsoft Edge but works in Chrome/Firefox/Safari/Opera
Lets say I have an array of javascript objects, and I am trying to pass those objects to a php page to save them into a database. I have no problems passing a variable to the php and using $_POST["entries"] on that variable but I can't figure out how to pass an entire array of objects, so I can access my objects.entryId and .mediaType values on the php page.
Oh and before anyone asks, yes the reason I need to do it this way is because I have a flash uploader, that you guessed it.. uploads into a CDN server (remote) and the remote server only replies back with such js objects.
Thanks for any help anyone can provide.
Here is my JS functions:
function test() {
entriesObj1 = new Object();
entriesObj1.entryId = "abc";
entriesObj1.mediaType = 2;
entriesObj2 = new Object();
entriesObj2.entryId = "def";
entriesObj2.mediaType = 1;
var entries = new Array();
entries[0] = entriesObj1;
entries[1] = entriesObj2;
var parameterString;
for(var i = 0; i < entries.length; i++) {
parameterString += (i > 0 ? "&" : "")
+ "test" + "="
+ encodeURI(entries[i].entryId);
}
xmlhttp.open("POST","ajax_entries.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameterString.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange = handleServerResponseTest;
xmlhttp.send(parameterString);
}
function handleServerResponseTest() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
maybe you need to take a look at json and jQuery ajax methods:
.- http://blog.reindel.com/2007/10/02/parse-json-with-jquery-and-javascript/
.- http://us.php.net/json_decode
The turorial is maybe a little outdated because jQuery last version is 1.3.x but you will get an idea on that and about the PHP json functions... if your server does not have the json extension enabled you can use some php classes:
.- http://google.com.co/search?rlz=1C1GPEA_enVE314VE314&sourceid=chrome&ie=UTF-8&q=php+json+class
good luck!
I too had the same trouble. But googling dint help.
I tried myself to tweak and test. And I got it. I am using POST method though. Please try the idea with GET method. Here is the idea:
Append the array index value within square brackets to the Post/Get variable name for array. Do this for each array element.
The part var parameters="&Name[0]="+namevalue1+"&Name[1]="+namevalue2; of the following script would give you a hint.
This is the test JS, I used (Again this uses POST method not GET):
var xmlAJAXObject;
function test() {
xmlAJAXObject=GetxmlAJAXObject();
if (xmlAJAXObject==null) {
alert ("Oops!! Browser does not support HTTP Request.");
return false;
}
var namevalue1=encodeURIComponent("Element 1");
var namevalue2=encodeURIComponent("Element 1");
var parameters="&Name[0]="+namevalue1+"&Name[1]="+namevalue2;
xmlAJAXObject.open("POST", "test.php", true);
xmlAJAXObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlAJAXObject.setRequestHeader("Content-length", parameters.length);
xmlAJAXObject.onreadystatechange=stateChanged;
xmlAJAXObject.send(parameters);
}
function stateChanged() {
if (xmlAJAXObject.readyState ==4) {
if (xmlAJAXObject.status == 200) {
alert('Good Request is back');
document.getElementById("show").innerHTML=xmlAJAXObject.responseText;
}
}
}
function GetxmlAJAXObject() {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject) {
// code for IE6, IE5
return new ActiveXObject("Microsoft.Microsoft.XMLHTTP");
}
return null;
}
This worked for me. Sorry for the formatting and incomplete code. I meant to give a direction. Google reault websites couldn't give a solution. Hope you find this useful.