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;
Related
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.
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
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).
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.
I am having a form written in php. In this form there is field named 'State' and the Options of this field are the names of the states.There is another field named 'District' whose Options are the names of the District. The Options of the these two fields are being fetched from the database. There are about 28 states and there are about 12 Districts for each state. Now what is want is that when someone selects the state, then all the Districts corresponding to that state automatically appear in the District field.
You will need javascript to implement this nicely.
Here are two options:
Load the District select/options using ajax. i.e. When the State is changed an AJAX request is fired and reloads the District select box.
Loading all the Districts in, and hiding the ones that are not appropriate.
The benefit of option 2 is you don't need to wait for another request to complete before they can select the District. However it will require loading all the Districts up front. So 300ish options.
Create a javascript array mapping districts to states, e.g.:
var map = [];
map['state1'] = ['district1', 'district2', ... ];
map['state2'] = ['district13', 'district14', ... ];
Then the first select has an onChange function that clears the options from the second select and repopulates them from the predefined values in the array. In jQuery:
$('select[name=state]').change(function(){
var state = $(this).val();
var options = '';
foreach (map[state] as district){
options = options + '<option>'+district+'</option>';
}
$('select[name=district]').html(options);
});
you could use an ajax call
on the select put onchange="changedist(this.value)"
and use the script function
function changedist(str)
{
if (str=="")
{
document.getElementById("dist").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("dist").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","./dist.php?q="+str,true);
xmlhttp.send();
}
and call this values in your page
<div id="dist"> here will returns the distrctis of the file dist.php</div>
and dist.php
$q = $_GET[q];
$sql= "select * from dist where state = $q";
$query ....
echo ' <select name=dist>';
while ($result = mysql_fetch_array($query))
{
echo " <option value=$result[key]>$result[dist]</option>";
}
so this will returns to your form page on the state change