Getting Started with AJAX - Updating Form via PHP - 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.

Related

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

Remove credit on pressing a button PHP MySQL AJAX

I'm trying to make a simple credit page where people have that much credit, and by clicking on a button next to their name it will remove on credit
<table border="1">
<tr>
<td>Name</td><td>Massages left</td>
</tr>
<?php
mysql_connect("localhost","dbuser","password");
mysql_select_db("db");
$command = "select pass_name, credit_left from pass;";
$result = mysql_query($command);
//If there is, list that particular entry
while ($data = mysql_fetch_object($result))
{
print "<tr><td>" . $data->pass_name . "</td>" .
"<td>" . $data->credit_left . "</td></tr>\n"
// Button here that you click and make credit go down one;
}
?>
</table>
For example it will say Ben - 2credits - click here to remove one.
Thanks
EDIT
okay here is what I have:
the script is
<script>
function removeOneCredit(str)
{
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("credit").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","removeonecredit.php"+str,true);
xmlhttp.send();
}
</script>
the form is:
while ($data = mysql_fetch_object($result)) {
print "<TR><TD>".$data->pass_name."</TD><TD id='credit'>".$data->credit_left."</TD><TD><form><input type='submit' value='- 1' onsubmit='removeOneCredit(?pass_id=".$data->pass_id."&credit_left=".$data->credit_left.")'></form></TD></TR>\n";
}
the removeonecredit.php is
<html>
<?php
$pass_id = $_GET[pass_id];
$credit_left = $_GET[credit_left]-1;
//change value
mysql_connect("localhost","user","pw");
mysql_select_db("db");
$command = "update pass set credit_left='$credit_left' where pass_id='$pass_id';";
mysql_query($command);
//now print value
mysql_connect("localhost","user","pw");
mysql_select_db("db");
$command = "select credit_left from pass where pass_id='$pass_id';";
$result = mysql_query($command);
$data = mysql_fetch_object($result);
echo $data->credit_left;
?>
</html>
If I pass the string manually at the end of removeonecredit.php, it works, so it must be the Ajax part of things...
Use a from with a button and use an AJAX script in JavaScript to update the database without reloading the page. If you don't care that the page reloads, then you can just use the form but you don't have to write the AJAX script. To update the database for a single user, you can iterate through your database, and find the user you are looking for by a unique identifier such as an id, or a username:
For example, using the UPDATE MySQL command:
UPDATE table_name
SET credits_left='1'
WHERE username='Bob'
So this will update the credits value only for the person with username 'Bob'.
I know this isn't very specific, but if you make your question more specific, I might be able to help you better.
turns out the = in the function arguments is a problem, I posted a question on how to escape it here: Javascript escape a equal sign PHP
If you want to make that change using PHP, you would have to make a form and submit to the same page. PHP renders code on the server and sends HTML to the client (the user on the computer). If you want it to be reflected in the database, you would have to run a mysql query to update that field. Then once the form is submitted, the top of the page can process it, and the new output would be loaded.
Another option would be to use javascript. In this case it would not be necessary to reload the page.
<script>
var count = 2;
$(document).on('click', '#clickButton', function(){
$('#countDiv').text(count--);
});
</script>
And your html/php page would have to have a button with id="clickButton" and a div like <div id="countDiv"></div>
I didn't test this out. But I hope it helps or takes you in the right direction!

POST variable doesn't exist after AJAX is used to filter select options

I have a working form with a POST method and this form contains the following select dropdown:
<div id="typeselect">
<select name="type" id="type" style="float:left;margin-right:100px;">
<option>Choose Surgery type</option>
<?php
$spec_res=mysql_query("select * from operation_list order by Narrative") or die(mysql_error());
while($spec_row=mysql_fetch_array($spec_res)){
echo "<option>".$spec_row['Narrative']."</option>";
}
?>
</select>
</div>
It works fine, and on the action page, $_POST['type'] has the correct value of whatever is selected.
However, I've added another dropdown with id='specialty' that is used to dynamically filter the options available in the 'type' dropdown using Ajax. Filtering is based on a column named 'Specialty1' in the same 'operation_list' database table. This works too, but then when I submit the form, $_POST['type'] has no value! Can someone tell me what I'm doign wrong? Here's the Ajax function and the PHP file it points to:
<script type="text/javascript">
function getTypes(str)
{
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("typeselect").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","showtypes.php?specialty="+str,true);
xmlhttp.send();
}
</script>
And showtypes.php:
<?php
//dbconnection here
$specialty=$_GET['specialty'];
?>
<select name="type" id="type" style="float:left;margin-right:100px;">
<option>Choose Surgery type</option>
<?php
$spec_res=mysql_query("select * from operation_list where Specialty1='$specialty' order by Narrative") or die(mysql_error());
while($spec_row=mysql_fetch_array($spec_res)){
echo "<option>".$spec_row['Narrative']."</option>";
}
?>
</select>
So, to sum up, why doesn't $_POST['type'] exist after I use Ajax to alter the select options, and what can I do to fix this while keeping all the functionality?
EDIT: Never mind the comment that was in the Ajax function, it was obsolete and I had forgotten to remove it.
I don't exactly know what your problem is, but I think you could simplify it a lot if you used jQuery.
<script type="text/javascript">
$('#type').change(function() {
$('#typeselect').load('showtypes.php', { specialty: $(this).val() });
});
</script>
See http://api.jquery.com/change/ for information on the change event.
See http://api.jquery.com/load/ for information of the Ajax load function.
Better yet,
jQuery-ized function:
function getTypes(str,input_form){
$.post("showtyps.php?specialty="+str, $("#"+input_form).serialize(),
function(data){
// This happens when the data is loaded
$("#typeselect").html(data);
});
}
The difference being you will also need to pass the id of the form along with the first argument.
If you would rather do things one field at a time, you can replace
$("#"+input_form).serialize()
with
{
'postvariablename' : $("#idofelement").serialize(),
'postvariable2name' : $("#idof2ndelement").serialize()
}
And so on...
You will of course need to include jQuery first in order for it to work, but I highly recommend using it in these types of cases, for the utmost in cross compatibility.

select value from <select> field corresponding to value in previous <select> field

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

Categories