Passing JavaScript variable to PHP on dropdown change - javascript

I am trying to change text in a div depending on value change on a dropdown box. The dropdown box values are populated from MySQL using PHP. I am loading the dropdown box on page load.
<script>
$(document).ready(function() {
$('#products').change(function(){
var idval=$('#products').val();
$.ajax
( {
type: "post",
url: "my.php",
data: {winner_id:idval},
success: function(response)
{ alert("The winner was passed!")},
}
);
<?php
require_once 'config.php';
$iid=$_GET['winner_id'];
$sql="SELECT * FROM Products where prod_id = ".$iid;
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$prodCredit="Credit :".$row["prod_price"];
$time="estmated time is :".$row["prod_time"];
?>
$('#esdTime').text(' <?php echo $prodCredit ?> ' );
$('#credit').text(' <?php echo $time ?> ' );
});
});
</script>
I am not getting results.
Let me know how can I assign JavaScript value idval to PHP variable $iid value.

//you would want a the php script to be in a separate file that you could call Have the php file return an array or json object. Have the callback success function append the new options to the html select. The following is a ruffexample
<script>
$(document).ready(function() {
$('#products').change(function(){
var idval=$('#products').val();
$.ajax
( {
type: "post",
url: "my.php",
data: {winner_id:idval},
success: function(response){
for (var i = 0; i < response.length; i++) {
$("#idofyourselect").append("<option val='" +response[i]+"'>" + response[i] + "</option>");
}
},
}
);
</script>

Related

Refresh page if there is change in database

I am trying to refresh my a page if there is a change in orderStatus from database using Ajax and PHP. I set the current orderStatus as predefined data and then use Ajax to get the current orderStatus from database and finally compare if they are not the same. I want to refresh the page if they are not the same.
PHP (autorefresh.php)
<?php
$orderId = $_POST["orderId"];
$query = "SELECT * FROM orderinhomeonlinecall WHERE orderId='$orderId'";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result))
{
$orderStatus = $row['orderStatus'];
$data = array(
'orderStatus' => $orderStatus
);
echo json_encode($data);
}
?>
Javascript
<script type="text/javascript" >
var predefined_val = '<?php echo $orderStatus; ?>';// your predefined value.
$.document(ready(function(){
setInterval(function(){
$.ajax({
type:"POST",
url:"autorefresh.php", //put relative url here, script which will return php
data:{orderId: <?php echo $orderId; ?>}, // if any you would like to post any data
success:function(response){
var data = response; // response data from your php script
if(predefined_val !== data){
window.location.href=window.location.href;
}
}
});
},5000);// function will run every 5 seconds
}));
The below code should work, Need to mention dataType:"json" else use JSON.stringify(data) to parse response
<script type="text/javascript">
var predefined_val = '<?php echo $orderStatus; ?>';// your predefined value.
$(document).ready(function () {
setInterval(function () {
$.ajax({
type: "POST",
url: "autorefresh.php", //put relative url here, script which will return php
data: {orderId: <?php echo $orderId; ?>}, // if any you would like to post any data
dataType: "json",
success: function (response) {
var data = response; // response data from your php script
if (predefined_val !== data.orderStatus) {
window.location.href = window.location.href;
}
}
});
}, 5000);// function will run every 5 seconds
});
</script>
I have tested this by creating two files(autorefresh.php,index.php) and test db with table and it is working for me. I think the below code would be helpful, If not please share you code, i will check and fix it.
autorefresh.php
// Create connection
$db = new mysqli("localhost", "root", "","test");
$orderId = $_POST["orderId"];
$query = "SELECT * FROM orderinhomeonlinecall WHERE orderId='$orderId'";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result))
{
$orderStatus = $row['orderStatus'];
$data = array(
'orderStatus' => $orderStatus
);
echo json_encode($data);
}
?>
index.php
<?php
$orderStatus ='pending';
$orderId =1;
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
var predefined_val = '<?php echo $orderStatus; ?>';// your predefined value.
$(document).ready(function () {
setInterval(function () {
$.ajax({
type: "POST",
url: "autorefresh.php", //put relative url here, script which will return php
data: {orderId: <?php echo $orderId; ?>}, // if any you would like to post any data
dataType: "json",
success: function (response) {
var data = response; // response data from your php script
if (predefined_val !== data.orderStatus) {
window.location.href = window.location.href;
}
}
});
}, 5000);// function will run every 5 seconds
});
</script>

Ajax call to php, get mysql data as array and use in JS function

I'm looking to make an ajax call to a PHP script to get data from MySQL, create a json array and pass it back to the success function of the ajax call, where i will then use it as parameters for a JavaScript function.
This is my ajax call,
$('button[name="message"]').click(function() {
var $row = $(this).closest("tr"); // Find the row
var $tenant_id = $row.find(".col-md-1 id").text(); // Find the tenants ID
var $landlord_id = "<?php echo $id; ?>"
$.ajax({
url : "./message.php",
type : "POST",
async : false,
data: {
landlord_id: $landlord_id,
tenant_id : $tenant_id
},
success: function(data){
console.log(data);
var messages = data;
insertChat(messages.sender_id, messages.body, messages.timestamp);
}
})
});
And this is my PHP file,
<?php
session_start();
require_once('../dbconnect.php');
// update tenants table to show deposit returned
if(isset($_POST['tenant_id'])){
$tenant_id = $_POST['tenant_id'];
$landlord_id = $_POST['landlord_id'];
$sql = "SELECT * from messages WHERE messages.sender_id OR messages.receiver_id = '$tenant_id' AND messages.sender_id OR messages.receiver_id = '$landlord_id'";
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));
//create an array
$messages = array();
while($row =mysqli_fetch_assoc($result))
{
$messages[] = $row;
}
echo json_encode($messages);
}
?>
If anybody has a link to a tutorial or the individual parts that would be fantastic. I don't even know if the process i have outlined above is correct.
If anybody could tell me the correct way to go about this that would be of great help!
Thanks
Just a few things to adjust your javascript side (I won't explain the php sql injection issue you have... but please research prepare, bind_param and execute):
Since you are returning an ARRAY of $messages from php (json_encoded), you need to loop on those in your success handler.
Add dataType: 'JSON' to your options, so it explicitly expects json returned from php.
And you were missing a couple semicolons ;)
Adjustments added to your code:
$('button[name="message"]').click(function() {
var $row = $(this).closest("tr");
var tenant_id = $row.find(".col-md-1 id").text();
var landlord_id = "<?php echo $id; ?>";
$.ajax({
url : "./message.php",
type : "POST",
data: {
landlord_id: landlord_id,
tenant_id : tenant_id
},
dataType: 'JSON',
success: function(data){
console.log(data);
if (typeof data !== undefined) {
for(var i = 0; i < data.length; i++) {
insertChat(data[i].sender_id, data[i].body, data[i].timestamp);
}
}
}
});
});

AJAX change a div value on click inside PHP loop

I'm looking to change the content of a div based on a link being clicked on a php page. The link is created through a loop and I need to pass several parameters through the URL. The div is also created through the loop so the id of the div will be variable. I'm having trouble with the AJAX to make this happen.
Below is my php:
<?php
if ($result3->num_rows > 0) {
while($row3 = $result3->fetch_assoc()) {
$tripDestination = $row3["tripDestination"];
$sessionID = $row3["$sessionID"];
$price = $row3["price"];
echo "" . $tripDestination . ' - ' . $price . "";
echo "<br />";
echo "<div id=\"trips\"></div>";
}
}
?>
I need to pass two variables in the URL: sessionID and tripDestination. I was able to load static content, but it needs to be dynamic. Here's my AJAX so far
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url: "sqlUpload.php?sessionID=35&tripDestination=SFO", success: function(result){
$("#div1").html(result);
}});
});
});
</script>
Thanks in advance!
I might think about sending the information from a data attribute on the link:
PHP:
<?php
if ($result3->num_rows > 0) {
while($row3 = $result3->fetch_assoc()) {
$tripDestination = $row3["tripDestination"];
$sessionID = $row3[$sessionID];
$price = $row3["price"];
// Store the organized data
$data = array(
'tripDestination'=>$tripDestination,
'sessionID'=>$sessionID,
'price'=>$price
);
?>
<!-- You can store the array into json on the data attribute -->
<a href="#" class="data-set" data-information='<?php echo json_encode($data) ?>'><?php echo $tripDestination.' - '.$price ?></a>
<br />
<div class="data-response"></div>
<?php
}
}
?>
JavaScript:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// When user clicks the <a> that has the "data-set" class
$('.data-set').on('click',function(e){
// I like to prevent default here, just incase
e.preventDefault();
// Assign current obj
var getObj = $(this);
// Fetch the json from the attribute
var getData = getObj.data('information');
// Send
$.ajax({
// Just send to the page, no query string
url: "sqlUpload.php",
// I would send POST, personally
type: 'GET',
// This is the data being sent
data: getData,
success: function(response){
// Presumably you want to put the response into the
// accompanying div, then you can just do next()
getObj.next('.data-response').html(response);
}});
});
});
</script>

Check the input quantity is greater than the available quantity in database

What I want to do is checking whether the text box input quantity is greater than the available quantity in database. Alert should be displayed onclick() of the ADD button.
ADD button
<button type="button" name="btnSave" id="btnSave" onclick="submitdata(); resetform(); checkQty();">ADD</button>
checkQty() function
function checkQty() {
//Grab current forms input field values.
var txtQuantity = document.getElementById("txtQuantity").value;
var listItemName = document.getElementById("listItemName").value;
//Connect to database and verify Quantity Ordered isnt greater than Quantity In Stock.
$.ajax({
type: "POST",
url: "/pms/includes/functions/qty_check.php",
data: 'listItemName=' + listItemName + '&txtQuantity=' + txtQuantity,
}).responseText;
}
qty_check.php
<?php
error_reporting(E_ALL );
ini_set('display_errors', 1);
//Start the Session
if(!isset($_SESSION))
{
session_start();
}
include_once("../../config.php");
require __DIR__."../../dbutil.php";
if(!empty($_POST['txtQuantity'])){$qty = $_POST['txtQuantity'];}
if(!empty($_POST['listItemName'])){$item = $_POST['listItemName'];}
$results = mysqli_query($connection, "SELECT * FROM purchase_items WHERE item_id= ".$_GET['listItemName']"");
$row = mysqli_fetch_assoc($results);
{
$tb_qty=$row["avail_qty"];
}
if($tb_qty < $qty){ ?>
<script type="text/javascript">
alert("Quantity exceeds the stock limit");
</script>
<?php
}
?>
I tried a lot, but I couldn't fix this. Appreciate any help.
You should not print out html directly from an ajax call. You should echo out some json that you can parse on the front end to get the information. using
echo json_encode(['key' => 'value'])
here is your code, with a little modification. I added a dataType to the ajax query and a done function that is called when the ajax request has finished.
function checkQty() {
//Grab current forms input field values.
var txtQuantity = document.getElementById("txtQuantity").value;
var listItemName = document.getElementById("listItemName").value;
//Connect to database and verify Quantity Ordered isnt greater than Quantity In Stock.
$.ajax({
type: "POST",
url: "/pms/includes/functions/qty_check.php",
dataType: 'json',
data: {
listItemName: listItemName,
txtQuantity: txtQuantity
}
}).done(function(response){
alert('check your console!')
console.log('this is the response', response.available);
})
}
qty_check.php
<?php
error_reporting(E_ALL );
ini_set('display_errors', 1);
//Start the Session
if(!isset($_SESSION))
{
session_start();
}
include_once("../../config.php");
require __DIR__."../../dbutil.php";
if(!empty($_POST['txtQuantity'])){$qty = $_POST['txtQuantity'];}
if(!empty($_POST['listItemName'])){$item = $_POST['listItemName'];}
$results = mysqli_query($connection, "SELECT * FROM purchase_items WHERE item_id= ".$_GET['listItemName']"");
$row = mysqli_fetch_assoc($results);
{
$tb_qty=$row["avail_qty"];
}
// echo out some json to send to the front end
echo json_encode(['available' => $tb_qty < $qty]);
?>

Set input fields value attribute from MYSQL database when selecting data from dropdown list

I'm trying send select query and set the result as value attribute for different input fields, the query should be sent upon selecting a value from dropdown list. After doing some researches I found this can be reached through jQuery.
jQuery will send request to php file which contains my query and fetch result and then return values in json format. At this point everything is working great, my php file is working and return valid json data but I cannot get these data append in the input fields I have. Here is my script that should run the php file and return the results in json then append results in text fields.
Check my code on fiddle
<script>
var flight_destination = $('#destination).text();
var flight_departure = $('#departure).text();
var flight_arrival = $('#arrival).text();
$('#flight_number').on('change', function() {
var flight_info = $('#flight_number :selected').text();
$.ajax({
url: "getFlightData.php",
type: "get",
data: '?flight_number=$flight_number',
success: function(data){
var flight_destination = data[1];
var flight_departure = data[2];
var flight_arrival = data[3];
}
}
$('#destination').val(flight_destination);
$('#departure').val(flight_departure);
$('#arrival').val(flight_arrival);
})
</script>
getFlightData.php
<?php
include "dbConnect.php";
$flight_number = $_GET['flight_number'];
$query = mysql_query("SELECT * FROM flights WHERE flight_number='$flight_number'");
$data = array();
while($row = mysql_fetch_array($query))
{
$row_data = array(
'flight_number' => $row['flight_number'],
'destination' => $row['destination'],
'departure' => $row['departure'],
'arrival' => $row['arrival']
);
array_push($data, $row_data);
}
echo json_encode($data);
?>
GOOD NEWS
A friends of mine helped me out with a syntax error in data: line. I did change it from data:'flight_number='+$('#flight_number').val(), to data:{'flight_number':$('#flight_number').val()},
In browser console window the json objects returned perfectly on change the drop down list value but still cannot append these objects to the input fields as value attribute
Update 2
Now I have this Still the data returned in the browser's console window perfectly, but the only what appended in the first text field is [object]
of the browser after selecting option from drop down list
Update 3
With great help and effort from #satyrwilder I'm now able to retrieve the first text field value. This is working version of the script snippet
$(function(){
var flight_destination = $('#destination');
var flight_departure = $('#departure');
var flight_arrival = $('#arrival');
var flight_number = $('#flight_number');
$('#flight_number').on('change', function() {
var flight_info = $('#flight_number :selected').text();
$.ajax({
url: "getFlightData.php",
type: "get",
dataType: "json",
data: { 'flight_number' : flight_number.val() }
})
.done(function(data) {
$("#destination").val(data[0].destination);
$("#departure").text(data[0].departure).val(data[0].departure);
$("#arrival").text(data[0].arrival).val(data[0].arrival);
});
});
});
I'm now looking forward to append the datetime-local values as well. I will keep this question updated regularly until it's 100% compelted
you must declare what type of data going to receive your inquiry.
 
dataType: "json"
$.ajax({
url: "getFlightData.php",
type: "get",
data: '?flight_number=$flight_number',
success: function(data){ ... },
dataType: "json", //<--------- this
});
Documentation of $.ajax()
And header from json in the start of you code php
For JSON:
header('Content-Type: application/json');
For JSON-P:
header('Content-Type: application/javascript');
Finally I came to the final working code where everything is working perfectly. First I'd like to thank #satyrwilder for correcting my javascript part.
Here is the final code, which appends values from database into text and datatime-local fields using jquery + php
getFlightDate.php
<?php
header('Content-Type: application/json');
include "dbConnect.php";
function datetime()
{
return date( 'Y-m-d\TH:i:s', time());
}
$flight_number = $_GET['flight_number'];
$query = mysql_query("SELECT * FROM flights WHERE flight_number='$flight_number'");
$data = array();
while($row = mysql_fetch_array($query))
{
$row_data = array(
'flight_number' => $row['flight_number'],
'destination' => $row['destination'],
'departure' => datetime($row['departure']),
'arrival' => datetime($row['arrival'])
);
array_push($data, $row_data);
}
echo json_encode($data);
?>
print.php
<?php
include "dbConnect.php";
$flight_numbers = mysql_query("SELECT flight_number FROM flights");
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<title>Test</title>
</head>
<body>
<select id="flight_number">
<?php while($row = mysql_fetch_array($flight_numbers))
{
Print "<option>".$row['flight_number'] . "</option> ";
}
?>
</select>
<br>
<input type="text" id="destination">
<input type="datetime-local" id="departure" />
<input type="datetime-local" id="arrival" />
<script>
$(function(){
var flight_destination = $('#destination');
var flight_departure = $('#departure');
var flight_arrival = $('#arrival');
var flight_number = $('#flight_number');
$('#flight_number').on('change', function() {
var flight_info = $('#flight_number :selected').text();
$.ajax({
url: "getFlightData.php",
type: "get",
dataType: "json",
data: { 'flight_number' : flight_number.val() }
})
.done(function(data) {
$("#destination").val(data[0].destination);
$("#departure").text(data[0].departure).val(data[0].departure);
$("#arrival").text(data[0].arrival).val(data[0].arrival);
});
});
});
</script>
</body>
</html>
The trick was to change the datetime format before json_encode, because datetime-local input fields shows values in specific format which is 2014-12-05T08:30:59 -> Y-m-d\TH:i:s

Categories