Ajax request with PHP in ASP.NET - javascript

I am trying to connect with my database and get some data with Ajax and PHP. I have created a Web App in ASP.NET, i am using Azure Data Studio for database. I do not know how to execute all of this. How can i run the php script, how can i get data from database without reloading the page on changing value in a dropdown.
My connection string is:
"ConnectionStrings": {"ConnectionString":"Server=(localdb)\\mssqllocaldb;Database=DatabaseName; Trusted_Connection=True;"}
My HTML Code is:
<form action="">
<select name="customers" onchange="showValue(this.value)">
<option value="">Select a customer:</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</form>
<br>
<div id="txt">Here is info..</div>
My Ajax request, function in JS:
function showValue(str) {
var xhttp;
if (str == "") {
document.getElementById("txt").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txt").innerHTML = this.responseText;
}
};
xhttp.open("GET", "getValue.php?q="+str, true);
xhttp.send();
}
And finally my PHP script:
<?php
$servername = "(localdb)\mssqllocaldb";
$username = "";
$password = "";
$dbname = "DatabaseName";
$mysqli = new mysqli($servername,$username,$password,$dbname);
if($mysqli->connect_error) {
exit('Could not connect');
}
$sql = "SELECT Id, Name, Number
FROM Table1 WHERE Id = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $_GET['q']);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id, $name, $number);
$stmt->fetch();
$stmt->close();
echo "<table>";
echo "<tr>";
echo "<th>ID</th>";
echo "<td>" . $id . "</td>";
echo "<th>Name</th>";
echo "<td>" . $name . "</td>";
echo "<th>Number</th>";
echo "<td>" . $number . "</td>";
echo "</tr>";
echo "</table>";
?>

Related

pass data from javascript to php via ajax, select a myslq table dynamically and retrieve the data of the query in javascript

i am stuck with ajax and php, i would like to pass information to a php file that communicate with mysql and retrieve data in a variables.
For the moment i managed to pass data via javascript to php, i can't to do the opposite.
Here is the code
HTML CODE
<form action="">
<select name="misura" onchange="show(this.value)">
<option value="">scegli la misura</option>
<option value="1">1</option>
<option value="2">2</option>
-->
<option value="husqvarna_272xp_catena_nuova_operatore_1">husqvarna_272xp_catena_nuova_operatore_1</option>
<option value="husqvarna_550xp_catena_usata_operatore_2">husqvarna_550xp_catena_usata_operatore_2</option>
<option value="husqvarna_550xp_catena_usata_operatore_1">husqvarna_550xp_catena_usata_operatore_1</option>
<option value="husqvarna_550xp_catena_nuova_operatore_2">husqvarna_550xp_catena_nuova_operatore_2</option>
<option value="husqvarna_550xp_catena_nuova_operatore_1">husqvarna_550xp_catena_nuova_operatore_1</option>
</select>
</form>
</form>
JAVASCRIPT/AJAX
function show(str){
var xhttp;
if(str == "") {
document.getElementById("txtHint").innerHTML ="";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200){
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xhttp.open("GET","database_web.php?q="+str, true);
xhttp.send();
}
PHP CODE IN THE FILE DATABASE.PHP
<?php
$q = intval($_GET['q']);
$con=mysqli_connect("localhost","USER","PASS","DB");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform queries
$dati="SELECT * FROM ".$_GET['q']."";
$result = mysqli_query($con,$dati);
echo "<table>
<tr>
<th>Frequenza</th>
<th>dati_X</th>
<th>dati_Y</th>
<th>dati_z</th>
</tr>";
while($row=mysqli_fetch_array($result,MYSQLI_NUM)) {
echo "<tr>";
echo "<td>" . round($row[0],2) . "</td>";
echo "<td>" . round($row[1],2) . "</td>";
echo "<td>" . round($row[2],2) . "</td>";
echo "<td>" . round($row[3],2) . "</td>";
$prova = $row;
$xData[] = $row[0];
}
mysqli_close($con);
Convert to json in the file database.php
<script type="text/javascript">
// pass PHP variable declared above to JavaScript variable
// operatore 1 antivibrante
// misura 1 exp
var assex =
<?php echo json_encode($xData) ;?>;
console.log(assex);
</script>
In the console.log i can't view nothing and i can't understand why.
My objective are to retrieve data from sql interrogation and create a graph dynamically with the data.
I made a page for testing in this address
http://www.rdgdesign.it/elaboration/ajax_web.php
Thanks for all !

How to get the selected value from dropdown and use it in query without clicking submit?

I'm making a chart that will show its result based from the year that was selected from the dropdown. Is it possible to get the variable from the dropdown and use it in query without clicking submit button? I tried this code but didn't work out:
<?php
require '../includes/dbheader.php';
$query = "SELECT DISTINCT DATE_FORMAT(orderdate, '%Y') AS year
FROM prodsoldmonthly
";
$result = mysqli_query($conn, $query);
echo "<select id='selectyear[]' name='selectyear' class='cd-select filter-input'>";
echo "<option class='dropdown' value='' selected>Choose Year</option>";
while($row = mysqli_fetch_assoc($result)) {
echo "<option class='dropdown' value='{$row['year']}'>".htmlspecialchars($row["year"])."</option>";
}
echo "</select>";
?>
<script>
$yearselected = $("#selectyear option:selected").text();
</script>
<!-- Products Sold per Category -- YEAR -->
<?php
include('../includes/dbheader.php');
$query = "SELECT categoryName, qty, DATE_FORMAT(orderdate, '%Y') AS year
FROM prodsoldmonthly WHERE year = '$yearselected'
";
$result = mysqli_query($conn, $query);
?>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart()
{
var data = google.visualization.arrayToDataTable([
['categoryName', 'qty'],
<?php
while($row = mysqli_fetch_array($result))
{
echo "['".$row["categoryName"]."', ".$row["qty"]."],";
}
?>
]);
var options = {
title: 'Products Sold Per Category by Year',
is3D:true,
pieHole: 0.4
};
var chart = new google.visualization.PieChart(document.getElementById('piechartyear'));
chart.draw(data, options);
}
</script>
You can use AJAX to launch the request with the year without having to submit the whole page:
function queryProducts(yearselected) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// this line will be called when the query finishes successfully
document.getElementById("products").innerHTML = this.responseText;
}
};
// set url with parameter
xmlhttp.open("GET", "products.php?yearselected=" + selectedyear, true);
xmlhttp.send();
}
Add an 'onchange' listener to your select to call the function while passing the selected year:
<select id='selectyear[]' name='selectyear' onchange="queryProducts(this.value)" class='cd-select filter-input'>";
Lastly, add a placeholder to display the result of the query:
<div id="products"></div>
EDIT:
For your select statement, put the code in another page like products.php for example and call that page in the AJAX function:
<?php
// products.php
include('../includes/dbheader.php');
// get url parameter
$yearselected = intval($_GET['yearselected']);
$query = "SELECT categoryName, qty, DATE_FORMAT(orderdate, '%Y') AS year
FROM prodsoldmonthly WHERE year = '".$yearselected."'";
$result = mysqli_query($conn, $query);
echo "<table>
<tr>
<th>Category</th>
<th>Qty</th>
<th>Order date</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['categoryName'] . "</td>";
echo "<td>" . $row['qty'] . "</td>";
echo "<td>" . $row['orderdate'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($conn);
?>

How to get variables from js and use them in php

Hi all i was making a website were you can add excel file and choose a person and when you choose a person then it the web would only print those rows were only is a person that you chosen from select box.
Does anyone know how i could get result variable from js function (function getSelectedPerson()) and that resul insert in php for statement.
<script>
var filling_prices= new Array();
filling_prices["None"]=0;
filling_prices["dla_dei_mat"]="Deividas Matulis";
filling_prices["dla_tom_ver"]="Tomas Veršinskas";
filling_prices["dla_dar_ser"]="Darius Sereika";
filling_prices["dla_dov_pra"]="Dovydas Prakapas";
function getSelectedPerson()
{
var theForm = document.forms["dla_darbuotojo_pasirinkimas_form"];
var selectedPerson = theForm.elements["dla_darbuotojo_pasirinkimas"];
fillSelectedPerson=filling_prices[selectedPerson.value];
return fillSelectedPerson;
}
</script>
<?php
require_once "Classes/PHPExcel.php";
$chosenPerson = $_GET["getSelectedPerson()"];
$tmpfname = "visi.xls";
$excelReader = PHPExcel_IOFactory::createReaderForFile($tmpfname);
$excelObj = $excelReader->load($tmpfname);
$worksheet = $excelObj->getSheet(0);
$lastRow = $worksheet->getHighestRow();
echo "<table>";
for ($row = 1; $row <= $lastRow; $row++) {
if ($chosenPerson == ($worksheet->getCell('D'.$row)->getValue()) ) {
echo "<tr><td>";
echo $worksheet->getCell('D'.$row)->getValue();
echo "</td><td>";
echo $worksheet->getCell('F'.$row)->getValue();
echo "</td><td>";
echo $worksheet->getCell('G'.$row)->getValue();
echo "</td><tr>";
}
}
echo "</table>";
?>
<form name="dla_darbuotojo_pasirinkimas_form">
<div class="Choose_people">
<select name="dla_darbuotojo_pasirinkimas">
<option value="None">Darbuotojai</option>
<option value="dla_dei_mat">Deividas Matulis</option>
<option value="dla_tom_ver">Tomas Versinskas</option>
<option value="dla_dar_ser">Darius Sereika</option>
<option value="dla_dov_pra">Dovydas Prakapas</option>
</select>
</div>
</form>
I think this is what you are looking for. You can not use Javascript variables in PHP, you have to pass the values via GET or POST requests. You don't need the script portion of your example.
<form name="dla_darbuotojo_pasirinkimas_form" action="yourscript.php" method="get">
<div class="Choose_people">
<select name="dla_darbuotojo_pasirinkimas" onchange="this.form.submit()>
<option value="None">Darbuotojai</option>
<option value="dla_dei_mat">Deividas Matulis</option>
<option value="dla_tom_ver">Tomas Versinskas</option>
<option value="dla_dar_ser">Darius Sereika</option>
<option value="dla_dov_pra">Dovydas Prakapas</option>
</select>
</div>
</form>
Change
$chosenPerson = $_GET["getSelectedPerson()"];
to
$chosenPerson = $_GET["dla_darbuotojo_pasirinkimas"];
You may also need a condition in your PHP script
if(isset($_GET["dla_darbuotojo_pasirinkimas"])) {
// do the get person stuff
$chosenPerson = $_GET["getSelectedPerson()"];
$tmpfname = "visi.xls";
$excelReader = PHPExcel_IOFactory::createReaderForFile($tmpfname);
$excelObj = $excelReader->load($tmpfname);
$worksheet = $excelObj->getSheet(0);
$lastRow = $worksheet->getHighestRow();
echo "<table>";
for ($row = 1; $row <= $lastRow; $row++) {
if ($chosenPerson == ($worksheet->getCell('D'.$row)->getValue()) ) {
echo "<tr><td>";
echo $worksheet->getCell('D'.$row)->getValue();
echo "</td><td>";
echo $worksheet->getCell('F'.$row)->getValue();
echo "</td><td>";
echo $worksheet->getCell('G'.$row)->getValue();
echo "</td><tr>";
}
}
echo "</table>";
}
So if the script has been called with no person it won't try to run that code.

AJAX request displaying content to user but not on the source of the page

On the body of the document, lets call it "form.php" we have the following:
On the head we have a JavaScript code:
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
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("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "getchauffeur.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
We query to database and populate a dropdown. We switch content using (showUser):
<div>
<?
$result = $mysqli -> query("select id, nomchauffeur from chauffeurs");
echo "<select name='id' onchange='showUser(this.value)'>";
while ($row = $result -> fetch_assoc()) {
unset($id, $name);
$id = $row['id'];
$name = $row['nomchauffeur'];
echo '<option value="'.$id.
'">'.$name.
'</option>';
}
?>
Here we are still in body. We put the content of AJAX into div.
<div id="txtHint"><b>chauffeur info will be listed here...</b> </div>
</div>
Here is our script that populate form fields with the content of AJAX request:
<script>
var table = document.getElementById('table');
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
//rIndex = this.rowIndex;
document.getElementById("nomchauffeur").value = this.cells[0].innerHTML;
document.getElementById("prenomchauffeur").value = this.cells[1].innerHTML;
document.getElementById("agechauffeur").value = this.cells[2].innerHTML;
document.getElementById("cinchauffeur").value = this.cells[3].innerHTML;
};
}
</script>
Now here is our getchauffeur.php:
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','','nouveau');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax");
$sql="SELECT * FROM chauffeurs WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>nom</th>
<th>prenom</th>
<th>age</th>
<th>adresse</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['nomchauffeur'] . "</td>";
echo "<td>" . $row['prenomchauffeur'] . "</td>";
echo "<td>" . $row['agechauffeur'] . "</td>";
echo "<td>" . $row['adressechauffeur'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
The Problem: Everything works fine if the table is on the same page. But here the AJAX request constraints us to put the table in other php page(chauffeur.php).
What we need is populating the form fields automatically by clicking on the row displayed from dropdown Change actions. It appears that the row inserted into table inside 'chauffeur.php' is not printed on the html DOM. When we click on page view source, it displays only:
<div id="txtHint"><b>chauffeur info will be listed here...</b> </div>
And not the content of the following fields:
nomchauffeur prenomchauffeur agechauffeur adressechauffeur
How could we grab the content of row and fill automatically the form and where is it?
This whole javascript AJAX should be after your HTML div #txtHint.
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
Also you can return only row instead of whole table. On main page create table as id 'txtHint' and insert that row in response.

PHP & AJAX not returning values within form element

I'm trying to use AJAX and PHP to update the options of a drop down menu based on the previous selection from another drop down menu.
I have this script in the head of my document:
<script>
function show_districts(str)
{
if (str.length==0)
{
document.getElementById("districts_dropdown").innerHTML="";
return;
}
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 (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("districts_dropdown").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","get_districts.php?q="+str,true);
xmlhttp.send();
}
</script>
... which, when onchange() is triggered, passes the value of this drop down:
<label for="banner" class="medium">Banner</label>
<select name="banner" id="banner" class="textbox short_field" onchange="show_districts(this.value)">
<option value=""></option>
<?php
$result = mysql_query("SELECT name FROM banners", $connection);
if (!result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row["name"] . '"';
if($row["name"] == $banner) { echo 'selected';} ;
echo '>' . $row["name"] . '</option>';
}
?>
</select>
... to this php file:
<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php
$q = $_REQUEST['q'];
if($q = 'TBOOTH') {$id = 2;}
$result = mysql_query("SELECT dist.name FROM districts AS dist JOIN int_bd AS ibd ON dist.id = ibd.districts_id WHERE banners_id = '".$id."' GROUP BY dist.id ORDER BY dist.id ASC", $connection);
if (!result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row["name"] . '"';
if($row["name"] == $district) { echo ' selected';} ;
echo '>' . $row["name"] . '</option>';
}
mysqli_close($connection);
?>
... which should return the values from the php file to this drop down menu with <span id="districts_dropdown">:
<label for="district" class="medium">District</label>
<select name="district" class="textbox short_field">
<option value=""></option>
<span id="districts_dropdown"></span>
</select>
This works nicely if <span id="districts_dropdown"> is outside of the <select> tags, but not within. Any insight as to why would be greatly appreciated.
Thanks for you help Popnoodles! I fixed part of the problem by having the php code generate the entire <select> tag like this:
<?php
$q = $_REQUEST['q'];
$id = "";
if ($q = 'TBOOTH') {
$id = "2";
} else {
if ($q = 'WIRELESS ETC') {
$id = "3";
}
}
echo '<select name="district" class="textbox short_field">
<option value=""></option>';
$query = "SELECT dist.name FROM districts AS dist JOIN int_bd AS ibd ON dist.id = ibd.districts_id WHERE banners_id = '".$id."' GROUP BY dist.id ORDER BY dist.id ASC";
$result = mysql_query($query, $connection);
if (!result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row["name"] . '"';
if($row["name"] == $district) { echo ' selected';} ;
echo '>' . $row["name"] . '</option>';
}
mysql_close($connection);
?>
But now the $id variable I have at the top of that code isn't updating when the onchange() is triggered.
It looks like you want to repopulate the options in a select tag. First of all you cannot put a span in there. Please adhere to the specs - <select> tags can only contain <option> and <optgroup> tags.
This is what you're changing
document.getElementById("districts_dropdown").innerHTML=xmlhttp.responseText;
So what will happen if you target this instead
<select name="banner" id="banner" class="textbox short_field" onchange="show_districts(this.value)">
with
document.getElementById("banner").innerHTML=xmlhttp.responseText;
You get options. http://jsfiddle.net/Da26e/1/

Categories

Resources