I have a js script that inserts html elements into the page everytime a button is clicked. In one of those inputs(Select) i want to show a list of options retrieved from a database. I have the correct code for this but I have no idea how to combine them because i can not place PHP into JS.
My code:
var rowCount = 0;
function add_product()
{
var $table = $('table');
var generateRow = function(indx){
$table.append('<tr>\n\
<td></td>\
<td>\
<b>Aantal: </b><input style="width: 60px;" id="aantal" name="aantal_'+indx+'" type="number" min="0" required>\
</td>\
<td>\
<b>Product: </b><select name="products_'+indx+'" type="text" required>\n\
</select>\
</td>\
</tr>');
}
generateRow(++rowCount);
}
<?php
$productQuery = mysql_query("SELECT * FROM voorraad")
while ($productInfo = mysql_fetch_array($productQuery))
{
$productID = $productInfo[0];
$product = $productInfo[1];
echo "<option value='$productID'>$product</option>";
}
?>
This is not the best method of doing what you're trying to achieve, but using the method you have started then it can be accomplished like this.
First you need to put the options string into a PHP variable
Then put that options string into a javascript variable.
This also assumes that your PHP and Javascript are all in the same document and that your PHP code is above your Javascript in the document.
<?php
$options = '';
$productQuery = mysql_query("SELECT * FROM voorraad")
while ($productInfo = mysql_fetch_array($productQuery))
{
$productID = $productInfo[0];
$product = $productInfo[1];
$options .= "<option value='$productID'>$product</option>";
}
?>
var options = "<?php echo $options; ?>";
var rowCount = 0;
function add_product()
{
var $table = $('table');
var generateRow = function(indx){
$table.append('<tr>\n\
<td></td>\
<td>\
<b>Aantal: </b><input style="width: 60px;" id="aantal" name="aantal_'+indx+'" type="number" min="0" required>\
</td>\
<td>\
<b>Product: </b><select name="products_'+indx+'" type="text" required>\n\
' + options + ' </select>\
</td>\
</tr>');
}
generateRow(++rowCount);
}
You can do it like this:
jQuery.ajax({
type: "POST",
url: 'your_functions_address.php',
dataType: 'json',
data: {functionname: 'add', arguments: [1, 2]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
yourVariable = obj.result;
}
else {
console.log(obj.error);
}
}
});
From:
How can I call PHP functions by JavaScript?
Related
I have a button that adds a row to a table so that data can be inserted. One of the <td> tags populates a dropdown menu. I need to get the value from that dropdown to post in an ajax call back to a php page to insert the data in the database. Everything I've tried has returned undefined for position_ID.
I'm getting a 500 Error on the POST and I think it's due to var position_ID = $(this).parents('tr').find('.positionList').val();, in the Insert function, not being set.
HTML Code:
<html>
<head>
<script src='jquery-3.4.1.js' type='text/javascript'></script>
<script src='script.js' type='text/javascript'></script>
</head>
<body>
<button type="button" name="add" id="add">Add</button>
<table id="dataTable">
<tr>
<th>Last Name</th>
<th>First Name</th>
<th>Location Number</th>
<th>Position</th>
</tr>
</table>
</body>
</html>
PHP Code:
<?PHP>
$sql = "SELECT positionID, name FROM position";
$result = mysqli_query($db,$sql);
$position_arr = array();
while( $row = mysqli_fetch_array($result) ){
$positionID = $row['positionID'];
$name = $row['name'];
$position_arr[] = array("positionID" => $positionID, "name" => $name);
}
// encoding array to json format
$JSON_array = json_encode($position_arr);
echo $JSON_array;
?>
<?PHP>
if(isset($_POST["last_name"], $_POST["first_name"], $_POST["location_num"], $_POST["position_ID"]))
{
$lastName = mysqli_real_escape_string($db, $_POST["last_name"]);
$firstName = mysqli_real_escape_string($db, $_POST["first_name"]);
$locationNum = mysqli_real_escape_string($db, $_POST["location_num"]);
$positionID = mysqli_real_escape_string($db, $_POST["position_ID"]);
$sqlInsertEmployee = "INSERT INTO employee(lastName, firstName, positionID, locationID) SELECT ?, ?, positionID, locationID from location join position p on p.positionID = ? where number = ?";
$stmtInsertEmployee = mysqli_prepare($db,$sqlInsertEmployee);
mysqli_stmt_bind_param($stmtInsertEmployee, "ssss", $lastName,$firstName,$positionID,$locationNum,);
mysqli_stmt_execute($stmtInsertEmployee);
mysqli_stmt_close($stmtInsertEmployee);
}
?>
Script code:
$('#add').click(function(){
var html = '<tr>';
html += '<td contenteditable id="lastName"></td>';
html += '<td contenteditable id="firstName"></td>';
html += '<td contenteditable id="locationNum"></td>';
html += '<td contenteditable id="positionID"><select class="positionList"><option></option></select>';
$(document).ready(function() {
var data
$.ajax({
dataType: 'json',
url: 'get-position.php',
data: data,
success: function(data) {
// begin accessing JSON data here
console.log(data)
//data = jQuery.parseJSON(data);
var html_to_append = '';
html_to_append += '<option value="0">-- Select One --</option>'
$.each(data, function(i, item) {
html_to_append += '<option value="' + item.positionID + '">' + item.name + '</option>';
});
$(".positionList").html(html_to_append);
},
})
})
html += '</td><td><button type="button" name="insert" id="insert">Insert</button></td>';
html += '</tr>';
$('#dataTable tr:first').after(html);
});
$(document).on('click', '#insert', function(){
var last_name = $('#lastName').text();
var first_name = $('#firstName').text();
var location_num = $('#locationNum').text();
var position_ID = $(this).parents('tr').find('.positionList').val();
console.log(position_ID);
if(first_name != '' && last_name != '' && location_num != '')
{
$.ajax({
url:"insert.php",
method:"POST",
data:{last_name:last_name, first_name:first_name, location_num:location_num, position_ID:position_ID},
success:function(data)
{
$('#alert_message').html('<div class="alert alert-success">'+data+'</div>');
$('#dataTable').DataTable().destroy();
fetch_data();
}
});
setInterval(function(){
$('#alert_message').html('');
}, 5000);
}
else
{
alert("All Fields is required");
}
});
The .val() method is used to get the value of an element.
Also note that #Kaka Sarmah is correct. Even this will not work because you're creating multiple elements with the same ID. IDs must be unique. Try giving it a class instead.
html += '<td contenteditable class="positionID"><select class="positionList"><option></option></select>';
Then in your javascript you can try to locate it using that class. Something like:
var position_ID = $(this).parents('tr').find('.positionList').val();
I was getting alert value after change function but after success function, I not getting any values
my ajax page
$(document).ready(function(){
$("#customer").change(function() {
var customer_type = $(this).find(":selected").val();
var dataString = 'customer_type='+ customer_type;
$.ajax({
url: 'http://localhost/capms_v3/ajax/getcust_type.php',
dataType: "json",
data: dataString,
cache: false,
success: function(customerData) {
alert(data);
alert("test");
if(customerData) {
var customer = [customerData];
customerData.forEach(function(item) {
var data = '<tr>';
data+= '<td colspan="4"> </td>';
data+= '<td align="right">'+item.company_id+'</td>';
data+= '<td align="right">'+item.company_name+'</td>';
data+='</tr>';
$('.appendData').append(data);
});
} else {
$("#heading").hide();
$("#records").hide();
$("#no_records").show();
}
}
});
});
});
my array values are not coming after the success function but in getcusttype page values was coming in an array
getcusttype.php
<?php
//header("Content-type:application/json");
include 'db.php';
$db=DbConnect();
if($_REQUEST['customer_type']) {
$sql = "SELECT company_id,company_name FROM ca_customer WHERE customer_type ='".$_REQUEST['customer_type']."'";
$result = mysql_query($sql) or die(mysql_error());
$data = array();
while( $rows = mysql_fetch_array($result) ) {
$data[] = $rows;
}
echo json_encode($data);
} else {
echo 0;
}?>
//var customer =[{"0":"1","company_id":"1","1":"Win Win
web","company_name":"Win Win web"},{"0":"7","company_id":"7","1":"New
Company","company_name":"New Company"},
{"0":"10","company_id":"10","1":"Murugan Super
Store","company_name":"Murugan Super Store"}];
after the success: function(customerdata) if I alert(data) values was getting alert I don't know what error I have made.
view
<select id="customer" name="customer_type" class="form-control">
<option value="">Select Customer Type</option>
<?php
foreach($all_ca_customer_type as $ca_customer_type)
{
$selected = ($ca_customer_type['customer_type_id'] == $this->input->post('customer_type')) ? ' selected="selected"' : "";
echo '<option value="'.$ca_customer_type['customer_type_id'].'" '.$selected.'>'.$ca_customer_type['customer_type_name'].'</option>';
}
?>
</select>
<tbody class="appendData">
</tbody>
not getting values after success function.if anybody face this problem help me.thanks in advance
Uncomment header("Content-type:application/json"); in getcusttype.php
It looks like your alert() function is referencing data Where does data come from? Try alert(customerData) in place of alert(data).
success: function(customerData) {
alert(data);
alert("test");
if(customerData) {
var customer = [customerData];
customerData.forEach(function(item) {
var data = '<tr>';
data+= '<td colspan="4"> </td>';
data+= '<td align="right">'+item.company_id+'</td>';
data+= '<td align="right">'+item.company_name+'</td>';
data+='</tr>';
$('.appendData').append(data);
});
} else {
$("#heading").hide();
$("#records").hide();
$("#no_records").show();
}
}
If you're looking to alert the row that your appending you should move the alert(data) call, as is, down into your forEach() block after you declare your data variable.
Ex:
customerData.forEach(function(item) {
var data = '<tr>';
data+= '<td colspan="4"> </td>';
data+= '<td align="right">'+item.company_id+'</td>';
data+= '<td align="right">'+item.company_name+'</td>';
data+='</tr>';
alert(data);
$('.appendData').append(data);
});
So i wanted to make a little "search engine" for my database.
my javascript is:
$(document).ready(function () {
$("#display").click(function () {
var zoeknaam = $("#zoeknaam").val();
var zoektype = $("#zoektype").text();
$.ajax({ //create an ajax request to load_page.php
type: "POST",
url: "display.php",
data: { name: zoeknaam, zoekt: "name" },
dataType: "html", //expect html to be returned
success: function (response) {
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
my html is the following:
<input type="text" name="inputtext" id="zoeknaam" />
<select name="searchtype" id="zoektype"><option value="name">name</option><option value="age">age</option></select>
<input type="button" id="display" value="Display All Data" />
and now i have my php
include("connection.php");
$dataget = $_POST["name"];
$datawaar = $_POST["zoekt"];
$stmt = $conn->prepare("SELECT * FROM student WHERE :waar=:postname");
$stmt->bindParam(':waar', $datawaar, PDO::PARAM_STR);
$stmt->bindParam(':postname', $dataget, PDO::PARAM_STR);
$stmt->execute();
echo "<table>";
while($data = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo "<tr>";
echo "<td align=center>$data[name]</td>";
echo "<td align=center>$data[address]</td>";
echo "<td align=center>$data[age]</td>";
echo "</tr>";
}
echo "</table>";
When i remove the where condition and set the condition to name it works. Now when i retrieve it with the post and param it doesn't work.
The connection.php is correct since it works with the condition.
This is wrong:
... WHERE :waar=:postname
You can only bind values using placeholders in a prepared statement, not column- or table names.
If you want to accept and use client-provided column- or table names, the only way to secure that, is to check them against a white-list and then inject them directly in the query string.
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.
Here's my code :-
<script>
$(document).ready(function(){ //#This script uses jquery and ajax it is used to set the values in
$("#day").change(function(){ //# the time field whenever a day is selected.
var day=$("#day").val();
var doctor=$("#doctor").val();
$.ajax({
type:"post",
url:"time.php",
data:"day="+day+"&doctor="+doctor,
dataType : 'json',
success:function(data){
var option = '';
$.each(data.d, function(index, value) {
option += '<option>' + value.res + '</option>';
});
$('#timing').html(option);
}
});
});
});
</script>
And here's the php script.
<?
$con=mysqli_connect("localhost","clinic","myclinic","myclinic");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$doctor = $_POST['doctor'];
$day = $_POST['day'];
$query="SELECT * FROM schedule WHERE doctor='" .$doctor."'AND day='" .$day. "'";
$result = mysqli_query($con, $query);
$i = 0; //Initialize the variable which passes over the array key values
$row = mysqli_fetch_assoc($result); //Fetches an associative array of the row
$index = array_keys($row); // Fetches an array of keys for the row.
while($row[$index[$i]] != NULL)
{
if($row[$index[$i]] == 1) {
$res = $index[$i];
echo json_encode($res);
}
$i++;
}
?>
I want options with time values inserted inside a select on my html page which looks something like this :-
<select id="timing" name="timing"></select>
My java script code is posting values to the php script alright but the code is still not working. There aren't any errors in my javascript as I see it. Kindly help me out
var postUrl = "time.php";
$.ajax({
type: "POST",
url: postUrl,
data: {day: day,doctor: doctor},
dataType: "json",
success: function (data) {
$.each(data, function (key, value) {
$('#timing').append('<option value="' + key + '">' + value + '</option>');
});
}
});
hope it's help to you
success:function(data){
var select= '<select>';
var option = '';
$.each(data.d, function(index, value) {
option += '<option>' + value.res + '</option>';
});
select = select+option'</select>';
$('#timing').html(select);
}
HTML :
<div id="timing"> </div>
var day=$("#day option:selected").val();
var doctor=$("#doctor option:selected").val();
data:"{day:'"+day+"', doctor: '" + doctor + "'}" ,