Adding/Removing form fields with Php - php

I have a form which gives the ability for the user to add additional fields form to the form and it selects data from the database for the select/options.
It works ok but not entirely correct and am wondering if somebody wouldn't mind casting an eye on the code to see if can be done in a much cleaner way.
The main issue being that the select isn't sending the correct value across to the action script.
HTML output of the form:
<?php $dashboardId = $_GET['dashboard_id']; ?>
<form action="cm.php" method="POST">
<input type="hidden" name="dashboardId" value="<?php echo $dashboardId; ?>">
<div id="exercises">
<div class="team">
<select name="teamId[]">
<?php
$sql = "SELECT * FROM teams WHERE dashboard_id = $dashboardId";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo '<option value="' . $row["team_id"] . '">' . $row["team_name"] . '</option>';
}
}
?>
</select>
<button class="remove">x</button>
</div>
</div>
<button id="add_exercise">add more</button>
<br>
<input type="text" name="memberName">
<br>
<input type="submit" name="submit" value="Create Member" />
</form>
So the above renders out my simple form. The second part the JQuery that handles the facility to add additional select fields.
<script type="text/javascript">
$('#add_exercise').on('click', function() {
$('#exercises').append('<div class="team"><select name="teamName[]"><?php
$sql = "SELECT * FROM teams WHERE dashboard_id = $dashboardId";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo '<option value="' . $row["team_id"] . '">' . $row["team_name"] . '</option>';
}
}
?> </select><button class="remove">x</button></div>');
return false; //prevent form submission
});
$('#exercises').on('click', '.remove', function() {
$(this).parent().remove();
return false; //prevent form submission
});
</script>
Now as can be seen it isn't the neatest of solutions combining the jQuery with the Php however I am not sure how else I would separate it out? So what is happening is when I do a var_dump($_POST) I see that the generated select passes ["teamName"]=> array(1) { [0]=> string(3) "211" where it should be passing ["teamId"]=> array(1) { [0]=> string(3) "211"
I am fully aware it is open to SQL injection but for now I am just trying to make this little part work.
update - team table scehema

Main.php File
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div class="wrapper">
<div>
<select class="options" name="">
<option value="1">item_1</option>
<option value="1">item_2</option>
<option value="1">item_3</option>
</select>
</div>
</div>
<button type="button" class="addme" name="button">Add More</button>
</body>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
$('.addme').click(function(){
$.ajax({
url:'getData.php',
type:'GET',
success:function(result){
console.log(result);
$('.wrapper').append(result);
}
})
});
});
getData.php File
<select>
<option value='1'>Item1</option>
<option value='2'>Item2</option>
<option value='3'>Item3</option>
</select><br>
In this example getData file data was static but you have write query to get dropdown list data and pass in success response.

Related

Why does my submit button not submit to mySQL?

I have a php form I'll call it "php1" that uses ajax to populate the input text boxes from a mySQL db. to do so it uses a secondary page I'll call "php2". On php2 there is a submit "button" being used to submit any changes to the mySQL db. Every aspect works beautifully, except the submit, unless I test php2 by itself, then it submits to the db.What am I doing wrong?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
function myBlur(str){
if (str == "") {
document.getElementById("demo").innerHTML = "You Must Enter a Device Name! <br>";
$("#demo").css("background-color","red");
$("#Name").css("background-color","red");
return;
} else {
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("form1").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","php2.php?q="+str,true);
xmlhttp.send();
}
}
</script>
This is to call the second page.
<fieldset><legend>Input</legend>
<div width="100%" id="form1">
<div id="demo"><br></div><br>
<form method="post" action="php1.php">
Asset Number: <input type="text" required="required" id="Name" name="Name" autocomplete="off" autofocus="true" value="<?php echo $Name ?>" onChange="myBlur(this.value)">
MAC Address: <input type="text" id="MAC" name="MAC" autocomplete="off" value="<?php echo $MAC ?>">
Owner or Location: <input type="text" id="Own" name="Own" readonly="true" value="<?php echo $Own ?>">
Type: <select name="Type" id="Type" required="required" readonly="true" value="<?php echo $Type ?>">
<option value=""></option>
<option value="Desktop">Desktop</option>
<option value="Laptop">Laptop</option>
<option value="Server">Server</option>
<option value="Monitor">Monitor</option>
<option value="Printer">Printer</option>
<option value="Phone">Phone</option>
</select>
<br>
</div>
</fieldset>
</form>
That is the form code from php1
$sql = "SELECT * FROM $table WHERE Name = '$q'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$N=$row["Name"];
$MA=$row["MAC"];
$Ow=$row["Own"];
$Ty=$row["Type"];
echo "<tr>";
echo "<form method='post' action='php1.php' id='UpAss'>",UpAss,"
<br><br>
Device Name: <input type='text' id='Name' name='Name' value=".$N." onBlur='myBlur(this.value)'>
MAC Address: <input type='text' id='MAC' name='MAC' readonly='True' autocomplete='off' value=". $MA.">
Owner or Location: <input type='text' id='Own' name='Own' value=". $Ow.">
Type: <select id='Type'>
<option value='".$Ty."'>". $Ty."</option>
<option value='Desktop'>Desktop</option>
<option value='Laptop'>Laptop</option>
<option value='Server'>Server</option>
<option value='Monitor'>Monitor</option>
<option value='Printer'>Printer</option>
<option value='Phone'>Phone</option>
<option value='iPhone'>iPhone</option>
</select>
echo "<input type='submit' id='Usubmit' value='Update Asset' form='UpAss' onClick='myUpdate()'></input></form>";
}
function myUpdate()
{
// Create connection
$connU = new MySQLi($db_host, $db_user, $db_pass, $db_name, $db_port);
// Check connection
if ($connU->connect_error) {
die("Connection failed: " . $connU->connect_error);
}
$Name = ($_POST["Name"]);
$MAC = ($_POST["MAC"]);
$Own = ($_POST["Own"]);
$Model = ($_POST["Model"]);
$OS = ($_POST["OS"]);
$Type = ($_POST["Type"]);
$sqlU = "REPLACE INTO SET $table SET MAC='$MAC', Own='$Own', Type='$Type' WHERE Name=$Name;";
if ($connU->query($sqlU) === TRUE) {
echo "PPC-".$Name." Has Been Updated!";
} else {
echo "Error: " . $sqlU . "<br>" . $connU->error;
}
$connU->close();
}
if(isset($_POST['Usubmit']))
{
myUpdate();
}
?>
And that is the code to load the form from php2 in to php1. I am sure it is something simple that I am missing and would appreciate any help. all this code works great, but the submit.
*(I left the DB information out of this code on purpose.)
1.) For Posting(Insert, update and delete via ajax)
This will get you started on how to post via ajax jquery. you can see comments on the code
You can also see that form parameter is set to id="add_content" which is refrenced in the jquery ajax call
<form method="post" id="add_content">
you can also see in the body of the html div that shows image loader when button is click and when result from backend is displayed hence
see sample on that
post.html
<html><head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function(){
$('#add_content').on('submit', function(e){
e.preventDefault();
alert('ok');
// display a loading image and message
$('#loader').fadeIn(400).html('<img src="loader.gif" align="absmiddle"> <span class="loading">Please Wait.. submiting form..</span>');
$.ajax({
type:'POST',
url:'post.php',
data:$(this).serialize(),
crossDomain: true,
cache:false,
success:function(msg){
// hide loader to display result
$('#loader').hide();
$('#showposts').fadeIn('slow').prepend(msg);
}
});
});
});
</script>
</head>
<body>
<div id="loader"> </div>
<div id="showposts"> </div>
<form method="post" id="add_content">
Asset Number: <input type="text" required="required" id="Name" name="Name" autocomplete="off" autofocus="true" value="100" onChange="myBlur(this.value)">
MAC Address: <input type="text" id="MAC" name="MAC" autocomplete="off" value="1001">
Owner or Location: <input type="text" id="Own" name="Own" readonly="true" value="nancy read only">
Type: <select name="Type" id="Type" required="required" readonly="true" value="nancy type">
<option value=""></option>
<option value="Desktop">Desktop</option>
<option value="Laptop">Laptop</option>
<option value="Server">Server</option>
<option value="Monitor">Monitor</option>
<option value="Printer">Printer</option>
<option value="Phone">Phone</option>
</select>
<br>
</div>
</fieldset>
<input type="submit" name="add" id="add" value="Add" />
</form>
</body>
example of post.php
<?php
// use strip_tags to avoid html injection that can also leads to xss attck
// sample with assets number
$asset_number= strip_tags($_POST['Name']);
$MAC= $_POST['MAC'];
$Own= $_POST['Own'];
$Type= $_POST['Type'];
// you can check for emptiness eg.
if($asset_number ==''){
echo "asset number is empty";
exit();
}else{
echo "success. my assests no is: $asset_number";
}
?>
sample 2.
if you want fetch records only with or without sending parameters, you can try
Remember to pass jquery library (jquery.min.js) if you are calling it from another page
<script>
$(document).ready(function(){
// set variable payload for formality. though you can pass it to backend as a variable
var payload= 'Am Nancy Mooree';
var datasend = "payload="+ payload;
$('#loader1').fadeIn(400).html('<img src="loader.gif" align="absmiddle"> <span class="loading">Please Wait.. submiting form..</span>');
$.ajax({
type:'POST',
url:'showresult.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
$('#loader1').hide();
$('#listposts').fadeIn('slow').prepend(msg);
}
});
});
</script>
<div id="loader1"></div>
<div id="listposts"></div>
showresult.php
<?php
// assuming you are sending a post or get variables to query database
$payload= strip_tags($_POST['payload']);
// query your database to display result to ajax.
echo $result ="Am from database where payload is: $payload";
?>

Submit form in div with ajax, return php in div without refresh

I have an index page with three buttons at the top. On the click of each button a php file is loaded into the main div. One of these buttons loads a form that users fill out and submit. On submitting of the form I need it to not refresh the page and to load the resulting data into a div on the form page...not the main div.
If I load the form page on it's own (ie, not by clicking on the button, but just typing in the address of the form itself)...everything works fine. The form validation works, it submits without a refresh and the resulting data is returned into the results div on the form.
However, I load the index page and click on the button to load the form. The form loads correctly, but when I click submit it just refreshes the page...which causes the form to disappear since the div into which it is loaded is originally hidden. Also, the form doesn't validate and doesn't execute the php action.
Again, the form and its associate php work perfectly on their own. The issue only comes up when I load the form in the index page. So I'm assuming that this issue has something to do with me loading it into a div on the index page. Any help would be greatly appreciated.
Index code:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<div id="header">
<center><h2>OMS Tutoring Database</h2></center>
</div>
<div id="navbar">
<center>
<button class="navbutton" id="buttonview" type="button">View Tutoring Lists</button>
<button class="navbutton" id="buttonadd" type="button">Add Students</button>
<button class="navbutton" id="buttonadmin" type="button">Admin</button>
</center>
<br>
</div>
<div id="content"></div>
<script>
$(document).ready(function() {
$('#buttonview').click(function(){
$('#content').load('tutoring.php', function(){
});
});
$('#buttonadd').click(function(){
$('#content').load('addtest.php', function(){
});
});
$('#buttonadmin').click(function(){
$('#content').load('admin.php', function(){
});
});
});
</script>
</body>
</html>
Form Code
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#addstudent").validate({
debug: false,
rules: {
studentid: "required",
teacher: "required",
assignment: "required",
date: "required",
},
messages: {
studentid: "Please enter the student's ID number.",
teacher: "Please enter your name.",
assignment: "Please select a tutoring assignment.",
date: "Please select a day.",
},
submitHandler: function(form) {
$.ajax({
url: 'add.php',
type: 'POST',
data: $("#addstudent").serialize(),
success: function(data) {
$("#studentid").val("");
$('#studentid').focus();
$("#results").empty();
$("#results").append(data);
}
});
return false;
}
});
});
</script>
</head>
<title>OMS Tutoring - Add Student</title>
<body>
Use this form to add students to the tutoring list.
<p>
<div style="float:left;width:100%;margin-bottom:10;">
<div>
<form name="addstudent" id="addstudent" action="" method="post">
<fieldset><legend>Add student to tutoring list</legend>
<div><label for="studentid">ID number</label><input type="text" name="studentid" id="studentid"></div>
<div><label for="day">Date</label><select name="date" id="date">
<option value="">Please select a day</option>
<option value="mon">Monday <? echo $monday; ?></option>
<option value="tue">Tuesday <? echo $tuesday; ?></option>
<option value="wed">Wednesday <? echo $wednesday; ?></option>
<option value="thu">Thursday <? echo $thursday; ?></option>
<option value="fri">Friday <? echo $friday; ?></option>
</select></div>
<div><label for="assignment">Tutoring assignment</label><select name="assignment" id="assignment">
<option value="">Please select an assignment</option>
<option value="att">Activity Time</option>
<option value="acc">ACC</option>
<option value="tech">ACC Tech </option>
<option value="ast">After School</option>
</select></div>
<div><label for="teacher">Assigning teacher</label><input type="text" name="teacher" id="teacher"></div>
<input type="submit" name="submit" value="submit">
</fieldset>
</form></div></div>
<div id="results" style="margin-left:4;width:350;"><div>
</body>
</html>
Form processing php code:
<?php
$mysqli = new mysqli('localhost', 'xxx', 'xxx', 'xxx');
$studentid = $_REQUEST['studentid'];
$day = $_REQUEST['date'];
$assignment = $_REQUEST['assignment'];
$teacher = $_REQUEST['teacher'];
$dayquery = $mysqli->query("SELECT date FROM days WHERE day='$day'");
$dayresult = $dayquery->fetch_array();
$date = array_shift($dayresult);
$timestamp = date('Y-m-d H:i:s');
$mysqli->query("INSERT INTO assign (id, assignment, assignteacher, date, timestamp)
VALUES ('$studentid', '$assignment', '$teacher', '$date', '$timestamp')");
$namequery = $mysqli->query("SELECT first, last FROM students WHERE students.id='$studentid'");
$nameresult = $namequery->fetch_array();
echo $nameresult['first'].' '.$nameresult['last'].' successfully added.';
$teacherquery = $mysqli->query("SELECT assignteacher FROM assign WHERE id='$studentid' AND date='$date'");
$rowcount = $teacherquery->num_rows;
if ($rowcount > 1) {
while ($row = $teacherquery->fetch_array()) {
$teachernames[] = $row[0];
}
$teachers = implode(', ', $teachernames);
echo '<br><br>Caution: '.$nameresult['first'].' '.$nameresult['last'].' has already been added by the following teachers: '.$teachers.'. ';
echo 'They may have precedence.';
}
else {
}
$alreadyadded = $mysqli->query("SELECT assign.id, students.first, students.last, assign.assignment, assign.assignteacher FROM assign
LEFT JOIN students
ON assign.id=students.id
WHERE assign.date='$date' AND assign.assignteacher='$teacher'
ORDER BY assign.assignment ASC, students.last ASC");
echo '<br><br><br>You already have the following student(s) assigned to tutorials on this day';
echo '<table border="1">';
while ($row = $alreadyadded->fetch_array()) {
echo '<tr><td>'.$row['id'].'</td><td>'.$row['first'].'</td><td>'.$row['last'].'</td><td>'.$row['assignment'].'</td></tr>';
}
?>
When you load the form into your page using the load method, most browsers delete the <head> tag.
As from the jquery website:
During this process, browsers often filter elements from the document
such as <html>, <title>, or <head> elements. As a result, the elements
retrieved by .load() may not be exactly the same as if the document
were retrieved directly by the browser.
So, include your javascript in the main page instead of in the form page, or manually add the javascript to your main page dynamically.

Displaying mysql query result using jquery

I'm trying to display data from mysql on the same page that i've got my form with checkboxes. The question is how to write js script that gonna display it.
The code is:
<form id="myForm" action="pdoakcja.php" method="post">
<!--Instruktor: <input type="text" name="name" /> -->
Permissions:<input type="checkbox" name="M1" value="M1" />M1
<input type="checkbox" name="M2" value="M2" />M2
<input type="submit" value="Szukaj" />
</form>
<div id='name-data'>Instruktorzy o podanych uprawnieniach:</div>
<script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script>
............??????
</script>
You could solve your problem by using jquery form plugin, which will help you to submit the form without having to reload the page and show you the return from your target page in the same page. Just follow the instructions:
Download this jquery form plugin first and save it.
Then
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<!-- This jquery.form.js is for Submitting form data using jquery and Ajax -->
<script type="text/javascript" src="js/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
success: showResponse
};
// bind form using 'ajaxForm'
$('#myForm').ajaxForm(options);
});
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
if(responseText==1){
$("#error").html('No Result Found');
} else{
$("#result").html(responseText);
}
}
</script>
<form id="myForm" enctype="multipart/form-data" action="pdoakcja.php"
method="post" name="myForm">
<!--Instruktor: <input type="text" name="name" /> -->
Permissions:<input type="checkbox" name="M1" value="M1" />M1
<input type="checkbox" name="M2" value="M2" />M2
<input type="submit" value="Szukaj" />
</form>
<span id="error"></span>
<span id="result"></span>
YOUR pdoakcja.php file: (I have got the following code from your another post here, haven't checked it though)
<?php
$query = mysql_query("SELECT * FROM permissions WHERE m LIKE '".$_POST['M1']."' OR m LIKE '".$_POST['M2']."' OR mn LIKE '".$_POST['MN1']."' ");
if($query) {
while($permissions = mysql_fetch_assoc($query)){
$query2 = mysql_query("SELECT name_surname FROM instruktorzy WHERE instruktor_id='".$permissions['instruktor_id']."'");
while($Mdwa = mysql_fetch_assoc($query2)){
echo "<p style=\"font-size: 14px; font-family: Helvetica; background-color: #FFFFFF\"> ".$Mdwa['name_surname']."<br />" ; "</p>" ;
}
}
} else {echo "1";}
?>
I hope this will work for you. For detail information you could study the jquery form plugin's website.
Heres a pseudo example showing how you can do it with jQuery, this will also update as you click the check box so you could remove the submit altogether;
You say you already have a database doing the job so I wont include that. Just copy and paste.
<?php
//Some pseudo data kinda as your receive it from a query
$datafromSql = array(
array('id'=>1,'permission'=>'M1','theData'=>'User has M1 permission'),
array('id'=>2,'permission'=>'M2','theData'=>'User has M2 permission'),
array('id'=>3,'permission'=>'M1','theData'=>'User has M1 permission'),
array('id'=>4,'permission'=>'M1','theData'=>'User has M1 permission'),
);
//Access the data
if($_SERVER['REQUEST_METHOD']=='POST'){
$is_ajax = false;
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'){
$is_ajax = true;
}
//pseudo code, really you would put your query here
// SELECT theData FROM your_table WHERE permission=POST_VALUE ... ...
//And then format your output
$result=array();
foreach($datafromSql as $row){
if($is_ajax == true){
foreach($_POST as $key=>$value){
if($_POST[$key] == 'true' && $row['permission']==$key){
$result[]=$row['theData'].'<br />';
}
}
}else{
foreach($_POST as $key=>$value){
if($_POST[$key] == $row['permission']){
$result[]=$row['theData'].'<br />';
}
}
}
}
$result = implode('<hr />',$result);
//AJAX Response, echo and then die.
if($is_ajax === true){
header('Content-Type: text/html');
//example output sent back to the jQuery callback
echo $result;
//echo '<pre>'.print_r($_POST,true).'</pre>';
die;
}
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js" charset="utf-8"></script>
<script type="text/javascript">
function update(){
$.post('./<?php echo basename(__FILE__)?>',
{
M1: $("#M1").is(':checked'),
M2: $("#M2").is(':checked')
},
function(data) {
$('#result').replaceWith('<div id="result"><h1>The Result:</h1>'+ data +'</div>');
});
}
</script>
</head>
<body>
<form method="POST" action="<?php echo basename(__FILE__)?>">
Permissions:
<input type="checkbox" id="M1" name="M1" value="M1" onChange="update()"/>M1
<input type="checkbox" id="M2" name="M2" value="M2" onChange="update()"/>M2
<input type="submit" value="Szukaj" />
</form>
<p id='result'><?php echo isset($result)?$result:null;?></p>
</body>
</html>
You should use the PHP MySQL functions to retrieve the data you want from your database and then display them via PHP, not javascript.
Especially have a look at this: mysql_fetch_assoc - there is a fully working example.

Post result from a query via php in same page with Ajax

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.

Using JSON to select a Dropbox option

I am using Json to retrieve elements from mysql and insert them into form boxes. Displaying in form boxes(text type) was not a problem but in my html one of my form structure is dropbox ... How should i display info that is in the database to the one that is in dropbox??
Here is the code that i used for displaying elements in form type (text). One of them is dropbox in the html.
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#button1").click(function(){
$.post('script_1.php', { id: $('input[name="id"]', '#myForm').val() },
function(json) {
$("input[name='title']").val(json.title);
$("input[name='rno']").val(json.rno);
$("input[name='url']").val(json.url);
}, "json");
});
</script>
</head>
<body>
<form id="myForm" method="post">
id: <input type="text" name="id"/>
<input type="button" id="button1" value ="Get"/>
<input type="button" id="button2" value="Submit to script 2" />
<p>title:<input type="text" name="title"/></p>
<p>Report No:<input type="text" name="rno"/></p>
<p>URL:<input type="text" name="url"/></p>
Institution: <select name="institution">
<option value="abc">abc</option>
<option value="cdf">cdf</option>
</select>
</form>
<div id="age"></div>
</body>
</html>
PHP part or script_1.php
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);
//connect to DB part
$name = mysql_real_escape_string($_POST['id']);
$sql ="SELECT * FROM parentid WHERE id = '$name'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
**//i am not using $row['institution'] (no institution or dropbox part)**
$abc_output = array('title' => $row['title'],'rno' => $row['reportno'],'url' => $row['calc_url']);
}
}
echo json_encode($abc_output);
}
}
?>
Help appreciated.John.
var option1 = new Option("InstitutionName1","InsitutionValue1");
var option2 = new Option("InstitutionName2","InsitutionValue2");
document.myForm.institution.options.length = 0;
document.myForm.institution.options[0] = option0;
document.myForm.institution.options[1] = option1;
This is the way its done normally. In this particular case, you may want to have a for loop or something or jQuery's each(..).
#John
You can put the following snnipet of code at the end of the script tag:
for (item in json.institution) {
$('select[name="institution"]').html('').append('<option value="' + json.institution[item].value + '">' + json.institution[item].text + '</option>');
}
where:
json.institution is a named array that will be returned along with the other form fields by your .php script.
json.institution[item].value is the value of each option.
json.institution[item].text is the text of each option.
The .html('') code is for clear the previous loaded select options.

Categories