How to post data to database in Jquery - javascript

Currently I have this jquery that helps me to get data from my database which only display the different types of option when this department is selected. But now I want to post this data to database again. is there any solution available? Here's my code:
<script type="text/javascript" src="js/jquery-1.7.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#cat").change(function() {
$.ajax({
type: "GET",
url: "getPositionTitle.php",
data: "category_id=" + $(this).find(":selected").val(),
cache: false,
success: function(msg){
$("#position_title").empty();
my_position_title_array = $.parseJSON(msg);
for (i = 0; i < my_position_title_array.length; i ++) {
$("#position_title").append('<option value="' + my_position_title_array[i].id + '">'
+ my_position_title_array[i].position_title + '</option>');
}
$("#position_title").trigger('change');
}
});
});
$("#cat").trigger('change');
});
</script>
<form id="offeredjob" method="post" action="doOfferedJob.php">
<tr>
<td><label for="applied_department">Department:</label></td>
<td>
<select id="cat" name ="applied_department" applied_position_title="category">
<?php
$query = "SELECT id, department FROM department";
$result = mysqli_query($link, $query) or die(mysqli_error());
while ($row = mysqli_fetch_assoc($result)) {
echo "<option value ='" . $row['id'] . "'>" . $row['department'] . "</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td><label for = "applied_position_title">Position Title:</label></td>
<td>
<select id="position_title" applied_position_title="applied_position_title">
<option value="1"></option>
</select>
</td>
</tr>
And this is how I post to my database:
$query = "UPDATE job_application SET applied_department = '$applied_department', applied_position_title = '$applied_position_title' WHERE id = '$id'";
$result = mysqli_query($link, $query) or die(mysqli_error($link));

Add something like this to your JQuery.
// Post data to postPositionData.php when user changes form
$("#offeredjob").change(function() {
// Serialize form data
var yourFormData = $(this).serialize();
// POST
$.ajax({
type: "POST",
url: "postPositionData.php",
data: yourFormData,
success: function(msg){
// do something
}
});
});
File postPositionData.php would then do the database insert/update.

Related

Multiple ajax returns and sum values

I have a group of dropdowns with a list of players. When a player is selected, their 'Value' should appear next to the drop down and the Total should update to be the sum of all selected players values.
php code below is for two players but I have ten, will likely have ten different similar functions for each of the dropdowns
select-player.php
<!--player1-->
<tr>
<td style="width:50%;">
<select name="player1" id="player1" onchange="showvalue1()">
<option disabled selected value></option>
<?php
$sql = "SELECT * FROM players ORDER BY value DESC";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<option value='". $row['playername'] ."'>" .$row['playername'] ."</option>";
}
}
?>
</select>
</td>
<td style="width:50%;" id="value1">
</td>
</tr>
<!--player2-->
<tr>
<td style="width:50%;">
<select name="player2" id="player2" onchange="showvalue2()">
<option disabled selected value></option>
<?php
$sql = "SELECT * FROM players ORDER BY value DESC";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<option value='". $row['playername'] ."'>" .$row['playername'] ."</option>";
}
}
?>
</select>
</td>
<td style="width:50%;" id="value2">
</td>
</tr>
<tr>
<th style="width:50%";>Total</th>
<th style="width:50%;" id="total"></th>
</tr>
ajax.js
function showvalue1(){
var x = document.getElementById("player1").value;
var t = document.getElementById("total").value;
$.ajax({
url:"../showvalue.php",
method: "GET",
datatype: 'json',
data:{
id : x,
total : t
},
success:function(data){
$("#value1").html(data.price);
$("#total").html(data.newtotal);
}
})
}
function showvalue2(){
var x = document.getElementById("player2").value;
var t = document.getElementById("total").value;
$.ajax({
url:"../showvalue.php",
method: "GET",
datatype: 'json',
data:{
id : x,
total : t
},
success:function(data){
$("#value2").html(data.price);
$("#total").html(data.newtotal);
}
})
}
I've read that jsonencode is used to send arrays back that I can then assign to IDs in js.
showvalue.php
<?php
include_once 'includes/dbh.inc.php';
$pl = $_POST['id'];
$pl = trim($pl);
$total = 0;
$total = $_POST['total'];
$sql = "SELECT value FROM players WHERE playername='{$pl}'";
$result = mysqli_query($conn, $sql);
while($rows = mysqli_fetch_array($result)){
$newtotal = 0;
$value = $rows['value'];
$newtotal = $total + $value;
$ret = array('price'=>$value, 'newtotal'=>$newtotal);
echo json_encode($ret);
}
?>
Not getting any errors or console returns but also no values are being returned.
What am I missing?
Checking your HTML source, #total is a table cell:
<th id="total"></th>
And you are retrieving it using .value:
var t = document.getElementById("total").value;
But .value is for inputs, not text in a table cell, so that won't work.
To get the text, using jQuery instead of vanilla JS (since the rest of your code is jQuery):
var t = $('#total').text();

Fetch data from mysql database based on multiple dropdown selections

I am working on a project where data about therapists is stored in a database, I have 5 dropdowns on my page and I want the data to be fetched based on the dropdown values selected by the user.
<div id="dropdowns">
<form method="post">
<?php
session_start();
$username = "root";
$password = "";
$database = "align";
$mysqli = new mysqli("localhost", $username, $password, $database);
$sql = "SELECT DISTINCT `Designation` FROM `therapists`";
if($res = $mysqli->query($sql))
{
echo '<div class="select">
<select id="profession" name="profession" onchange="getSelectDesignation(this.value);">
<option selected disabled>Filter by Profession</option> ';
while ($row = $res->fetch_assoc()) {
echo "<option value='" . $row['Designation'] ."'>" . $row['Designation'] ."</option>";
}
echo ' </select>
</div>';
$res->free();
}
$ids = "SELECT DISTINCT `Identifies As` FROM `therapists`";
if($res = $mysqli->query($ids))
{
echo '<div class="select">
<select id="idas" name="idas" onchange="getSelectIdentifiesas(this.value);">
<option selected disabled>Identifies as</option> ';
while ($row = $res->fetch_assoc()) {
echo "<option value='" . $row['Identifies As'] ."'>" . $row['Identifies As'] ."</option>";
}
echo ' </select>
</div>';
$res->free();
}
$clgr = "SELECT DISTINCT `Client Group` FROM `therapists`";
if($res = $mysqli->query($clgr))
{
echo '<div class="select">
<select id="clgr" name="clgr" onchange="getSelectClientGroup(this.value);">
<option selected disabled>Client Group</option> ';
while ($row = $res->fetch_assoc()) {
echo " <option value='" . $row['Client Group'] ."'>" . $row['Client Group'] ."</option>";
}
echo ' </select>
</div>';
$res->free();
}
$istr = "SELECT DISTINCT `Issues Treated` FROM `therapists`";
if($res = $mysqli->query($istr))
{
echo '<div class="select">
<select id="istr" name="istr" onchange="getSelectIssuesTreated(this.value);">
<option selected disabled>Issues treated</option> ';
while ($row = $res->fetch_assoc()) {
echo " <option value='" . $row['Issues Treated'] ."'>" . $row['Issues Treated'] ."</option>";
}
echo ' </select>
</div>';
$res->free();
}
$lan = "SELECT DISTINCT `Languages` FROM `therapists`";
if($res = $mysqli->query($lan))
{
echo '<div class="select">
<select id="idas" name="lan" onchange="getSelectLanguages(this.value);">
<option selected disabled>Languages</option> ';
while ($row = $res->fetch_assoc()) {
echo " <option value='" . $row['Languages'] ."'>" . $row['Languages'] ."</option>";
}
echo ' </select>
</div>';
$res->free();
}
?>
</form>
</div>
Whenever a user selects a dropdown option, a specific function for each dropdown gets called which takes the value of the option selected and sends it to a different page called fetch_data which displays the information about the therapists.
function getSelectDesignation(val1)
{
$.ajax({
type: 'post',
url: 'fetch_data.php',
data: {
get_option1:val1,
},
success: function (response) {
document.getElementById("boxes").innerHTML=response;
}
});
}
function getSelectIdentifiesas(val2)
{
$.ajax({
type: 'post',
url: 'fetch_data.php',
data: {
get_option2:val2,
},
success: function (response) {
document.getElementById("boxes").innerHTML=response;
}
});
}
function getSelectClientGroup(val3)
{
$.ajax({
type: 'post',
url: 'fetch_data.php',
data: {
get_option3:val3,
},
success: function (response) {
document.getElementById("boxes").innerHTML=response;
}
});
}
function getSelectIssuesTreated(val4)
{
$.ajax({
type: 'post',
url: 'fetch_data.php',
data: {
get_option4:val4,
},
success: function (response) {
document.getElementById("boxes").innerHTML=response;
}
});
}
function getSelectLanguages(val5)
{
$.ajax({
type: 'post',
url: 'fetch_data.php',
data: {
get_option5:val5,
},
success: function (response) {
document.getElementById("boxes").innerHTML=response;
}
});
}
Below is the code in my fetch_data page :
<?PHP
session_start();
$username = "root";
$password = "";
$database = "align";
$mysqli = new mysqli("localhost", $username, $password, $database);
$state1 = $_POST['get_option1'];
$state2 = $_POST['get_option2'];
$state3 = $_POST['get_option3'];
$state4 = $_POST['get_option4'];
$state5 = $_POST['get_option5'];
$loc = $_SESSION['location'];
$find="SELECT * FROM `therapists` AS `T` inner join `personal details` as `P` ON `T`.`Therapist ID` = `P`.`Therapist ID` WHERE(`Location` LIKE '%".$loc."%' AND `Designation` LIKE '%".$state1."%' AND `Identifies As` LIKE '%".$state2."%' AND `Client Group` LIKE '%".$state3."%' AND `Languages` LIKE '%".$state5."%' AND `Issues Treated` LIKE '%".$state4."%')";
if ($result = $mysqli->query($find)) {
while ($row = $result->fetch_assoc()) {
$field1name = $row["Therapist ID"];
$field2name = $row["Name"];
$field3name = $row["Designation"];
$field4name = $row["Identifies As"];
$field5name = $row["Client Group"];
$field6name = $row["Languages"];
$field7name = $row["Issues Treated"];
$field8name = $row["Location"];
$field9name = $row["Phone Number"];
$field10name = $row["Intro"];
$field11name = $row["Instagram Link"];
$field12name = $row["Linkedin Link"];
$field13name = $row["Aasha URL"];
echo '<div id="profile-card">
<div id="info">
<div class="name-desig-img">
<div class="name-desig">
<a class="therapist-name" href="http://localhost/aasha/profile.php/'. $field2name .'">';echo $field2name;echo'</a>
<p>';echo $field3name;echo'</p>
</div>
<div class="p-img">
<img class="prof-img" src="';echo $field14name;echo'">
</div>
</div>
<div class="intro">
<p>';echo $field10name;echo'</p>
</div>
<div class="location">
<p>';echo $field8name;echo'</p><p>
</div>
</div>
<div id="links">
<div id="t-socials">
<div class="tp"><a class="t-links" href="';echo $field13name;echo'">';echo' Profile </a></div>
<div class="tli">|</div>
<div class="tli"><a class="t-links" href="';echo $field12name;echo '"><i class="fab fa-linkedin">';echo'</i></a> </div>
<div class="tli">|</div>
<div class="tli"><a class="t-links" href="';echo $field11name;echo '"><i class="fab fa-instagram-square">';echo'</i></a></div>
</div>
<p class="showphone">
<span class="clickshow" style="display: inline;"><b>Show Phone Number</b></span>
<span class="hiddenphone" style="display: none;">
<span>';echo $field9name;echo'</span>
</span>
</p>
</div>
</div>';
}
/*freeresultset*/
$result->free();
}
?>
Now the issue is whenever I select a dropdown option the value for the other dropdowns is empty and I get the undefined array key error in PHP. For example, if I select option1 which is the first dropdown, I get undefined array key error for option2, option3, option4, and option5. If I select option2 I get undefined array key error for option1, option3, option4, and option, and so on. I need to find a way to make the query work even if no option is selected in 1 or more dropdowns.
You can check if the options are set by using
isset() and if the value is not set, Just assign '' a string of length zero to those variables.
if(isset($_POST['get_option1'])){
$state1 = $_POST['get_option1'];
}else{
$state1 = '';
}
Similarly for all other variables.
First of all, only 1 request can be made in ajax at once, according to your code, the request is sent when onchange() so only 1 request will be made.
Everything looks fine but you are fetching all variables from _POST where as only 1 is sent at a time, so, you need to send all the variables at a time for your query $find="SELECT * FROM `therapists` AS `T` inner join `personal details` as `P` ON `T`.`Therapist ID` = `P`.`Therapist ID` WHERE(`Location` LIKE '%".$loc."%' AND `Designation` LIKE '%".$state1."%' AND `Identifies As` LIKE '%".$state2."%' AND `Client Group` LIKE '%".$state3."%' AND `Languages` LIKE '%".$state5."%' AND `Issues Treated` LIKE '%".$state4."%')"; to work.
Do something like this.....
<div id="dropdowns">
<form>
<!-- Your selectors here -->
<select id="idas" name="lan">
<option> ...... </option>
</select>
<select id="clgr" name="lan">
<option> ...... </option>
</select>
<select id="istr" name="lan">
<option> ...... </option>
</select>
<input type="button" onclick = "gettheValues()" value="GetIt">
</form>
</div>
Java script
function gettheValues()
{
var val1 = document.getElementById("idas").value;
var val2 = document.getElementById("clgr").value;
var val3 = document.getElementById("istr").value;
$.ajax({
type: 'post',
url: 'fetch_data.php',
data: {
get_option1:val1,
get_option2:val2,
get_option3:val3
},
success: function (response) {
document.getElementById("boxes").innerHTML=response;
}
});//Send values all together...
}
I guess nothing need to be changed in php code.
And I need to find a way to make the query work even if no option is selected in 1 or more dropdowns. what you meant by this?
If those states state1 - state5 are important for your query then it is not possible to run that query.
It is you who know the importance of the states in that query so it won't be appropriate to answer.
If you think you can query as per different selectors do like this.
<?php
if(isset($_POST['get_option1']))
{
//appropriate query here
$query = "Your query with option1";
}
if(isset($_POST['get_option2']))
{
//appropriate query here
$query = "Your query with option2";
}
...
..etc to option5
//Here your result of query with html
?>
For any queries comment below, if you need a working example I will make one.

ajax not working displaying data into text area on dropdown change in php

i am trying to display data inside using ajax in php, i have done the following code:
<table>
<select id="staff" name="staff">
<option value="#N">N</option>
<option value="#R">R</option>
<option value="#S">S</option>
<option value="#J">J</option>
<option value="#So">So</option>
<option value="#Sr">Sr</option>
<option value="#Jo">Jo</option>
<option value="#Sc">Sc</option>
<option value="#P">P</option>
</select>
<textarea id="show" rows="8" name="notice" class="form-control"></textarea>
</table>
$('#customer').change(function () {
var id = $(this).val();
$.ajax({
type: "GET",
url: "page2.php",
data: "pass_id=" + id,
success: function (data) {
alert(data);
document.getElementById("show").innerHTML = data;
}
});
});
below is my page2.php which fetches the data from database:
<?php
echo $get_id = $_GET['pass_id'];
include("db.php");
$sql = "select notice from admin where username='$get_id'";
while ($row = mysqli_fetch_array($sql)) {
echo $row['notice'];
}
?>
but this is not giving me any data in textbox area , can anyone please tell me what is wrong in my code?
You are using 'customer' instead of 'staff' please change and try
$('#staff').change(function () {
var id = $(this).val();
$.ajax({
type: "GET",
url: "page2.php",
data: "pass_id=" + id,
success: function (data) {
console.log(data);
document.getElementById("show").innerHTML = data;
}
});
});
<?php
$data = [];
$get_id = $_GET['pass_id'];
include("db.php");
$sql = "select notice from admin where username='$get_id'";
while ($row = mysqli_fetch_array($sql)) {
$data[] = $row['notice'];
}
echo json_encode($data);
?>
Use $('#staff').change(function () {
because your Id is staff not customer.
Change your id customer to staff
$('#staff').change(function () {
var id = $(this).val();
$.ajax({
type: "GET",
url: "page2.php",
data: "pass_id=" + id,
success: function (data) {
alert(data);
document.getElementById("show").innerHTML = data;
}
});
});
And also there is a mistake in your query, please try the below code.
<?php
$get_id = $_GET['pass_id'];
include("db.php");
$sql = "select notice from admin where username='$get_id'";
$result = mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($result)) {
echo $row['notice'];
}
?>
Hope it will help.

jQuery function doesn't return anything on callback

I have a jQuery function that takes the selected option of a form select element and sends it to a php file, which is supposed to return the html to populate a second select element. Unfortunately, the jQuery is firing, but the return is empty. Any ideas?
Form elements:
if ($result) {
echo '<label>*Team: <select name="team" class="team" style=\'width: 150; font-size: 16px;\' autocomplete="off" tabindex="1">';
echo '<option value="">Select</option>';
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '<option value="'.$row['TeamID'].'">'.$row['CaptainLast']." ".date('m-y',strtotime($row['ArrDate'])).'</option>';
}
echo '</select></label>';
} else {
echo "0 results";
}
?>
<label>*Team Member: <select name="member" class="member" style='width: 150; font-size: 16px;' autocomplete="off" tabindex="2">
<option value="">Select</option>
</select></label>
The jQuery:
$(document).ready(function(){
$(document).on('change','.team', function(){
var id=$(".team option:selected").val();
var dataString = 'tmid='+ id;
console.log(dataString);
$.ajax({
type: "POST",
url: "scripts/memfltpop.php",
data: dataString,
dataType: 'html',
success: function(html){
$(".member").html(html);
}
});
});
});
and the server file:
<?php
$team = $_POST['tmid'];
echo $team;
$con = mysqli_connect('**********', '****', '******', '*******');
if ($con) {
$sql = "SELECT MemberAdmin.IndID, MemberAdmin.First, MemberAdmin.Last ". "FROM MemberAdmin ". "LEFT JOIN Members ON MemberAdmin.IndID = Members.IndID ". "WHERE Members.TeamID='" .$team. "'";
$result = mysqli_query($con,$sql) or die(mysqli_error());
if ($result) {
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$id=$row['IndID'];
$data=$row['First']." ".$row['Last'];
echo '<option value="">Select</option>';
echo '<option value="'.$id.'">'.$data.'</option>';
}
} else {
echo "0 results";
}
}
else {
echo'Not connected to database';
}
For getting response in html, you need to use dataType html inside ajax request like this :
$.ajax({
type: "POST",
url: "scripts/memfltpop.php",
data: dataString,
dataType : 'html',
success: function(html){
$(".member").html(html);
}
});
Wow, found it. I never thought this would cause the SQL to freak out, but I changed from
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
to
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
As I was updating my SQL language, I missed this line. Thanks guys!

Insert record into mysql using json

I want to insert the record using json into mysql and the system could display the new record without refreshing the page.
My code is shown as below:
Part 1, the script get two values from form and convert it into json, passing them to action.php
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var name = $("#name").val();
var dataString = {'content': textcontent, 'name': name};
if (textcontent == '') {
alert("Enter some text..");
$("#content").focus();
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
dataType: 'json',
cache: true,
success: function(html){
$("#show").html(html);
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
<div>
<?php
$conn=mysqli_connect('localhost','Practical4','1234') or die('Not connected');
$database=mysqli_select_db($conn,'Practical4') or die('Database Not connected');
$id=$_GET['id'];
$query = "select * from hotel where name='$id'";
$data=mysqli_query($conn,$query);
while($rows=mysqli_fetch_array($data)){
$name=$rows['name'];
$price=$rows['price'];
$duetime=$rows['dueTime'];
$address=$rows['location'];
}
?>
<form method="post" name="form" action="">
<h3>Add Comment for <?php echo $name;?><h3>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="text" name="name" id="name" value="<?php echo $name;?>" hidden > <br>
<input type="submit" value="Add Comment" name="submit" class="submit_button"/>
</form>
</div>
<?php
$host="localhost";
$username="Practical4";
$password="1234";
$db_name="Practical4";
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select * from comment where name='$name'";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_row($result)){
$json[] = $row[1];
}
}
mysql_close($con);
echo implode('<br />', $json);
?>
<div class="space" ></div>
<div id="flash"></div>
<div id="show" ></div>
Part2, action.php, which insert the record into mysql database.
<?php
$DBServer = 'localhost'; // e.g 'localhost' or '192.168.1.100'
$DBUser = 'Practical4';
$DBPass = '1234';
$DBName = 'Practical4';
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
// check connection
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
$v1="'" . $conn->real_escape_string($_POST['content']) . "'";
$v2="'" . $conn->real_escape_string($_POST['name']) . "'";
$sql="INSERT INTO comment (content,name) VALUES ($v1,$v2)";
if($conn->query($sql) === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
$last_inserted_id = $conn->insert_id;
$affected_rows = $conn->affected_rows;
echo '<div class="showbox">'.$v1.'</div>';
}
?>
So far the code can insert new data, but it won't display the new record dynamically without refreshing page. Any idea to fix that?
Change your dataType to html since this parameter tells the server what kind of response it will accept in return:
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
dataType: 'html',
cache: true,
success: function(data){
$("#show").html(data);
$("#flash").hide();
$("#content").focus();
}
});
In the above case the return value should be plain html:
print '<div class="showbox">' . $v1 . '</div>';
You then add it to your page using:
$('#show').html(data);
If you still would like to use json you could encode your response using something like this:
print json_encode(array('html' => '<div class="showbox">' . $v1 . '</div>'));
Then you would need to parse this value:
$("#show").html(data.html);
In the above example it seems clearer to name the success functions argument to something like data since it won't contain just html in the case.

Categories