I have a form on my website with 3 drop-down boxes. After user select an option from each one and hit submit the data is posted to an external php file, that makes an query to MySQL and then the page is reloaded and result posted. I'd like to make this more fancy - with ajax without reloading the page. the problem is I'm completely nube. I search interned and tried a couple of examples but no result. Here is the code:
HTML FORM:
<form name="showprice" id="showprice" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="country" id="country">
<option value="">Select Country</option>
</select>
<select name="industry" id="industry" onchange="setOptions(document.showprice.industry.options[document.showprice.industry.selectedIndex].value);">
<option value="">Select Industry</option>
</select>
<select name="quality" id="quality">
<option value=" " selected="selected">Select country and industry first.</option>
</select>
<input value="Submit" type="submit" name="submit" id="submit">
</form>
<script type="text/javascript">
var frmvalidator = new Validator("showprice");
frmvalidator.addValidation("country","req","Please select country");
frmvalidator.addValidation("industry","req","Please select industry");
frmvalidator.addValidation("quality","req","Please select quality");
</script>
NOTE: I have removed the options to save space.
The external view.prices.php:
It is in another folder and now I am calling the result with
<?php include('includes/view.prices.php'); ?>
Present code is:
if(isset($_POST['submit'])) {
include ('config.php');
$con1 = mysql_connect($server, $username, $password);
if (!$con1)
{
die(<b>Could not connect: </b> . mysql_error());
}
echo'<br /><br /><table id="myTable" class="tablesorter" align="center">
<thead>
<tr>
**some table headers (8 columns)**
</tr>
</thead>
<tbody>';
$cou = $_POST['country'];
$ind = $_POST['industry'];
$qua = $_POST['quality'];
$sql = "SELECT * FROM $ind WHERE quality=$qua AND desig=$cou ORDER BY id ASC" or die('<b>Data Insert Error:</b> ' . mysql_error());
echo("<tr>
**Some table results with 8 variables taken from the MySQL database**
</tr>");
if (!mysql_query($sql,$con1))
{
die('Error: ' . mysql_error());
}
}
echo '</tbody>
</table>';
mysql_close($con1);
}}
else {
echo '<div class="grid_9">
<p><b>TIP:</b> Pick country, industry and quality from the drop-down above and hit "Submit" button to view results.</p>
</div>';
}
Any help highly appreciated.
I'd investigate jQuery. You will want to disable the default handler:
e.preventDefault();
Then with jQuery you can do something like:
$.ajax({
type: 'POST',
url: '',
data: $("#showprice").serialize(), dataType: 'json',
success: function(data){
if( data['status'] == 'success' )
{
// Do stuff here
}
}
});
That code assumes that you're going to return a json encoded string. Which jQuery can handle without any problems.
I use jQuery for this all the time.
$(function() {
$('#showprice').sumbit(function() {
$.post('includes/view.prices.php', $(this).serialize(),function(data) {
$('#idoftag').html(data);
})
});
})
With some help from a friend I've managed to do this:
1) In head of the file where is the form add:
<script type="text/javascript" src="path-to-jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var working = false;
$('#id-of-form').submit(function(e){
e.preventDefault();
if(working) return false;
working = true;
//$('#submit').val('Sending..');
$.post('path-to-php-file-to-be-executed',$('#id-of-form').serialize(),function(msg){
working = false;
//$('#submit').val('Submit');
$('#id-of-div-where-result-will-be-outputed').html(msg);
});
});
});
</script>
2) After the form add the div for outputed data
<div id="output_div"></div>
3) In path-to-php-for-execution add:
if(isset($_POST['id-of-form-field-1']) && isset($_POST['id-of-form-field-2']) && isset($_POST['id-of-form-field-3'])) {
// some queries here
}
That's all
in your form, reference your current page as the action value...example, if your page is index.php. then use action="index.php" and method = "post". within the div you want the data to appear, write the php code in the correct format and enclose all this code with an if($_POST){ -your database retrieval code - } ?>. This means that your post action will call the same page which will make the condition surrounding your code to be true, hence executed. Hope this helps, it nagged me back then but i this worked.
In Notepad++, it looks like your { } are mismatched. They line up when I deleted one after the die statement and one above the else.
Related
and thank you in advance for reading this. I'm new in php and jquery. I've managed to do few forms in php that worked, and now feel a big need (because of how my webpage is shaping) to make them work with jquery. I'm trying but something is not right. This is the form:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method ="post" id="form_Add">
<br>
<div class="Add_field" id="title_div">Title:<input typee="text" class="Add_text" maxlength="100" name="title" id="title"></div>
<br>
<div class="Add_field">Discription:<input typee="text" class="Add_text" maxlength="1000" name="discription" id="discription"></div>
<br>
<div class="Add_field" id="content_div">Content:<textarea class="Add_text" maxlength="65535" name="content" id="content" rows="5" cols="15"></textarea></div>
<br>
<div class="Add_field"><label for="shortstory"><input typee="radio" name="prose" class="" id="shortstory" value="1">Short story</label></div>
<div class="Add_field" id="prose_div"><label for="chapter"><input typee="radio" name="prose" class="" id="chapter" value="2">Chapter</label></div>
<br>
<div class="Add_field" id="typey">type:
<select name="type1">
<option value="1" selected="selected">Fantasy</option>
<option value="2">Action</option>
<option value="3">Romance</option>
</select>with elements of
<select name="type2" id="type2">
<option value="" selected="selected"></option>
<option value="1">fantasy</option>
<option value="2">action</option>
<option value="3">romance</option>
</select>and
<select name="type3" id="type3">
<option value="" selected="selected"></option>
<option value="1">fantasy</option>
<option value="2">action</option>
<option value="3">romance</option>
</select>
</div>
<div class="Add_field"><input typee="submit" name="Add_story" class="Add_button" id="submit_story" value="Add story"></div>
</form>
<div id="response">Something</div>
That is script:
<script>
$('#form_Add').on('submit', function (e) {
e.preventDefault();
checkAdd();
});
var selectType = function(){
var type2 = $('#type2').val();
if(type2 === ""){
$('#type3').attr('disabled', 'disabled');
$('#type3').val("");
}
else{
$('#type3').removeAttr('disabled');
}
}
$(selectType);
$("#type2").change(selectType);
function checkAdd(){
var title = $('#title').val();
var content = $('#content').val();
if(title === ""){
$('#titleErr').remove();
$('#title_div').append("<p id='titleErr'>Please add the title.</p>");
}
else{
$('#titleErr').remove();
}
if(content.replace(/ /g,'').length <= 18){
$('#contentErr').remove();
$('#content_div').append("<p id='contentErr'>Content needs to be at least 19 characters long.</p>");
}
else{
$('#contentErr').remove();
}
if($("#shortstory").not(":checked") && $("#chapter").not(":checked")){
$('#proseErr').remove();
$('#prose_div').append("<p id='proseErr'>Check one of the above.</p>");
}
if($("#shortstory").is(":checked") || $("#chapter").is(":checked")){
$('#proseErr').remove();
}
if($("#titleErr").length == 0 && $("#contentErr").length == 0 && $("#proseErr").length == 0){
$.post('"<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"', { // when using this bit of script I get 403 Forbidden in Firebug console
title: $('#title').val(),
discription: $('#discription').val(),
content: $('#content').val(),
prose: $('input[name=prose]:checked').val(),
type1: $('#type1').val(),
type2: $('#type2').val(),
type3: $('#type3').val()
}, function(d){
alert(d);
console.log(d);
$('#response').html(d);
});
}
/*
var postData = $("#form_Add").serialize(); // when using this bit of script instead of one on top, I get alert fail and ReferenceError: data is not defined in Firebug console
var formURL = $("#form_Add").attr("action");
$.ajax(
{
url : formURL,
typee: "POST",
data : postData,
datatypee: 'json',
success:function(data, textStatus, jqXHR)
{
alert("success");//data: return data from server
console.log(data.error);
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
alert("fail");
console.log(data.error);
}
});
}
*/
};
</script>
And here is php code:
<?php
session_start();
if(isset ($_SESSION['arr'])){
$arr = $_SESSION['arr'];
$uid = $arr['id'];
}
$title = $discription = $content = $prose ="";
if (isset($_POST["Add_story"])) {
$title = stripslashes($_POST["title"]);
$title = mysqli_real_escape_string($connection , $title);
$discription = stripslashes($_POST["discription"]);
$discription = mysqli_real_escape_string($connection , $discription);
$content = stripslashes($_POST["content"]);
$content = mysqli_real_escape_string($connection , $content);
$prose = stripslashes($_POST["prose"]);
$prose = mysqli_real_escape_string($connection , $prose);
$type1 = $_POST["type1"];
$type2 = $_POST["type2"];
$type3 = $_POST["type3"];
$pQuery = "INSERT INTO prose (u_id, data, title_s, discription_s, content_s, prose_s, type1_s, type2_s, type3_s, shows_s)
VALUES ('{$uid}', CURDATE(), '{$title}', '{$discription}', '{$content}', {$prose}, '{$type1}', '{$type2}', '{$type3}', 0)";
$resultP = mysqli_query($connection, $pQuery);
if ($resultP) {
$title = $discription = $content = $prose ="";
}
else {
die("Query failed." . mysqli_error($connection));
}
}
?>
Php code is on the top of the document. Source is on bottom and form is in the middle (I'm using jquery-1.11.1.min.js - source is added in main page, as this one is included in it). I've also tried putting php in separate file and pointing to it through form action instead of <?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> but without any joy. I'm guessing my problem is with post data. It probably has to be in an array or object (and I'm doing it wrong) and when it reaches processing there is some sort of incompatibility. Probably using select and radio buttons complicates the process.
Any tips you can share I will greatly appreciate. Thank you for your time.
You have a serious typo in your submit button
<input typee="submit" name="Add_story"
^ extra "e"
which should read as
<input type="submit" name="Add_story"
Your code's execution relies on your conditional statement:
if (isset($_POST["Add_story"])){...}
Plus, you've made the same typo for all your other inputs typee="xxx"
Change them all to type
A simple CTRL-H (typee/type) in a code editor such as Notepad++ even in Notepad will fix that in a jiffy.
I noticed you have given id's to both <select name="type2" id="type2">
and <select name="type3" id="type3"> but not for <select name="type1">, so that could also be another factor that could affect your code's execution, seeing that you have:
type1: $('#type1').val(),
type2: $('#type2').val(),
type3: $('#type3').val()
Edit:
You've also put a commented message which I only saw now and should have been made clear in your question:
// when using this bit of script I get 403 Forbidden in Firebug console
over to the right of
$.post('"<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"', {
so I didn't see that.
Try changing it to either, and in single quotes only:
$.post('<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>', {
or
$.post('your_file.php', $(this).serialize(), function(data){
This page may help:
https://www.codeofaninja.com/2013/09/jquery-ajax-post-example.html
It contains an example in there that you can base yourself on.
which contains
$.ajax({
type: 'POST',
url: 'post_receiver.php',
data: $(this).serialize()
})
and may need to be added to your script.
You commented out url : formURL, - try using url: 'your_PHP_file.php', in its place, that being the PHP/SQL file that you're using.
If none of this helped, than let me know and I will simply delete this answer.
Basically I have a list of data that is shown via a foreach statement from a table in my database. I want a dropdown list next to each that has some values in them that need to be saved to a field in my table, however I want to autosave the value in the dropdown list to the field as soon as the value in it is changed. Can anyone point me to a tutorial or something that might help?
I am using php and mysql to create the system, but will happily use JavaScript if required
I have had a look at this: dynamic Drive Autosavehttp://www.dynamicdrive.com/dynamicindex16/autosaveform.htm which is similar to what i want, however i need it to actually store that data in my database not temporary storage.
Any Guidance appreciated,
Ian
BIG EDIT
So, thankyou for the replys but I have no clue about ajax call.....I found this:How to Auto Save Selection in ComboBox into MYSQL in PHP without submit button?.
can i get it to work?
<script>
$(document).ready(function(){
$('select').live('change',function () {
var statusVal = $(this).val();
alert(statusVal);
$.ajax({
type: "POST",
url: "saveStatus.php",
data: {statusType : statusVal },
success: function(msg) {
$('#autosavenotify').text(msg);
}
})
});
});
</script>
<?php foreach ( $results['jobs'] as $job ) { ?>
<td width="25%"><?php echo $job->job_id</td>
<td>
<select name="status" id="status">
<option value=''>--Select--</option>
<option value='0'>Approve</option>
<option value='1'>Reject</option>
<option value='2'>Pending</option>
</select>
<div id="autosavenotify"></div>
</td>
</tr>
<?php } ?>
and on the page saveStatus.php:
<?php
if (isset($_POST['statusType'])) {
$con=mysql_connect("localhost","username","mypass","rocketdb3");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("jobs", $con);
$st=$_POST['statusType'];
$query = "UPDATE jobs SET status=$st WHERE job_id=$id";
$resource = mysql_query($query)
or die (mysql_error());
}
?>
Where is the $id in saveStatus.php ?
You need to pass the statusType and job_id via AJAX to update correctly in the saveStatus.php.
For example:
<script>
$(document).ready(function(){
$('select').on('change',function () {
var statusVal = $(this).val();
var job_id = $(this).id;
alert(statusVal);
$.ajax({
type: "POST",
url: "saveStatus.php",
data: {statusType : statusVal, job_id: job_id },
success: function(msg) {
$('#autosavenotify').text(msg);
}
})
});
});
</script>
<?php foreach ( $results['jobs'] as $job ) { ?>
<td width="25%"><?php echo $job->job_id; ?></td>
<td>
<select name="status" id="<?php echo $job->job_id; ?>">
<option value=''>--Select--</option>
<option value='0'>Approve</option>
<option value='1'>Reject</option>
<option value='2'>Pending</option>
</select>
<div id="autosavenotify"></div>
</td>
</tr>
<?php } ?>
*Note: .live() is deprecated, use .on() instead.
And saveStatus.php
$st = (int)$_POST['statusType'];
$id = (int)$_POST['job_id'];
$query = "UPDATE jobs SET status=$st WHERE job_id=$id";
You will need to use JavaScript (+ jQuery for easier working) to achieve this.
Catch the 'change' of the value using JavaScript and fire an AJAX call to a PHP script that saves the value to the MySQL db.
Use jQuery! On the drop-down onchange event do a ajax call and update the record in DB. Here is a link to jQuery Ajax method.
I am creating a MySQL query that will be execute when user select options from more a dropdown lists.
What I want is, on selecting a dropdown list option a query related to that option should be automatically executed using ajax/javascript on the same page. As I have the both html and php code on the same page.
Earlier I was using form submit options for dropdown list but as the number of dropdown option are more than five for filtering the result so queries became complicated to implement. That's why I want to refine result of each dropdown individually.
Any help is appreciated. Thanks in advance!
My HTML code for dropdown list is:
<p>
<label for="experience">Experience :</label>
<select id="experience" name="experience">
<option value="" selected="selected">All</option>
<option value="Fresher">Fresher</option>
<option value="Experienced">Experienced</option>
</select>
</p>
PHP code for executing related queries is:
<?php
if (isset($_GET['exp'])) {
switch ($_GET['exp']) {
case 'Experienced':
$query = "SELECT job_seekers.ID, job_seekers.Name, job_seekers.Skills, job_seekers.Experience FROM job_seekers where job_seekers.Experience!='Fresher'";
break;
case 'Fresher':
$query = "SELECT job_seekers.ID, job_seekers.Name, job_seekers.Skills, job_seekers.Experience FROM job_seekers where job_seekers.Experience='Fresher'";
break;
default:
$query = "SELECT job_seekers.ID, job_seekers.Name, job_seekers.Skills, job_seekers.Experience FROM job_seekers";
}
}
$result = mysql_query($query) or die(mysql_error());
echo "<ul class=\"candidates\">";
while($row = mysql_fetch_row($result))
{
echo "<li>";
echo "<p> <b>ID:</b> <u>$row[0]</u> </p>";
echo "<p> <b>Name :</b> $row[1] </p>";
echo "<p> <b>Key Skills:</b> $row[2] </p>";
echo "<p> <b>Experience:</b> $row[3] </p>";
echo "</li>";
}
echo "</ul>";
?>
When you want to AJAX call a php script, you should you $.ajax provided by Jquery
http://api.jquery.com
so you can use it like so:
$.ajax({
url: 'ajax.php',
data: {
//put parameters here such as which dropdown you are using
},
success: function(response) {
//javascript and jquery code to edit your lists goes in here.
//use response to refer to what was echoed in your php script
}
});
this way, you will have dynamic dropdowns and the refined results you want
<?php
if (isset($_GET['experience'])) {
echo $_GET['experience'];
/* do mysql operations and echo the result here */
exit;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
function myFunction(value)
{
if(value!="All")
{
$.ajax(
{
type: "GET",
url: '<?php echo $_SERVER['PHP_SELF']; ?>',
data: { experience: value},
success: function(data) {
$('#resultDiv').html(data);
}
});
}
else
{
$('#resultDiv').html("Please select a value.");
}
}
</script>
</head>
<body>
<p>
<label for="experience">Experience :</label>
<select id="experience" name="experience" onChange="myFunction(this.value)">
<option value="All" selected="selected">All</option>
<option value="Fresher">Fresher</option>
<option value="Experienced">Experienced</option>
</select>
</p>
<div id="resultDiv">
Please select a value.
</div>
</body>
</html>
You cannot re-execute a PHP part on the same page. Rather use Ajax request to perform the action.
Problem solved...variable undefined. I will add full answer when stackoverflow allows me to answer own question
update, firebug is telling me that the variable barrister is undefined in plugin.php but I do define that variable (or at least I try to)
this is the line where it's supposedly undefined: if(barrister.attr("value"))
this is the line where I try to define it: var barrister = $('input:radio[name=barrister]:checked').val();
I'm using a form with a radio button to submit data. The file plugin.php is supposed to get the data using javascript/ajax and then send it to results.php so that it can be inserted into the database. Information's also retrieved from the database and is supposed to be inserted into the html. I can't figure out where it's breaking down, but I do know the database connection itself works. Any idea how I might find out the broken link? When I test it and check the database, there's no data in it.
The form
<form method="post" id="form">
<table>
<tr>
<td><label>Barrister's Exam</label></td>
<td><input type="radio" id="barrister" name="barrister" value="1" /> Pass</td>
<td><input type="radio" id="barrister" name="barrister" value="0" /> Fail</td>
</tr>
<tr>
<td>Submit</td>
<td><input id="send" type="submit" value="Submit" /></td>
</tr>
</table>
</form>
Getting the form data with plugin.php
function my_function() { ?>
<script type="text/javascript">
$(document).ready(function(){
//global vars
var barrister = $('input:radio[name=barrister]:checked').val();
var loading = $("#loading");
var messageList = $(".content > ul");
//functions
function updateShoutbox(){
//just for the fade effect
messageList.hide();
loading.fadeIn();
//send the post to shoutbox.php
$.ajax({
type: "POST", url: "http://yearofcall.com/wp-content/plugins/myplugin/results.php", data: "action=update",
complete: function(data){
loading.fadeOut();
messageList.html(data.responseText);
messageList.fadeIn(2000);
}
});
}
//check if all fields are filled
function checkForm(){
if(barrister.attr("value"))
return true;
else
return false;
}
//Load for the first time the shoutbox data
updateShoutbox();
//on submit event
$("#form").submit(function(){
if(checkForm()){
var barrister = barrister.attr("value");
//we deactivate submit button while sending
$("#send").attr({ disabled:true, value:"Sending..." });
$("#send").blur();
//send the post to results.php
$.ajax({
type: "POST", url: "http://yearofcall.com/wp-content/plugins/myplugin/results.php", data: "action=insert&barrister=" + barrister,
complete: function(data){
messageList.html(data.responseText);
updateShoutbox();
//reactivate the send button
$("#send").attr({ disabled:false, value:"Send" });
}
});
}
else alert("Please fill all fields!");
//we prevent the refresh of the page after submitting the form
return false;
});
});
</script>
<?php
}
add_action('wp_head', 'my_function');
putting the data into "results" table of the database "year" with results.php I know the database connection works
<?php
define("HOST", "host");
define("USER", "user");
define("PASSWORD", "password");
define("DB", "year");
/************************
FUNCTIONS
/************************/
function connect($db, $user, $password){
$link = #mysql_connect($db, $user, $password);
if (!$link)
die("Could not connect: ".mysql_error());
else{
$db = mysql_select_db(DB);
if(!$db)
die("Could not select database: ".mysql_error());
else return $link;
}
}
function getContent($link, $num){
$res = #mysql_query("SELECT barrister FROM results ORDER BY date DESC LIMIT ".$num, $link);
if(!$res)
die("Error: ".mysql_error());
else
return $res;
}
function insertMessage($barrister){
$query = sprintf("INSERT INTO results(barrister) VALUES('%s');", mysql_real_escape_string(strip_tags($barrister))
));
$res = #mysql_query($query);
if(!$res)
die("Error: ".mysql_error());
else
return $res;
}
/******************************
MANAGE REQUESTS
/******************************/
if(!$_POST['action']){
//We are redirecting people to our shoutbox page if they try to enter in our shoutbox.php
header ("Location: index.html");
}
else{
$link = connect(HOST, USER, PASSWORD);
switch($_POST['action']){
case "update":
$res = getContent($link, 100);
while($row = mysql_fetch_array($res)){
$result .= "<li><strong>".$row['user']."</strong><img src=\"http://eslangel.com/wp-content/plugins/myplugin/CSS/images/bullet.gif\" alt=\"-\" />".$row['message']." </li>";
}
echo $result;
break;
case "insert":
echo insertMessage($_POST['barrister']);
break;
}
mysql_close($link);
}
?>
The html where the data is returned to when retrieved from the database
<div id="container">
<ul class="menu">
<li></li>
</ul>
<span class="clear"></span>
<div class="content">
<div id="loading"><img src="http:///></div>
<ul>
<ul>
</div>
</div>
The first error I notice is that all of your radio buttons have the same ID. An ID attribute should be unique on the page. Besides this, the best tool for debugging javascript is the console.
Javascript Debugging for beginners
EDIT
Here's an example of an ajax form submit using your markup http://jsfiddle.net/UADu5/
$(function(){
// Submit form via ajax
$('#check').click(function(){
var barrister = null
$.each($("input[name='barrister']:checked"), function(){
if($(this).val() == 1)
barrister = $(this).attr('value');
});
if(barrister){
$.ajax({
type: "POST", url: "http://yearofcall.com/wp-content/plugins/myplugin/results.php",
data: "action=insert&barrister=" + barrister,
complete: function(data){
messageList.html(data.responseText);
updateShoutbox();
//reactivate the send button
$("#send").attr({ disabled:false, value:"Send" });
}
});
} else {
alert('Please fill all fields!')
}
})
})
<form method="post" id="form">
<fieldset>
<legend>Grade Exams</legend>
<ul>
<li>
<p>Barrister's Exam</p>
<label>
<input type="radio" name="barrister" value="1" /> Pass
</label>
<label>
<input type="radio" name="barrister" value="0" /> Fail
</label>
</li>
<li class="submit">
<input type="button" id="check" value="Test">
</li>
</ul>
</fieldset>
</form>
I strongly recommend using Firebug, as it will show you all the requests being made and all the request/response header info so you can see if and where the AJAX is going wrong. It's also great for debugging HTML/CSS stuff!
Firebug practically changed my life when it comes to JavaScript and CSS.
I think you have error in insert statement:
//remove extra bracket and semicolon
sprintf("INSERT INTO results(barrister) VALUES('%s')", mysql_real_escape_string(strip_tags($barrister))
);
Hope it helps
Change
var barrister = $('input:radio[name=barrister]:checked').val();
to
barrister = $('input:radio[name=barrister]:checked');
should help.
I am trying to build my first jquery web application, but I've hit a roadblock and can't seem to figure this out.
I have a PHP page and an HTML page.
The HTML page has a form with a triple drop down list.
The PHP page connects to the database but I am not sure how to pass the query result from the php page to populate the drop down list on the html/javascript page.
Here is my code thus far.
HTML:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#selector").submit(function() {
$.ajax({
type: "GET",
url: "DBConnect.php",
success: function(msg){
alert(msg);
}
});
var select_car_make = $('#select_car_make').attr('value');
var select_car_model = $('#select_car_model').attr('value');
var select_car_year = $('#select_car_year').attr('value');
alert("submitted");
}); //end submit
});
</script>
<h1 style="alignment-adjust:center">Car information:</h1>
<hr />
<div id="results">
<form action="get.php" id="selector" method="get" name="sizer">
<table width="451" height="70" border="0">
<th width="145" height="66" scope="row"><label for="select_car_make"></label>
<div align="center">
<select name="select_car_make" id="select_car_make" onchange="">
</select>
</div></th>
<td width="144"><label for="select_car_model"></label>
<div align="center">
<select name="select_car_model" id="select_car_model">
</select>
</div></td>
<td width="140"><label for="select_car_year"></label>
<div align="center">
<select name="select_car_year" id="select_car_year">
</select>
</div></td>
</tr>
</table>
<input name="completed" type="submit" value="submit" />
</form>
Here is the PHP Page:
<?php
$DBConnect = mysqli_connect("localhost", "root", "password", "testing")
or die("<p>Unable to select the database.</p>" . "<p> Error code " . mysqli_errno($DBConnect) . ": " . mysqli_error($DBConnect)) . "<p>";
echo "<p>Successfully opened the database.</p>";
$SQLString1 = " SELECT car_make FROM cars";
$QueryResult = mysqli_query($DBConnect, $SQLString1)
Hey Justin if this is your first time dipping your toes, I would keep it ultra-simple. Put the select box inside something with an ID, such as a span or div. Then get your AJAX response to just rewrite the contents, this is an easy and clear way to start with AJAX, for example:
$.ajax({
type: "POST",
url: "/call.php",
data: "var=" + myData,
success: function(response){
$("#someId").html(response);
}
});
On your remote page just echo the whole select box:
echo "<select name='cars'>";
echo "<option value='".$value."'>".$name."</option>";
etc...
Again this isn't the best way, but its certainly not the worst.
You should be able to JSON encode your result from PHP into a variable which Javascript or the Jquery can read. I did it like this with an image string I received from PHP reading a directory of images:
var imageFiles = '<?=$images_js?>';
imageFiles = $.parseJSON(imageFiles);
var images = [];
for(i = 0; i<imageFiles.length; i++){
var image = document.createElement('img');
image.src = imageFiles[i];
images.push(image);
}
var count = imageFiles.length;
var i = 0;
the is the variable which came from my php result. The $.parseJSON(imageFiles); does the interpretation for the variable.
I hope this helps, or puts you along the right path.
If you want the car make selection page to be populated by your database, you should give it a .php extension as well. I think you should reconsider if AJAX is the best option.
But I would put the database connection code inside a "conn.php" file to be included on your selection page then populate it with PHP.