Javascript doesnt contact php page - php

im quite new to php and javascript but still trying to get my webpage to work.
Im trying to add a 5-star-voting-system to the page which will contact my database and update accordingly.
As you might have noticed my code grammar isnt perfect either.
<div class="first" onmouseover="starmove('-32px')" onmouseout="starnormal()" onclick="rate('harrys','1')">
this is the div that "contacts" the javascript
function rate(id,ratings){
var i=id;
var r=ratings;
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()
{
xmlhttp.open("POST","http://------/rating.php?id="+i+"&rating="+r,true);
xmlhttp.send();
}
this is the javascript
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Namnlös 1</title>
</head>
<body>
<?php
mysql_connect("host", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
mysql_set_charset('utf8');
$itemid = ($_GET["id"]);
$rating = ($_GET["rating"]);
$query = "INSERT INTO ratings(id,rating) VALUES ('$itemid','$rating')";
mysql_query($query);
?>
</body>
</html>
this is my rating.php file (note: the values in mysql_connect is right on actual page, even if not defined here.)
if I just open my php file there will be a row added to mysql so i know its connected properly.

You are passing the values to rating.php as GET but you are fetching it as POST
xmlhttp.open("POST","http://------/rating.php?id="+i+"&rating="+r,true);
Here, even if you give the method as POST, ?id="+i+"&rating="+r means that id and rating is being passed as GET.
So you cannot access them as
$itemid = ($_POST["id"]);
$rating = ($_POST["rating"]);
You will need to change that to:
$itemid = ($_GET["id"]);
$rating = ($_GET["rating"]);
Also change your query to:
$query = "INSERT INTO ratings(id,rating) VALUES ('".$itemid."','".$rating."')";
EDIT:
I have updated the Javascript code here. Try this:
<script>
function rate(id,ratings)
{
var i=id;
var r=ratings;
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("POST","http://------/rating.php?id="+i+"&rating="+r,true);
xmlhttp.send();
}
</script>
Changes:
1. There were two braces after:
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
The second brace effectively closed the rate() function, so the code after that wasnt doing what it was expected to. So I moved that brace to the end of the code, to wrap the function.
The onreadystatechange function is called AFTER data has been sent to the server in order to track, what is going on with the request. In your code, you were sending the request INSIDE the onreadystatechange, which would never execute, since the request would never get sent..
I changed
xmlhttp.onreadystatechange=function()
{
xmlhttp.open("POST","http://------/rating.php?id="+i+"&rating="+r,true);
xmlhttp.send();
}
into a simple POST call:
xmlhttp.open("POST","http://------/rating.php?id="+i+"&rating="+r,true);
xmlhttp.send();
I hope this explains everything :)

You should try jQuery for XHTTP Calls. That way, you are sure that all browsers are supported with your code.
Add this to your head section:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
Then use this code to make the call to the PHP page:
var i = id;
var r = ratings;
$.get("http://------/rating.php?id="+i+"&rating="+r);
I also noticed you did put "sds" in the "id" field in your query. The "id" field should be an integer. If it is an integer already, that's your problem. Also change $_POST to $_GET. Fixed version:
$itemid = ($_GET["id"]);
$rating = ($_GET["rating"]);
$query = "INSERT INTO ratings(id,rating) VALUES ($itemid,'$rating')";

Please use jQuery to handle ajax requests. jQuery works cross browser and you can be sure it works.
Also:
$itemid = ($_POST["id"]);
$rating = ($_POST["rating"]);
$query = "INSERT INTO ratings(id,rating) VALUES ('sds','$rating')";
Is insecure
$itemid = intval($_POST["id"]);
$rating = intval($_POST["rating"]);
$query = "INSERT INTO ratings(id,rating) VALUES ('sds','$rating')";
is a lot better

First, use relative instead of absolute links if the php file you're trying to request is in the same site:
// Absolute link
xmlhttp.open("POST","http://------/rating.php?id="+i+"&rating="+r,true);
// Relative link
xmlhttp.open("POST","rating.php?id="+i+"&rating="+r,true);
Then, you're trying to send and retrieve the info via POST, but you're sending the info in a query string (GET):
JS:
xmlhttp.open("GET","rating.php?id="+i+"&rating="+r,true);
PHP:
$itemid = $_GET["id"];
$rating = $_GET["rating"];
Finally, before you insert, use mysql_real_escape_string() or mysqli_real_escape_string(), depending on the MySQL library you're using, to prevent SQL injection in the database and compromise your site:
$itemid = mysql_real_escape_string($_GET["id"]);
$rating = mysql_real_escape_string($_GET["rating"]);
$query = 'INSERT INTO ratings(id,rating) VALUES ('.$itemid.','.$rating.')';
mysql_query($query);

Related

Sql Querying with Ajax while offline returning blank

I'll over simplify the problem in order to make it easier. I'm using the following Ajax script to call another .php file and have it return the results to the original page. I'm using Apache offline and the page is unfortunately returning blank.
<html>
<head>
<script>
function showInfo(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.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status== 200) {
document.getElementById("result").innerHTML= xmlhttp.responseText;
}
}
xmlhttp.open("GET","practice.php?q="+str,true);
xmlhttp.send();
}
window.onload = function() { showInfo('bleh'); };
</script>
</head>
<body>
<div id="result"></div>
</body>
//Then the code below is another file called practice.php, which corresponds the ajax above
<?
$test = $_GET['q'];
echo $test;
?>
I am pretty sure $_GET is a case-sensitive variable name on most OSes, so $_Get would be empty.
I would comment if I could -
What happens when you try to hit the page directly (ie put practice.php?q=test) in the browser?
Also I can't find any documentation (it's hard to google it), but it wouldn't hurt to make the opening tag <?php instead of just <?

AJAX PHP Submission not working

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

JavaScript / PHP / Ajax set multiple session variables

Hello friends a newbie question. I am new to programming hence please be gentle.
I am trying to post multiple session variables using JavaScript so that I can use them later in my PHP at multiple places.
My index.php file
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<?php
if ((empty($_SESSION['function1Val'])) & (empty($_SESSION['function2Val'])) && (empty($_SESSION['jsStatus']))) {
echo '<script type="text/javascript" src="vals.js"></script>
<script type="text/javascript">
var session=false;
var jsStatus;
var function1Val;
var function2Val;
</script>';
} else {
echo '<script type="text/javascript">
var session=true; var jsStatus=' . $_SESSION['jsStatus'] . ';
var session=true; var function1Val=' . $_SESSION['function1Val'] . ';
var session=true; var function2Val=' . $_SESSION['function2Val'] . ';
</script>';
}
?>
</head>
<body>
<?php
echo $jsStatus;
echo $function1Val;
echo $function2Val;
session_destroy ();
?>
</body>
</html>
My vals.js file
window.onload = function() {
// if there is no session (session = false)
if (!session) {
// Set value to variable jsStatus
jsStatus = 'enabled';
// Call function to get function1
function1();
// Call function to get function2
function2();
// Make ajax call to php page to set the session variable
setSession();
}
}
function function1() {
// code to get value goes here
function1Val = 'result1';
}
function function2() {
// code to get value goes here
function2Val = 'result2';
}
function setSession() {
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)
{
// Reload the page
window.location.reload();
}
}
xmlhttp.open("POST","session.php?function1Val=" + function1Val,true);
xmlhttp.send();
// like this I want to transfer other values of 'function2Val' and 'jsStatus'
}
My session.php file
<?php
session_start();
// check if it is already set if you like otherwise:
$_SESSION['function1Val'] = $_REQUEST['function1Val'];
$_SESSION['function2Val'] = $_REQUEST['function2Val'];
$_SESSION['jsStatus'] = $_REQUEST['jsStatus'];
?>
I know the code is messy but I don't know how to write the correct syntax. I actually tried to modify a single variable code but failed. hence need help.
The idea is to post various values derived out of various JavaScript functions to the session for use by PHP.
Please help.
UPDATE:
It has to be this way as the values to the said variables can be calculated with the help of JavaScript only.
You have to concatenate the parameters with an ampersand (&).
Use this line
xmlhttp.open("POST","session.php?function1Val=" + function1Val+"&function2Val=" + function2Val+"&jsStatus=" + jsStatus,true);
BTW: I would really suggest to use jQuery or a similar library for AJAX requests. Furthermore I would use JSON for exchanging the data or a Javascript array where the key names are those of the variables.

Javascript document.getElementById concatenating

I'm struggling with some JavaScript code that I have used countless times across my pages just tweaking as I go. The problem I have is concatenating part of the form elements id and a string variable defined elsewhere in the page to make my ajax call dynamic.
Im am using the following code which works perfect when the element is hard coded as below(only works for the item coded and not dynamically so no good after testing)
<script type="text/javascript">
function edttodo(str)
{
if (str=="")
{
document.getElementById("todoitemwr").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("todoitemwr(2)").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","todo/edt_todo.php?q="+str,true);
xmlhttp.send();
}
</script>
So you understand what my need is for the dynamic aspect of the code I have a mysql query undertaken which is as follows:
<?php
//Get Current To-Do Items
//select database
mysql_select_db("jbsrint", $con);
//query users_dash_user
$result1 = mysql_query("SELECT * FROM todo WHERE todo_user_id_fk= '".$_SESSION['user_id']."' AND todo_item_status='1'");
while($row1 = mysql_fetch_array($result1))
{
echo"<div class=\"todoitemwr\" name=\"todoitemwr(". $row1['todo_id'] .")\" ID=\"todoitemwr(". $row1['todo_id'] .")\"><span class=\"todoitem\">" . $row1['todo_item'] . "</span><span class=\"rmv\" onclick=\"rmvtodo(". $row1['todo_id'] .")\" onmouseover=\"className='rmvon';\" onmouseout=\"className='rmv';\">X</span><img src=\"images/edit.png\" class=\"edt\" onclick=\"edttodo(". $row1['todo_id'] .")\"></img></div>";
}
?>
</div>
As you can see the div id is dynamically named based on the id of the information that has been retrieved. The use of my ajax code above is to be able to edit the text that is retrieved in-situ and once corrected/altered it can then be re-submitted and update that record.
I'm sure that it is simply a case of understanding how JavaScript requires me to combine the text and str value in the document.getElementById("todoitemwr(2)") part.
As usual any help is much appreciated.
Alan.
Instead of using id="todoitemwr(2)" write id="todoitemwr_2".
That's because braces are not allowed in ID attributes.
The code would become:
document.getElementById('todoitemwr(' + str + ')')

Insert MySQL record with PHP and AJAX

trying to insert a record in my DB using AJAX for the very first time. I have the following...
Form
<form>
<input type="text" id="salary" name="salary">
<input type="button" onclick="insertSalary()">
</form>
AJAX
<script type="text/javascript">
function insertSalary()
{
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('current-salary').innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("POST","insert_salary.php",true);
xmlhttp.send("salary=" + document.getElementById("salary").value);
}
</script>
PHP
$uid = $_SESSION['oauth_id'];
$monthly_income = mysql_real_escape_string($_POST['salary']);
#Insert a new Record
$query = mysql_query("INSERT INTO `income` (user_id, monthly_income) VALUES ($uid, '$monthly_income')") or die(mysql_error());
$result = mysql_fetch_array($query);
return $result;
Nowmy data is being inserted into the table BESIDES the 'salary' which is being inputted as '0'
Once inserted I also have a div 'current-salary' that should then be populated with there inputted value only it isnt, Can anybody help me to understand where im going wrong?
If you want to save your self a lot of time, effort, and heartache, use the jquery library for your ajax requests. You can download it at http://jquery.com/
After adding a reference(Script tag) to the jquery script your javascript for the ajax request would become:
function insertSalary()
{
var salary = $("#salary").val();
$.post('insert_salary.php', {salary: salary}, function(data)
{
$("#current-salary").html(data);
});
}
Also keep in mind that using "insert_salary.php" as the url means it is a relative path and must be in the folder of the current running script.
Your php script needs to echo whatever you would like to be injected into your current-salary tag also.

Categories