Global variable in ajax possible? Work around? - php

Right now I have a website which uses PHP to generate a table from a large SQL database.
I want to add two buttons to my website which will use AJAX to update the table with new data. The table is all indexed, so all I need is to be able to submit an "offset" variable through my XMLHttpRequest to get the new data. The code I have for that is:
xmlhttp.open("GET","schedule_top.php?q="+offset, true);
xmlhttp.send();
Right now, my "next" button will give an offset of 3, and my "previous" button gives an offset of -3. The problem I have is if the user wants to click either button more than once. As the offset is set to 0 each time at function call, I cannot cycle beyond -3 and 3.
What should I be doing? My current AJAX code is below:
function loadXMLDoc(int) {
var xmlhttp;
var offset = 0;
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('tobooth').innerHTML = xmlhttp.responseText;
}
}
if (int == 1) {
offset -= 3;
} else {
offset +=3;
}
xmlhttp.open("GET","schedule_top.php?q="+offset, true);
xmlhttp.send();
}

I don't answer your question directly, but I can suggest another approach.
You can create simple fields in which you will contain new offset. Or you can store offset directly on elements next and prev, e.g.
<a href='#' id='0' class='goPrev'>Previous</a>
and
<a href='#' id='3' class='goNext'>Next</a>
Default offset is zero. For next button offset will be 3, for previous null (and user can't click on prev button).
When user will click next button, you will do your ajax request and update both fields. goNext field will have offset 6 and previous will have offset 0.
When user will click next button again, you will do your ajax request again and update both fields again. goNext field will have offset 9 and previous will have offset 3.
Etc etc etc.
Also, you can store data in hidden inputs.
Hope, this will help.

Related

Update database only by pressing link

I have this code with some images, like this:
<img src="../images/woods/oak.png" onclick="loadXMLDoc(this), add_items_oak(this), add_skills_oak(this)" class="a" name="oak"/>
<img src="../images/woods/oak.png" onclick="loadXMLDoc(this), add_items_oak(this), add_skills_oak(this)" class="b" name="oak" />
When one of them is pressed, an ajax call is run:
function loadXMLDoc(h)
{
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)
{
var getEle = document.getElementsByClassName('woods1')[0];
var imagePath ="../images/woods/oak_cut.png";
h.src = imagePath + xmlhttp.responseText;
}
}
xmlhttp.open("POST","../database/update.php",true);
xmlhttp.send();
}
Which then updates the database by the use of this file:
<?php
require('../includes/db_connect.php');
/* Register a prepared statement */
if ($stmt = $mysqli->prepare('
UPDATE items_woods t1 JOIN skills_woodcutting t2
ON t1.id = t2.id
SET t1.oak = oak+1,
t2.exp = exp+13
WHERE t1.id = ?;
')) {
/* Bind parametres */
$stmt->bind_param('i', $id);
/* Insert the parameter values */
$id = 1;
/* Execute the query */
$stmt->execute();
/* Close statement */
$stmt->close();
} else {
/* Something went wrong */
echo 'Something went terrible wrong' . $mysqli->error;
}
?>
The problem now is that people can use the url to simulate a click on one of the images. Like writing something like: www.examplepage.com/database/update.php
I need update.php to check wether or not a image is clicked on.
I tried some code by having a value in the <img> tag that was set to true, and only if that was true at update.php, it would execute the code. This didn't help and since I am trying to find a solution that can't be cheated with, I thought about asking here. Any suggestions or advice? Thanks in advance.
What you want is not possible through any sort of standard method. There is no way to require someone to click a link vs visiting a URL directly.
You will have to do something like generating a one-time hash that only works for a short period of time, and only allow the script to work if that was passed in the link.
So if a user clicks a link with that hash, it'll work once, but future clicks with that same hash won't. They'd have to find the image again and click it a second time with a new hash to trigger the same function.
edit:
If you're doing what it looks like and making a sort of browser game where users see resources and click to claim them, could you generate a map first, and send the x/y coords they're clicking on, and then track that the resource was deleted?
Then if they try to "cut" the same x/y coord again, it wouldn't work since they already harvested it.
You can test for the POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// … your database code
}
This would at least stop the update happening if the user simply visited the URL because that would constitute a GET request

append/pre pend ajax response to top of div

In my application i want to append or pre pend if that's the right word, the result of a ajax request to an already displayed list of posts by people. i mean when the user clicks on post and the ajax request is fired, the result should be pushed in to the top of the existing list of posts in the div.
One way i thought of was to fire a second ajax request after the user posts something to fetch the new list of posts sorted by timestamp, this way the post will automatically appear at the top but this seems to be punishing the database with unnecessary calls.
Please suggest the best and effective way. Please do not suggest jquery for this, i want to do it in raw javascript, i will use jquery later when i do not have any way to achieving i want to achieve.
my javascript code:
function postAjaxFade(){
t = document.getElementById("post").value;
// other element values like timestamp etc...
params = "post="+t+"&fl="+f;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// what do i add here to append the value to top of this div below..
document.getElementById("postContainer").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","search.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(params);
}
change:
document.getElementById("postContainer").innerHTML=xmlhttp.responseText;
to
var inner = document.getElementById("postContainer").innerHTML;
inner = xmlhttp.responseText + inner;
document.getElementById("postContainer").innerHTML = inner;

How to pass Javascript variables to PHP [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
pass php variable to javascript
I want to compare the click count(s) clicked by the users with the data saved in database.
I am not sure how to proceed to pass the value of the HTML "clicks" to compare with "counts" in PHP.
<html>
<script type="text/javascript">
var count = 0;
function countClicks()
{
count = count + 1;
document.getElementById("clicks").innerHTML = count;
}
</script>
<?php
if(empty($counts)){
?>
<script type="text/javascript">
alert("Count is empty!!");
</script>
<?php
} else {
$data = mysql_query("SELECT clicks FROM customerdetails WHERE customer_username='$username'");
$info = mysql_fetch_array($data);
//compare $data with the clicks
echo 'same!';
}
?>
<body>
Count Clicks
<input type="button" onclick=countClicks() value="Click"/>
<p id="clicks">0</p>
</body>
</html>
You are using PHP and Javascript in the wrong way. PHP is a serverside language. which means it runs before the page even loaded on the browser.
You will have to create a javascript click counter and put its values into a hidden formfield. Then use a submit button to send the information to the server (PHP). Then let PHP do the checks and selections from the database and return an answer.
Another solution is to use javascript AJAX, but I do recommend first trying the above.
The best way to proceed would be to make an Asynchronous JavaScript and XML call (AJAX). PHP is a server-side language, which is executed before the HTML (thus, before Javascript) is built and shown to the browser.
Therefor, the only way for Javascript to exchange variables and data with PHP is to make an AJAX call (you could always reload the page with a form submit or with session variables and cookies, but this isn't the best way to go if action is repeated too often.
IN AJAX, you can make another PHP page that will check both values and return whatever you want. The response can be stored in a Javascript variable, or even in JSON.
I suggest you to read more about AJAX and also get to know what is PHP how to use it.
Edit: After reading your comment, I decided to put a simple example down here.
Javascript (in your HTML page)
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)
{
/*Here you should do what you want.
xmlhttp.responseText is the content of your PHP answer! */
var result = xmlhttp.responseText;
//I am parsing a JSON response, which is a specific, universal language
//To exchange data without losing formatting or anything else.
result = JSON.parse(result);
/* The we use the name of our PHP array key as a property
Here it is "response" (see PHP json_encode line) */
alert(result.response);
 }
}
/* Change this URL for the PHP filename. we use the GET method to send data. */
/* You should always use the POST method when sending sensitive data */
xmlhttp.open("GET","getUserClicks.php?clicks="+count+"&username="+username,true);
xmlhttp.send();
PHP (here it is the file named getUserClicks.php )
<?php
if(!isset($_GET['username']) || !isset($_GET['clicks']))
die("Error");
$username = $_GET['username'];
$jsClicks = $_GET['clicks'];
$phpClicks = null;
#I am using the mysqli class to execute the query since mysql is deprecated in PHP5.
$data = mysqli_query("SELECT clicks FROM customerdetails WHERE customer_username='$username'");
while($row = mysqli_fetch_array($data))
{
$phpClicks = $row['clicks'];
}
#If your "IF" only contains one line, you don't need brackets.
#Otherwise they are needed.
if($phpClicks == null)
die("Could not get the number of clicks of the desired username");
#This is the string PHP will send to Javascript.
$response = "Same number of clicks!";
#If phpClicks is different and has the same type as jsClicks...
if($phpClicks !== $jsClicks)
{
$response = "Number of clicks changed!";
if($jsClicks > $phpClicks)
{
#Updates the number of clicks the user has done.
$mysqli_result = mysqli_query("UPDATE customerdetails SET clicks=$jsClicks WHERE customer_username='$username';");
}
}
echo json_encode(array('response'=>$response));
?>
Be sure to make some research if you see functions or methods you have no idea what they do (eg.: isset).

Getting Started with AJAX - Updating Form via PHP

I have a simple HTML form which starts with a select menu where the user can select from a list of Projects. I've created a simple JSFiddle with the HTML form here:
http://jsfiddle.net/AZ4PM/
What I would like to happen is that when the user selects from the list it triggers a php script to be performed which takes the value from the ProjectNumber they have selected and passes this as a parameter, e.g. if I select Project A the URL would be:
getProjectPhases.php?projectNumber=10000
This php script will then return a new table cell which I would then like to appear as the 2nd cell in the form. It contains a new select menu with the values changing depending on the selection in the first select menu. This php page is working well manually, but I'm at the point now where I need to have it triggered when the user makes a selection from the Project Number menu.
I'm new to AJAX and would like to start with a simple example one step at a time whilst I learn. I'm happy to use jQuery if that makes things easier.
Appreciate any pointers to what the basic elements I need to include (assuming at least one js file etc).
I have something very similar that I use:
<select name="selectProject" id="selectID" onChange="showUser(this.options[selectedIndex].value)">
<?php
// Loop through and list each project
foreach ($var as $row) {
echo '<option value="'.$row['projectNumber'].'">'.$row['projectName'].'</option>';
}
?>
</select>
<label>Project Name</label>
<input id="projectName" type="text" class="span3" name="projectName">
The above just calls the showUser function with the parameter that is the projectNumber
Then below that I have:
<SCRIPT TYPE="text/javascript">
// Function to fill in form fields
function showUser(str)
{
if (str=="")
{
document.getElementById("").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)
{
var obj = eval('(' + this.responseText + ')');
document.getElementById("projectName").value=obj.projectname;
}
}
xmlhttp.open("GET","http://url.com/ajax/"+str,true);
xmlhttp.send();
}
</SCRIPT>
This script will call the url url.com/ajax/whateverIdIsSelected
From that page, you want to do whatever you have to do with your query.
As for what to return, I have this set up to use json, which I why I have the line
var obj = eval('(' + this.responseText + ')');
this.reponseText is what is returned from the ajax page. My return call looks like this
$projectData = json_encode($project);
echo $projectData;
Where $project is an array containing your project's attributes.
I'm not very good with ajax or js, but I got this working the way I like it. Let me know if you have questions
Pass id to the option select list
<select name="ProjectNumber" id="ProjectNumber">
Then call a method having these and then parse it via Ajax call.
var pvalue = document.getElementById('ProjectNumber').value;
var url = 'getProjectPhases.php?projectNumber='+pvalue;
First you need to bind the JQuery change() Handler to your drop down menu, calling a function that starts the ajax request, have a look at the jQuery get function you need to do something like this:
$.get("getProjectPhases.php", { projectNumber: this.val() }, function(data){
//Update your output using the data var
);
where data is the output of getProjectPhases, so it might be a good idea to just output plain text and no html tags or what ever.

Calling a Javascript function from HTML

I am having a HTML table with 5 rows (say) which is being displayed on the webpage. The first column of the table is RowID (which is unique for each row) and the last column of each row is a [X] button (which on click will remove the row). The whole table is in a <div> element with id="cartmain"
<div id="cartmain">
<table>
<tr>
<td>....</td>
<td>....</td>
<td> [X] </td>
</tr>
..
..
</table>
</div>
This is how I am removing the row:
STEP1: When user clicks on [X] button, an XMLHTTPRequest function will send message to a PHP code with unique id of each row. During the time PHP code is removing the row, DIV element shows "Loading..."
document.getElementById("cartmain").innerHTML = "Loading..."
STEP2: PHP code will delete the row from table (and from database) and will return the remaining table.
<?php
//removing row from database/table...
//send the remaining table back to the XMLHTTPRequest function...
echo "<table>";
echo "<tr><td>...</td>
<td>...</td>
<td> [X] </td>";
echo "</tr>";
...
...
...
echo "</table>";
?>
This remaining table received from the PHP code is then shown in the DIV element by using the below line:
document.getElementById("cartmain").innerHTML = removeitem.responseText;
My Problem:
Suppose I have table with 5 rows. When I click on the Remove button, the row is removed successfully and table is then displayed with 4 remaining rows. Here comes the problem: When I want to remove another row from the table: Nothing is Happening. In other words, if I again click on [X] of some row then nothing happens. The XMLHTTPRequest function is not called. In ideal case, it should have called the XMLHTTPRequest function again with that unique RowID and table should then be displayed with remaining 3 rows.
IMPORTANT NOTE: When I refresh the page, then I am able to remove another row. But this time also, I can remove only one row. For removing one more, I have to refresh the page again.
Is anyone able to identify the problem here? Please help.
NOTE: My table actually is a Shopping Cart which contains a product in each row. [X] button actually signifies "removing the item" from the cart.
Here is the JavaScript code:
function removeitem(itemid)
{
alert("The item to be removed is: "+itemid);
if(window.XMLHttpRequest)
{
removeitem = new XMLHttpRequest();
}
else
{
removeitem=new ActiveXObject("Microsoft.XMLHTTP");
}
removeitem.onreadystatechange=function()
{
if (removeitem.readyState==4 && removeitem.status==200)
{
document.getElementById("cartmain").innerHTML=removeitem.responseText;
}
else if(removeitem.readyState < 4)
{
document.getElementById("cartmain").innerHTML="Loading...";
}
}
var linktoexecute = "cart.php?option=5&itemid="+itemid; //option =5 signifies that I want to remove the item with ITEMID.
removeitem.open("GET",linktoexecute,true);
removeitem.send();
}
The function removeitem shows an alert "The item to be removed is: 123" for the first time but does not shows second time. When I am checking in Firebug console, the following error is coming second time:
removeitem is not a function
Please help!!
All my Javascript functions are in a separate file (sc.js) for which I am using <script type="text/javascript" src="js/sc.js"></script> in the HEAD tag of my page.
My viewpoint: So finally I think the question comes to a simple point: If a webpage is requesting some HTML from a PHP page using XMLHTTPRequest -- and if that HTML (sent by PHP) contains some button which is calling a Javascript function -- then what will happen in this situation[?]. Now since I am able to remove the row for the first time, I think it is false to say that above situation will not work. It is just that the code that came from PHP and the Javascript which has already been loaded are not aware of each others presence when I click the button second time.
Inside the removeitem function, you're overwriting removeitem by a XMLHttpRequest object. Hence the later error removeitem is not a function.
To fix this, either prefix removeitem by var (recommended), or use another variable name, or both.
Recommended code:
function removeitem(itemid) {
alert("The item to be removed is: "+itemid);
var removeitem = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
removeitem.onreadystatechange = function() {
if (removeitem.readyState == 4 && removeitem.status == 200) {
document.getElementById("cartmain").innerHTML = removeitem.responseText;
} else if(removeitem.readyState < 4) {
document.getElementById("cartmain").innerHTML="Loading...";
}
}
var linktoexecute = "cart.php?option=5&itemid="+itemid; //option =5 signifies that I want to remove the item with ITEMID.
removeitem.open("GET", linktoexecute, true);
removeitem.send();
}
Adding var before removeitem fixes the problem, because the variable is locally defined. When var is omitted, a new value will be attached to the closest parent declaration (the function, in this case).
var removeitem = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
The previous line is short for:
var removeitem;
if (window.XMLHttpRequest) {
removeitem = new XMLHttpRequest();
} else {
removeitem = new ActiveXObject("Microsoft.XMLHTTP");
}
it doesn't look like you're escaping your double quotes like #Rob W has stated. I generally use single quotes when using php to write out HTML. I find this to be a good practice in my opinion.
The only other thing I can think of is that maybe your function isn't outside AJAX response text. Just check Firebug or view source of what's being rendered after the first response returned.
I hope this helps.
Why you load all table html every click? You can send only true or false when deleting and after you can remove TR element with jQuery.
Removing TR:
In your removeitem function, after ajax response, just call $(this).parents("tr").remove();

Categories