Send sql query parameters to function - javascript

TABLE wp_thesis TABLE wp_courses
Thesis_ID Thesis_Title Course_ID Thesis_ID Course
1 thesis1 1 1 course1
2 thesis2 2 1 course2
3 2 course1
4 2 course2
5 2 course3
I have a select that calls the showText function onchange.
$query = "SELECT * FROM wp_thesis";
$result = mysqli_query($conn,$query);?>
<select name="ThesisTitle" onchange="showText(x,y)" required="">
<option disabled='disabled' selected='selected' value=''></option>"; <?php
foreach ($result as $row)
{
echo "<option value= {$row[Thesis_ID]}>{$row[Thesis_Title]}</option>";
}
echo"</select><br />";?>
First thought was to send the value of the select (onchange="showText(this.value)") and then have an sql query inside showText function in order to get the two values i wanted. I read that you can't execute sql queries inside functions because Javascript is client-side, so I thought to do the sql query on php and then send the values to showText function. The query I want is this:
$query = "SELECT Course FROM wp_courses WHERE Thesis_ID={$row[Thesis_ID]} ";
$courses = mysqli_query($conn,$query);
$coursesNo = mysqli_num_rows($courses);
Tha values I want to send are $courses and $coursesNo. Is it possiple to get the value of select in the same php file, without using a button or anything like that?

Get X and Y co-ordinate before rendering option and provide it as data attribute.
<select name="ThesisTitle" onchange="showText(this)" required="">
<option disabled='disabled' selected='selected' value=''></option>"; <?php
foreach ($result as $row)
{
echo "<option data-x={$row[Thesis_X]} data-y={$row[Thesis_Y]} value= {$row[Thesis_ID]}>{$row[Thesis_Title]}</option>";
}
echo"</select><br />";?>
Just after that go to showText(this) function with this as parameter and get the attribute with
function showText(obj){
var x_val = $(obj).attr("data-x");
var y_val = $(obj).attr("data-y");
}
Hope this helps to you.

I finally found what I needed. I am posting the code.
<script language="javascript" type="text/javascript">
//Browser Support Code
function showCourses(str){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Problem with your browser!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('courses'); // where it should be displayed
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value and pass it to server script.
var queryString = "?thesis_id=" + str ;
ajaxRequest.open("GET", "http://localhost/wordpress/get_thesis/" + queryString, true);
ajaxRequest.send(null);
}
From the select:
<select name="ThesisTitle" id="link_block" onchange="showCourses(this.value)" required="">
<option disabled='disabled' selected='selected' value=''></option>";<?php
foreach ($result as $row)
{
echo "<option value= {$row[Thesis_ID]}>{$row[Thesis_Title]}</option>";
}
echo"</select><br />";?>
I am sending the Thesis_ID to http://localhost/wordpress/get_thesis/ which is a php file that does the query I needed.

Related

Dropdown automatically selected a value

i need help for this problem.
I want to make a dynamically dropdown and when i select a value from one dropdown to "A", the another dropdown will be set to "B".
I have a javascript function for dynamically dropdown like this.
<script type="text/javascript">
function coba(){
document.getElementById("add").innerHTML +=
" <inputclass='department_name' type='text'
size='50' />";
}
</script>
REFERENCE: how to dynamically change item of two related combobox
In Short:
In file1.php, Retrieve mysql tbl1 and display it in a combo box A.
On change of Combo box A, Fetch the value of option and pass it a php file file2.php via ajax and Display the output in file1.php which is produced by file2.php.
In file2.php, Retrieve mysql tbl2 with the Id passed by Ajax and generate a combo box B.
Example:
index.php
<script type="text/javascript">
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function ajax_function(url, postData, id)
{
xmlhttp=GetXmlHttpObject();
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", postData.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
document.getElementById(id).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.send(postData);
}
function dispSecond(Id)
{
var params = 'Id=' + Id ;
var DivId = 'dispDiv';
ajax_function('ajax_display.php', params, DivId);
}
</script>
<?php
/* Mysqli query to retrieve and store in $ArrayList(Id=>Text)
Example: $ArrayList = array(1=>'Ford',2=>'Chevy');
*/
?>
<select id="drop_first" name="drop_first" onchange="return dispSecond(this.value);">
<option value="0">[Select]</option>
<?php
foreach ($ArrayList as $k=>$v)
{
echo '<option value="'.$k.'">'.$v.'</option>';
}
?>
</select>
<div id="dispDiv"></div>
ajax_display.php
<?php
$Id = isset($_REQUEST['Id']) ? $_REQUEST['Id'] : '';
if ($Id)
{
/* Mysqli query to retrieve and store in $SubArray where $Id
Example:
If $Id=1
$SubArray = array(1=>'Focus',2=>'Explorer');
If $Id=2
$SubArray = array(1=>'Cavalier',2=>'Impala', 3=>'Malibu');
*/
?>
<select id="drop_second" name="drop_second">
<option value="0">[Select]</option>
<?php
foreach ($SubArray as $k=>$v)
{
echo '<option value="'.$k.'">'.$v.'</option>';
}
?>
</select>
<?php
}
?>
Note:
Use Mysqli or PDO instead mysql
Below Demo and Download are based on arrays, you can implement by using mysqli retrieval.
Also You can try using $.ajax which is more easy also.
DEMO | DOWNLOAD

how to dynamically change item of two related combobox

I have two mySQL tables tbl1 and tbl2 tbl1 has a primary key column who reference in tbl2 column. Now I have html form in which two combobox is available . I shows all data of tbl1 into first combobox. Now I want to show the related data of tbl2 into second combobox after selection of item in first combobox.
So please explain me simple and easy technique to achieve it. Thanks in advance.
In Short:
In file1.php, Retrieve mysql tbl1 and display it in a combo box.
On change of Combo box, Fetch the value of option and pass it a php file file2.php via ajax and Display the output in file1.php which is produced by file2.php.
In file2.php, Retrieve mysql tbl2 with the Id passed by Ajax and generate a combo box.
Example:
index.php
<script type="text/javascript">
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function ajax_function(url, postData, id)
{
xmlhttp=GetXmlHttpObject();
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", postData.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
document.getElementById(id).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.send(postData);
}
function dispSecond(Id)
{
var params = 'Id=' + Id ;
var DivId = 'dispDiv';
ajax_function('ajax_display.php', params, DivId);
}
</script>
<?php
/* Mysqli query to retrieve and store in $ArrayList(Id=>Text)
Example: $ArrayList = array(1=>'Ford',2=>'Chevy');
*/
?>
<select id="drop_first" name="drop_first" onchange="return dispSecond(this.value);">
<option value="0">[Select]</option>
<?php
foreach ($ArrayList as $k=>$v)
{
echo '<option value="'.$k.'">'.$v.'</option>';
}
?>
</select>
<div id="dispDiv"></div>
ajax_display.php
<?php
$Id = isset($_REQUEST['Id']) ? $_REQUEST['Id'] : '';
if ($Id)
{
/* Mysqli query to retrieve and store in $SubArray where $Id
Example:
If $Id=1
$SubArray = array(1=>'Focus',2=>'Explorer');
If $Id=2
$SubArray = array(1=>'Cavalier',2=>'Impala', 3=>'Malibu');
*/
?>
<select id="drop_second" name="drop_second">
<option value="0">[Select]</option>
<?php
foreach ($SubArray as $k=>$v)
{
echo '<option value="'.$k.'">'.$v.'</option>';
}
?>
</select>
<?php
}
?>
Note:
Use Mysqli or PDO instead mysql
Below Demo and Download are based on arrays, you can implement by using mysqli retrieval.
Also You can try using $.ajax which is more easy also.
DEMO | DOWNLOAD

How to use AJAX to create/update radio buttons?

I currently have a setup where I use a PHP script to create a list of radio buttons by loading the required information from my database. This script is in the HTML structure rather than a separate file, so it requires a page refresh to update the list.
I'd like to figure out how to delete and reload the list upon pressing a button, the ID of which is 'btnDelete' (the actual deletion of items in the database is a separate point that I won't go into here). The current code that I have will delete the list of radio buttons, but when the next line is added, nothing happens (including list deletion).
PHP (delCom.php)
<?php
include_once('includes/conn.inc.php');
$query = ("SELECT comicID, comicName FROM comic WHERE username = '".$_SESSION['username']."'");
$result = mysqli_query($conn, $query);
while ($row = $result->fetch_assoc())
{
echo "<br><input name='comicList' id='".$row['comicID']."' type='radio' value='".$row['comicID']."'>".$row['comicName']." </option>";
}
?>
JavaScript
function delComic()
{
var ajaxRequest;
try
{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer Browsers
try
{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4)
{
$("#loadList").remove();
document.getElementById("divComics").innerHTML=xmlhttp.responseText;
}
}
ajaxRequest.open("GET", "delCom.php?t=", true);
ajaxRequest.send(null);
}
HTML
<div id="divComics">
<p><u>Uploaded Comics</u></p>
<!-- find comics in database -->
<div id="loadList">
<?php
include_once('includes/conn.inc.php');
$query = ("SELECT comicID, comicName FROM comic WHERE username = '".$_SESSION['username']."' ORDER BY comicName ASC");
$result = mysqli_query($conn, $query);
while ($row = $result->fetch_assoc())
{
echo "<br><input name='comicList' id='".$row['comicID']."' type='radio' value='".$row['comicID']."'>".$row['comicName']." </option>";
}
?>
</div>
<br>
<br>
<input type="button" onclick="delComic()" value="Delete Comic" name="deleteButton" id="btnDelete"/>
</div>
The code creates buttons correctly when run in the HTML, but not when in a separate php file.
Thanks in advance.
EDIT: Updated to fix a few misnamed things and to add the new line suggested. The loadList now empties but doesn't delete itself, as it should. The current problem is that the PHP file won't output the buttons again.
<?php
$username = $_GET['username'];
include_once('includes/conn.inc.php');
$query = ("SELECT comicID, comicName FROM comic WHERE username = '$username'");
$result = mysqli_query($conn, $query);
while ($row = $result->fetch_assoc())
{
echo "<br><input name='comicList' id='".$row['comicID']."' type='radio' value='".$row['comicID']."'>".$row['comicName']." </option>";
}
?>
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4)
{
document.getElementById('loadList').innerHTML="";
document.getElementById("divComics").innerHTML=xmlhttp.responseText;
}
}
ajaxRequest.open("GET", "delCom.php?username=MY_EXACT_NAME_I_KNOW_WORKS_HERE", true);
ajaxRequest.send(null);
There is no element with an id=comicList and you cannot remove it $("#comicList").remove(); in Javascript because it does not exist. Javascript is probably stopping execution at that point, and thereby not displaying your results from PHP.

Add a record to the database with XMLHttpRequest

I have the following form:
<form id="form" name="form">
<img id="close" src="images/3.png" onclick ="div_hide()">
<h2>Grade</h2>
<hr>
<input id="fn" name="fn" placeholder="Faculty number" type="number">
<select id="grade_type" name="grade_type">
<option value="test" selected="selected">Тест</option>
<option value="attendance">Attendance</option>
<option value="homework">Homework</option>
</select>
<input id="grade" name="grade" placeholder="Points" type="number">
Add record
</form>
When I click the submit button I want to add the points and the grade_type to the database. Therefore I am using JavaScript and PHP:
// Validating Empty Field
function check_empty() {
if (document.getElementById('grade').value == "") {
alert("Fill the fields!");
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
alert("xmlhttpreq");
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var grade = String(document.getElementById('grade').value);
var grade_type = document.getElementById('grade_type');
var grade_type_value = String(grade_type.options[grade_type.selectedIndex].value);
var fn = String(document.getElementById('fn').value);
xmlhttp.open("GET","getuser.php?grade="+grade+"grade_type="+grade_type_value+"fn="+fn,true);
xmlhttp.send();
document.getElementById('form').submit();
}
}
The contents of the getuser.php file are:
<?php
require "config.php";
$fn = $_GET["fn"];
$grade = $_GET["grade"];
$type = $_GET["grade_type"];
echo "<script type='text/javascript'>alert('$fn');</script>";
try {
$conn = new PDO("mysql:host=" . DB_SERVER . ";dbname=" . DB_NAME, DB_USERNAME, DB_PASSWORD);
}
catch(PDOException $e) {
die("Database connection could not be established.");
}
$sql = $conn->prepare("SELECT * FROM students WHERE fn = ?");
$sql->execute(array($fn));
if($sql->rowCount() > 0) {
$statement = $conn->prepare("INSERT INTO points (student_fn, type, grade, datetime)
VALUES (?, ?, ?, CURRENT_TIMESTAMP)");
$statement->execute(array($fn, $type, $grade));
}
else {
echo "<script type='text/javascript'>alert('No such fn');</script>";
}
$conn = null;
?>
However I think it never gets executed because I never see the result of the alert. I have never worked with XMLHttpRequest before so I don't even know whether my code is valid. I would greatly appreciate any help.
You can do this by using jquery.
$('#submit').click(function(){
$.ajax({
url: 'getuser.php',
type: 'GET',
data: $('#form1').serialize(),
success: function(result){
alert("Your data has been uploaded");
}
});
});
make sure that you need to add jquery file to your websitelike that

ajax call to populate form fields from database query when select value changes

I have been looking through the questions on here and cant find an exact answer to what i am after :( but i have managed to get something.
i have a form select field which i populate from a db query
<select style="width:100%;" class="quform-tooltip chosen-select" id="company_select" name="company_select" title="Company Select" onChange="showUser(this.value)">
<option value="">Please select</option>
<?php
$userID = $user->getUserID();
$query = $user->database->query("SELECT * FROM tbl_businesses as business LEFT JOIN tbl_user_businesses as biz_user ON business.businessID = biz_user.businessID WHERE biz_user.userID ='$userID'");
while($row=$user->database->fetchArray($query))
{
$bizID = $row['businessID'];
$bizName = $row['businessName'];
echo "<option value='$bizID'>$bizName</option>";
}?>
</select>
and then there are currently 2 other textboxes (might increase eventually) which i want to populate when the above select box value is changed/selected
<input id="company_name" type="text" name="company_name" value="" />
<input id="company_email" type="text" name="company_email" value="" />
so i have an onchange function on my select box which is this
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("company_name").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)
{
var data = JSON.parse(xmlhttp.responseText);
for(var i=0;i<data.length;i++)
{
document.getElementById("company_name").innerHTML += data[i].id + ' - ' + data[i].name + ' - ' + data[i].web;
}
}
}
xmlhttp.open("GET","formdata.php?q="+str,true);
xmlhttp.send();
}
</script>
and my formdata.php file is like so
<?php
include("include/user.php");
$q = intval($_GET['q']);
$sql="SELECT * FROM tbl_businesses WHERE businessID = '".$q."'";
$result = $user->database->query($sql);
$info = array();
while($row=$user->database->fetchArray($result))
{
$cID = $row['bussinessID'];
$cName = $row['businessName'];
$cWeb = $row['businessWebsite'];
$info[] = array( 'id' => $cID, 'name' => $cName, 'web' => $cWeb );
}
echo json_encode($info);?>
which is making the ajax call correctly and returning the data expected but i now need help to populate the textbox values?
can anyone please help me with this, have literatly spent ages trying to figure it out, im not familiar with javascript/json so not sure where to begin
i want the company_name textbox value to be set to $cName; and
company_email textbox value to be set to $cWeb;
appreciate any help
Luke
ok the solution that i used, for anyone else wanting to know how i solved it is
my index.php which contains the javascript and the form code
javascript code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("company_name").value="";
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)
{
var data = JSON.parse(xmlhttp.responseText);
for(var i=0;i<data.length;i++)
{
document.getElementById("company_name").value = data[i].name;
document.getElementById("company_email").value = data[i].web;
}
}
}
xmlhttp.open("GET","formdata.php?q="+str,true);
xmlhttp.send();
}
</script>
and the form code
<select style="width:100%;" class="quform-tooltip chosen-select" id="company_select" name="company_select" title="Company Select" onChange="showUser(this.value)">
<option value="">Please select</option>
<?php
$userID = $user->getUserID();
$query = $user->database->query("SELECT * FROM tbl_businesses as business LEFT JOIN tbl_user_businesses as biz_user ON business.businessID = biz_user.businessID WHERE biz_user.userID ='$userID'");
while($row=$user->database->fetchArray($query))
{
$bizID = $row['businessID'];
$bizName = $row['businessName'];
echo "<option value='$bizID'>$bizName</option>";
}?>
</select>
<input id="company_name" type="text" name="company_name" value="" />
<input id="company_email" type="text" name="company_name" value="" />
then my formdata.php
$q = intval($_GET['q']);
$sql="SELECT * FROM tbl_businesses WHERE businessID = '".$q."'";
$result = $user->database->query($sql);
$info = array();
while($row=$user->database->fetchArray($result))
{
$cID = $row['businessID'];
$cName = $row['businessName'];
$cWeb = $row['businessWebsite'];
$info[] = array( 'id' => $cID, 'name' => $cName, 'web' => $cWeb );
}
echo json_encode($info);?>
thats it, thanks to charlietfl for your help!
hope this helps someone :)
Here's an example with PHP and JQuery. If you are not familiar with JQuery, I suggest you take some time to digg into that before going on with your ajax, it's definitely gonna worth it. JQuery have methods like get and ajax to do async request to the server.
Now, heres some jquery we used to get JSON data from the server.
var title = '.....'
$.getJSON('getActivite.php?title=' + title, null,
function(data){
$("#currentId").val(data.ID);
$("#nomActivite").val(data.Nom);
$("#Description").val(data.Description);
$("#DateEvent").val(data.Date);
});
$("#currentId").val(data.ID); , this says : find the element with the id currentId in the DOM, and change it's value to the property ID of the data received from the ajax call.
On the PHP side, they had
<?php
header('Content-Type: application/json');
mysql_connect("localhost","root") or die (" NOPE . [" . mysql_error() . "]");
mysql_select_db("garderie");
$title = $_GET["title"]; // we received this from the json call
$query = " select a.ActiviteID as ActiviteID , rtrim(a.Nom) as Nom, a.Description from activites a inner join .....' ";
$result = mysql_query($query);
$ligne = mysql_fetch_array($result);
$data = array(
'ID' => $ligne["ActiviteID"],
'Nom' => $ligne["Nom"],
'Description' => $ligne["Description"],
'Date' => $date
);
mysql_close();
echo (json_encode($data));
?>

Categories