PHP: Store Result of JavaScript Function into a PHP Variable - php

Please bear in mind, I'm very new to PHP. I've only started taking it this semester at my school.
Here's what I want to eventually do: I have a senior project where I'm building a computer repair system. In the repair MySQL table, I have a bunch of fields and one of them is CustomerID (so I know which customers had which repair). I want to have a drop drown of customer's names, and then when I click on it, some how attach that customer's ID to a variable so I can do an INSERT statement. In order to partially achieve this, I've done things in smaller parts. The small part I have working is when I select a dropdown value, it outputs it to the screen, but that's in the javascript function.
Here's my code:
<?PHP
include('session.php');
$db_name = "";
$mysql_username = "";
$mysql_password = "";
$mysql_server = "";
$mysqli = new mysqli($mysql_server, $mysql_username, $mysql_password,
$db_name);
$query = "SELECT custID, CONCAT(custFirstName, ' ', custLastName) as
Customer_Name FROM customer";
$result = mysqli_query($mysqli, $query);
echo "<select name ='names' id='myselect' onchange = \"myFunction()\">";
while ($row = mysqli_fetch_array($result)){
echo "<option value = '" . $row['custID'] . "'>" . $row['Customer_Name'] . "
</option>";
}
echo "</select>";
echo "<p>When you select a customer name, a function is triggered which
outputs the ID of the selected customer.</p>
<p id=\"demo\"></p>
<script>
function myFunction() {
var x = document.getElementById(\"myselect\").value;
document.getElementById(\"demo\").innerHTML = x;
}
</script>";
$content = "<script> document.write(x) </script>";
echo "<br> <br> The technician ID = $sTechID <br> <br> The customer ID = $content";
?>
I can output the ID to the screen with the Javascript function, but when I try to store "x" into a php variable, it doesn't work. In chrome, the inspector says that X is undefined.
A side note: I made a test file with this code and it worked:
<?PHP
echo "
<script>
var x = \"hello\"
</script>";
$content = "<script> document.write(x) </script>";
echo "$content <br> <br> $content";
?>
Because the above code worked, I don't understand why my bigger code is not working.
I understand that my code is a mess, but any help will be greatly appreciated. Thanks!

PHP is a back-end language and can't detect front-end events such as click, change, etc.
In your larger code, the value of x will only be defined once the event is fired(onchange), that's when the select input changes. Javascript works that way, but PHP doesn't. Once PHP sends a response the first time, its job is done.
This is when you will want to use forms or Ajax.
Using forms would be a good start.
Quick note, it's good practice to try to keep HTML, CSS and JS separate from PHP as much as possible.
...
$result = mysqli_query($mysqli, $query);
?>
<form method='post' action='insert.php' /> <!-- Link to php file to insert data to database -->
<select name ='names' id='myselect' onchange = "myFunction()">
<?php
while ($row = mysqli_fetch_array($result)){
echo "<option value = '" . $row['custID'] . "'>" . $row['Customer_Name'] . "
</option>";
}
?>
</select>
<input type="submit" value="submit" /> <!-- You will need a button to submit the data -->
</form>
<p>When you select a customer name, a function is triggered which
outputs the ID of the selected customer.</p>
<p id="demo"></p>
And now your insert.php file would look like:
<?php
// Get data from that was posted from the form
$customer_id = $_POST['names'];
// Now do whatever with the customer ID
echo $customer_id;

I think you need a better understanding of PHP in general. PHP is executed BEFORE the browser executes the html/js that you've echo'd to it. The reason this works:
<?PHP
echo "
<script>
var x = \"hello\"
</script>";
$content = "<script> document.write(x) </script>";
echo "$content <br> <br> $content";
?>
is because you are writing JS to the dom and it's being executed once your browser reads it. If you run a var_dump($content); you will see that what you have stored in that PHP variable is not the result of x but actually a literal string that contains the text "<script> document.write(x) </script>".
The line echo "$content <br> <br> $content"; prints "<script> document.write(x) </script> <br> <br> <script> document.write(x) </script>"; to the DOM, which in turn is run as JS in the browser.
If you want your drop down selection to do something in PHP I would suggest triggering a JS function on change of the drop down that in turn sends an AJAX request to a separate PHP file that does what you need to do there and returns it to your function. This way you can update the HTML without navigating to another PHP page.

Related

getting value from post or session

Hello everyone I was trying to create a page for drag n drop in which I want to maintain floor_id when it reloads.
I'm getting floor_id from previous page on click of button, and i'm adding it to session so that the next time the page reloads it doesn't get any error.
But when I select other option from the previous page,same value in the session is stored,the value doesn't get assigned using the post method.Can anyone provide some idea.
this page is from where i get the selected id.
?>
<form action="rooms.php" method="post">
<select name="fl_type" id="ft" >
<option value=0>Select Floor</option>
<?php
while($row=mysqli_fetch_row($result))
{
?>
<option value="<?php echo $row[2];?>"><?php echo $row[2];}?></option>
<input type="submit" name="room" value="generate" />
</form>
<br />
</body>
here I'm fetchig the code and getting id.
<?php
$i=0;
require("config.php");
$id=$_SESSION['restid'];
if(isset($_SESSION['ft'])){
$ft=$_SESSION['ft'];
$query="select floor_id,width,height from floor_m where floor_type='".$ft."' and rest_id='".$id."'";
$res1=mysqli_query($con,$query);
$row1=mysqli_fetch_row($res1);
$fd=$row1[0];
$w=$row1[1];
$h=$row1[2];
//echo $fd;
$query2="select room_as_id,width,height,start_x,start_y,room_id,room_type_id from room_m where floor_id='".$fd."'";
//echo $query2;
$res2=mysqli_query($con,$query2);
while($row2=mysqli_fetch_row($res2))
{
$room_type_id=$row2[6];
$query3="select room_type from room_type where room_type_id='".$room_type_id."'";
$res3=mysqli_query($con,$query3);
$row3=mysqli_fetch_row($res3);
$room='room_id'.$i;
$width='width'.$i;
$height='height'.$i;
$start_x='x'.$i;
$start_y='y'.$i;
$room_id='room'.$i;
$room_type='roomt'.$i;
$response[$room]=$row2[0];
$response[$width]=$row2[1];
$response[$height]=$row2[2];
$response[$start_x]=$row2[3];
$response[$start_y]=$row2[4];
$response[$room_id]=$row2[5];
$response[$room_type]=$row3[0];
//echo $response[$room_id];
$i++;
/*echo '<script>var data1 = '.json_encode($row2[0]).';var data2 = '.json_encode($row2[1]).';var data3 = '.json_encode($row2[2]).';var data4 = '.json_encode($row2[3]).';var data5 = '.json_encode($row2[4]).';//
</script>*/
}
$i--;
$response['count']=$i;
echo '<script> var data='.json_encode($response).'</script>';
$wd=500/$w;
$_SESSION['wd']=$wd;
$_SESSION['ft']=$ft;
$_SESSION['fid']=$fd;
echo '<script>var pf = '.json_encode($_SESSION['wd']).';
var ft='.json_encode($_SESSION['ft']).';
var fid='.json_encode($_SESSION['fid']).';</script>';
$ht=$h*$wd;
}
else{
$ft=$_POST['fl_type'];
//echo $ft;
}
$sql="select width,height,floor_id from floor_m where floor_type='".$ft."' and rest_id='".$id."'";
//echo $sql;
$res=mysqli_query($con,$sql);
$row=mysqli_fetch_row($res);
$w=$row[0];
$h=$row[1];
$fid=$row[2];
$wd=500/$w;
$wd=round($wd);
//echo $wd;
$_SESSION['wd']=$wd;
$_SESSION['ft']=$ft;
$_SESSION['fid']=$fid;
echo '<script>var pf = '.json_encode($_SESSION['wd']).';
var ft='.json_encode($_SESSION['ft']).';
var fid='.json_encode($_SESSION['fid']).';</script>';
$ht=$h*$wd;
//echo $wd,$ht;
?>
To use the $_SESSION variable, you will need to start a session at the top of all your PHP scripts. This can be done as so:
session_start()
Again, it must go at the top of every PHP script you intend to use the $_SESSION variable. If you don't, it will go on without error, but won't save.

Form Inside Div, Show Result In a Different Div

I have a div statement with two nested divs inside. The first nested div is a form that contains a drop down menu that allows the person to select a basic school subject:
<form id="request" action="<?php echo $_SERVER['PHP_SELF']?> method="post">
<div id='d2'>
<p id='p2'>Subject:
<select id="s" name="subject">
<option value="English">English</option>
<option value="Social Studies">Social Studies</option>
<option value="Math">Math</option>
<option value="Science">Science</option>
</select>
</p>
<input type="button" value="Find"/>
</div>
</form>
The second nested div will print out, using PHP, a previously initialized array of tutors that can help the student user, along with a link allowing the person to choose a specific tutor. Please forgive me for the less-than-stellar formatting, I'm still a beginner:
<div id='div3'>
for ($i=0; $i<count($tutors); $i++)
{
echo "<div>'".$tutors[$i]."'</div><br/>"
. 'Choose me' . "<br/>";
}
</div>
The array is initialized at the very beginning of the php class by connecting to MySQL and then pulling out tutors from the database that are tutor users and tutor in the subject the student user has selected. Again, please forgive me for any bugs, I'm still learning:
<?php
if ($_SERVER['REQUEST_METHOD']=='POST')
{
$sub = $_POST['subject'];
$con = mysqli_connect("127.0.0.1", "root", "//removed", "mydb");
$msg = "";
if (mysqli_connect_errno())
{
$msg = "Failed to connect to MySQL: " . mysqli_connect_error();
echo $msg;
}
$query = mysqli_query($con, "SELECT * FROM User WHERE Role = tutor AND Subject ='".$sub."'");
$tutors = array();
while ($row = mysqli_fetch_assoc($query))
{
$tutors[] = $row["Username"];
}
}
else
{
echo "Failed form.";
}
?>
The problem pressing me the most right now is that failed form is always shown on the screen. I suspect this is because the form has been nested inside a div. Is there any way around this? Or is it a different problem(s)?
I'm also wondering if the code will indeed show what I want in the second nested div, or if there are bugs in that too (I'll style it later).
I am basing my solution. on the following assumption. According too these lines from your post. The second nested div will print out, using PHP, a previously initialized array of tutors that can help the student user, along with a link allowing the person to choose a specific tutor. Please forgive me for the less-than-stellar formatting, I'm still a beginner:>>>>>> those line were from your post.
Please read the comment in the code carefull. There i explain what i change and suggestions.
This the code
<!--
<form id="request" action="<?php //echo $_SERVER['PHP_SELF']?> method="post">-->
/*
* The line above is wrong and as you may understand by the comments of other user,
you dont need to give anything in the action as you are posting it on the same
* page. so you can delete it. and add this line below one.
*/
<form action="" method="post">
<div id='d2'>
<p id='p2'>Subject:
<select id="s" name="subject">
<option value="English">English</option>
<option value="Social Studies">Social Studies</option>
<option value="Math">Math</option>
<option value="Science">Science</option>
</select>
</p>
<!--<input type="button" value="Find"/>--->
<input type="submit" value="Find"/>
</div>
</form>
<div id='div3'>
<?php
//I am leaving these php tag for the reference only that you used it in your original code.
//You dont need those lines
?>
</div>
<?php
if ($_SERVER['REQUEST_METHOD']=='POST')
{
$sub = $_POST['subject'];
//$con = mysqli_connect("127.0.0.1", "root", "//removed", "mydb");
$con = mysqli_connect("127.0.0.1", "root", "", "mydb");
$msg = "";
if (mysqli_connect_errno())
{
$msg = "Failed to connect to MySQL: " . mysqli_connect_error();
echo $msg;
}
$query = mysqli_query($con, "SELECT * FROM User WHERE Role = 'tutor' AND Subject ='".$sub."'")or die(mysqli_error($con));
// $tutors = array(); You dont need that line either.
while ($row = mysqli_fetch_assoc($query))
{
$tutors = $row["username"];
echo "<div>'".$tutors."'</div><br/>"
. 'Choose me' . "<br/>";
/*
* **Here is the suggestion**. The link you are giving to
* the user is always going to be SelectedTutor.php.
* I dont think this what you want. you may want to
* show tutor profile or wanna do some thing else when
* somebody click on the link. Lets say you want show
* the tutor profile. Than you have to run another query.
* and should be able to generate link accordingly.
* I am giving you hint how you can do it in case you want to do it.
*/
/*
* you should change that line to this line link one to this
* echo "<div>'".$tutors."'</div><br/>"
* . 'Choose me' . "<br/>";
* If you notcie i added this parth after SelectedTutor.php, this one ?tutor='.$tutors.'
* Than your url will be different when ever user click on the link.
* Hope i did not confused you
*/
}
}
else
{
echo "Failed form.";
}
?>
And you ask why you are getting message of Failed form. In short why your else statement is running. to understand see the expanation below.
if ($_SERVER['REQUEST_METHOD']=='POST')
{
//I removed the code just left the basic shell so you can understand
}
else
{
echo "Failed form.";
}
If you read the above code you will understand why you are getting Failed form message each time when you run the code. You will not get this message when you click on submit.
Reason: Reason is this, in those lines your saying that if Request method is post, than run this bit of code. and Else echo this message out. means whenever your request method is not post run this else statement.
but the thing is that you only sending post request after clicking on the button. before that, there is no post request. so thats why you are getting this message each time you run your script and than it disappear when you click on submit. cause you send the post request.
English is not the first language if i confused you let me know i will explain it again.
Although you have asked for help with PHP/HTML, this is really a job for jQuery/AJAX. Don't worry, though -- it's much simpler than you might think.
The advantage to using AJAX is that you stay on the same page, and the page does not refresh -- but the dropdown selection is sent to a PHP file (that you specify), the MySQL database is consulted, and a response (in HTML) is returned.
Inside the AJAX success function, (did you hear that? Inside the success function!) you receive the HTML returned by the other PHP file and you then plunk the returned HTML into an existing DIV.
Here are some simple examples:
AJAX request callback using jQuery
(1) You would not need to put DIV d2 into <form> tags. Not necessary with AJAX
(2) Your jQuery code would look like this:
<script type="text/javascript">
$('#s').change(function(){
var sub = $(this).val();
$.ajax({
type: 'post',
url: 'my_php_file.php',
data: 'subj=' +sub,
success: function(resp){
$('#div3').html(resp);
}
});
});
</script>
The above script can be placed anywhere in the document, or in the head tags, or included in a separate document.
(3) You must reference the jQuery library, as per the first example in the "AJAX request callback..." link.
(4) There will be no need for the Find button, because the code will fire as soon as the dropdown value is changed. It takes microseconds to communicate with the server and stick the list of tutors in the div3 div.
(5) The div3 div must already exist on the page (but it can be empty).
(6) The PHP file (called my_php_file.php in the code above) would be exactly as you wrote, except that it would create an output variable containing the HTML to be plunked into the div3 div. For example:
<?php
if ($_SERVER['REQUEST_METHOD']=='POST'){
$sub = $_POST['subj'];
$con = mysqli_connect("127.0.0.1", "root", "//removed", "mydb");
$msg = "";
if (mysqli_connect_errno()){
$msg = "Failed to connect to MySQL: " . mysqli_connect_error();
echo $msg;
}
$query = mysqli_query($con, "SELECT * FROM User WHERE Role = tutor AND Subject ='".$sub."'");
$tutors = array();
while ($row = mysqli_fetch_assoc($query)) {
$tutors[] = $row["Username"];
}
$out = '';
for ($i=0; $i<count($tutors); $i++) {
$out .= '<div>' .$tutors[$i]. '</div><br/>
Choose me<br/>
';
}
}else{
$out = "Failed form.";
}
echo $out;
?>
All above code is untested, but could work...

Inserting SQL data into HTML textarea

I've been reading lots of questions at stackoverflow that have made my life easier, first time I ask something though.
Here is my problem. I need to be able to insert different values from my SQL database into a selected < textarea > field, depending on what option is selected in a < select > input on the same form.
The basic idea is that I want to edit news from the database, edit title and body. To do that, I want to show what (title / body) data contains my db to the user, by getting them from my SQL db. User may have multiple entries in the database, so when I select one entry at the < select > combobox, I'd like to change the contents to those from the selected entry from the db.
Its a simple idea difficult to express due to my poor English...
HTML form would be more or less as follows:
<form action="edit.php" method="post">
<select name="id">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
<textarea name="newsBody"></textarea>
<input name="submit" type="submit" value="Edit" />
</form>
SQL database structure goes more or less as follows:
DB name: database
DB table: news (fields id, body, title, author, timestamp)
I'd like to be able to select news from my < select > getting their 'id' / 'option value', then get from the DB the corrrect value, and show it in the corresponding < textarea >.
I'm new into website coding, and do it just as a hobby, so my knowledge in PHP, MySQL is very basic. I dont provide any PHP code or options, simply because I have no idea how to resolve it... I can understand sql, php syntax though.
I thought using < select > event 'onchange' and javascript, but couldn't make it work... Neither could I using jQuery / ajax, probably because the lack of useful examples!!
Hope that someone understands and can provide a solution!
Many thanks in advance!
You can use Ajax.
Create the following .html page:
<html>
<head>
<script>
function showData(str)
{
if (str=="")
{
document.getElementById("ajax-content").innerHTML="";
return;
}
// Code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// Code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("ajax-content").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","showData.php?id="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="news" onchange="showData(this.value)">
<option value="">Select ID:</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>
<div id="ajax-content"></div>
</body>
</html>
And the following .php script (showData.php in my example):
<?php
// Receive variable from URI
$id=$_GET["id"];
// Connect to your database
$con = mysql_connect('localhost', 'user1591005', 'stackOverflow');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Select your database
mysql_select_db("myDatabase", $con);
// Select all fields from your table
$sql="SELECT * FROM news WHERE id = '".$id."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo "<input type='text' value='" . $row['title'] . "'>";
echo "<textarea>" . $row['content'] . "</textarea>";
}
// Close the connection
mysql_close($con);
?>
Alright Ill give you a quick idea before my lunch... :)
Setup an AJAX request to pass the selected dropdown box value to a PHP script.
In this PHP script, fetch the data for the selected value from your database.
Return the data and set the textbox's value to that.
Sending an AJAX Request
It seems that you need to use AJAX and Mysql+PHP for this. The first thing is to collect data from the table.
for example $result = mysql_query('SELECT * FROM new_table WHERE author = author's id')
The second thing is to output the html code with the results from the table you could use
you can do this by using foreach() loop. Then you need to use ajax (from the jQuery framework) and to pull data from the database again on user selection.
Hope this helps
To get the data from the database, you'll have to use a server-side language, such as PHP. To react to the change in the <select> element, you'll have to use JavaScript. AJAX is what will bridge the gap between the two languages.
Firstly write some JavaScript to make the query. If you're using jQuery, this is very straightforward.
<script>
var selector = $("#mySelectorID"); // first select the <select> elm
selector.change(function(e) { // attach a function to it's change event
jQuery.get("getContents.php", // when it changes, make an AJAX call
{id:selector.val()}, // passing the value of the <select> as data
function(returnVal) { // after a successful AJAX ...
$("#myTextAreaID").val(returnVal); // ... set the textarea to the correct value
});
});
</script>
Then create a new php file (slightly simplified, but this would work):
<?php
$id = $_GET['id']; // get the id that was passed through the URL
$connection = mysql_connect("hostname","username","password"); // connect to db
mysql_select_db("database", $connection ); // select the db
$result = mysql_query("SELECT * FROM news WHERE ID = $id"); // make SQL query
if ($row = mysql_fetch_array($result)) { // fetch the first row
echo $row['body']; // output the contents of the row
}
connection mysql_close($connection ); // close the connection
?>
More info on AJAX with jQuery: http://api.jquery.com/jQuery.get/
I am imagining you want to work on a simple html/PHP solution before branching out to Ajax ...
<?php
$title = "" ; // set the variables
$body = "" ;
$action = "" ;
$submit = "Edit";
if(isset($_POST['id']) && (int) $_POST['id'] > 0 ){
// a positive integer was sent to your form
// so now construct your sql statement: ie
// "select title, body from new where id= " . $_POST['id'] ;
// assign your rows to your variables
// $title = $row['title'] ;
// $body = $row['body'] ;
// now re-use your empty form to display the variables
// re-assign the form variables
// $action = "save.php" ;
// $submit = "Save changes";
}
?>
// have the form submit to itself by default
<form action="<?php echo $action; ?>" method="post">
<select name="id">
<option value="1" <?php if($_POST['id'] == 1 ) echo "selected=selected; ?>>Option 1</option>
<option value="2" <?php if($_POST['id'] == 1 ) echo "selected=selected; ?>>Option 2</option>
</select>
// have your html form values the same name as your db table columns
<input type="text" name="title" value="<?php echo $title; ?>"/>
<textarea name="body"><?php echo $body; ?></textarea>
<input name="submit" type="submit" value="<?php echo $submit; ?>" />
</form>
save.php then stores the new values in your database and perhaps redirects back to this page...
I am really paring this down, you'd likely generate your ids from a select from the database, and they'd probably be id, title in alphabetical order:
A big story
Big story
etc
There is lots else to take into consideration, but this is one way to go about it.
If you are using php with SQL to retrieve data from a database you can insert the database field using the following code.
echo '<textarea name="MyText" id="MyText" rows="8" cols="80" >' . $MySelectedText . '</textarea></p>';
Where MySelectedText is the data base field name of your SQL text you have selected from the database.

How do i display specific results from SQL database in a HTML TABLE using select menus

I've been at this for hours and i have gotten a slight break through, however i am at a stand still at the moment. I have a SQL Database that store vehicle information, such as make, model and year. What i want to do is allow users to modify the query and only display specific results.
I understand how to display all the records at once but what i want to add is when the user selects say for example the make as "Toyota" i want only that specific make to appear. I did reach some where in this, by using this code:
<form method="post" action="">
<div id="search_query" >
Make
<select name="make" size="0">
<option value="honda">Honda</option>
<option value="toyota">Toyota</option>
<option value="nissan">Nissan</option>
</select>
<input type="submit" name="submit" value="submit">
</div>
</form>
<?php
$db_con = mysql_connect('localhost', 'root', '');
if (!$db_con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('my_db', $db_con);
$make = mysql_real_escape_string($_POST['make']);
$sql = sprintf("SELECT * FROM chjadb_vehicles WHERE v_make= '$make' ");
$result = mysql_query($sql);
echo "<table width= 970 border=1>
<tr>
<th width='120' scope='col'>Image</th>
<th width='170' scope='col'>Details</th>
<th width='185' scope='col'>Seller</th>
<th width='126' scope='col'>Price</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td> <img src=" .$row['v_image']. " width =200 height = 130>" . "</td>";
echo "<td>". $row['v_year'] . " " . $row['v_make'] . " ". $row['v_model'] . " ". $row['b_type']. "</td>";
echo "<td>". $row['user_id'] ."</td>";
echo "<td>". $row['v_price'] ."</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($db_con);
?>
however when i run the page initially i get this error: "Notice: Undefined index: make in C:\xampp\htdocs\carhuntja.com\buy_a_car.php on line 62"
i did some research and realized that this was happening because i had no make value set, what i wish to do here is at the start of going to that page i want all vehicles to be displayed.
The problem is that the query is being sent before the user chooses a make. To fix this, you need check that the user has actually submitted the form by enveloping your PHP code in if(isset($_POST['submit'])) ("submit" is used because that is the name of your submit button).
//place connection code here (do not query the database yet)
if(isset($_POST['submit']))
{
//all of the database retrieval code
}
else
{
$query_makes = "SELECT v_make FROM chjadb_vehicles";
$result_makes = mysqli_query($query_makes);
echo "Please choose a make."
//echo opening select tag
while($row = mysql_fetch_array($result_makes))
{
//echo each option tag
}
//echo ending select tag
}
Also, you are missing a slash in the self-contained input tag.
Finally, you should use MySQLi functions because MySQL functions are deprecated in PHP.
When the page loads for the first time you need to run this query:
SELECT * FROM chjadb_vehicles
You need to check if the user clicked the submit button and posted the make field, to do that use isset():
if (isset($_POST['make']){
$make = mysql_real_escape_string($_POST['make']);
}
I strongly suggest you use jquery and ajax
EDIT:
First time the page loads you display all vehicles.
In your javascript you bind a onSelect evvent to the dropdown and once the user selects a make, you send an ajax request to the server and display the new results from the server, so it'll look something like that:
$('#search_query select').change(function(){
//get the selected option text
var selectedVal = $(this).find('option:selected').text();
//send ajax request
$.ajax( {
url : url,
type : "POST",
data : selectedVal ,
dataType : 'json',
success : function(data) {//handle returned data}
})
});
I suggest you take a look here, for a complete VIDEO tutorial on jquery.

Call a jQuery function with input data that comes from a PHP script

I have this function http://jsfiddle.net/wnFsE/ . As you can see every time the user writes a languages on the textfield and then hits the button add a new language is added to the list. Then when the user hits save, all the info is sent with POST.
Until now, everything is ok. BUT, when the user sends the info, the info is stored on my MySQL database. So, every time when the user comes again to the page, he needs to see the languages already saved in the last session.
In my PHP script every time the user comes, I retrieve the languages from my database, but I don't know how to add them to the list. The solution would be call the $("#add").click(function() { from the PHP script who retrieve the data from the MySQL, but I don't know how to do this.
If it serves for any help, this is the simple PHP function which retrieves the languages from the user:
function list_lang() {
$this->DBLogin();
$result = mysql_query("SELECT * FROM ".table_lang." WHERE id_user=1");
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo $row['lang']." ".$row['level']."<br>";
//instead of the echo, here will be the call to jquery (if possible)
}
}
A simple soloution:
$buildHTML = '';
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$buildHTML .= '<li>'.$row['lang'].'<input type="hidden" name="languages[]" value="'.$row['lang'].'" />Remove</li>';
}
And then have
<script type="text/javascript">
var UserLangs = <?php echo $buildHTML; ?>;
$('#langs').append(UserLangs);
</script>
You can do this way:
<?php
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<script type="text/javascript">
...
...
listitem_html += <?php echo $row['lang']. $row['level'] . '<br>'?>;
...
...
</script>
<?php
}
?>

Categories