PHP AJAX and MySQL - javascript

I tried to follow this tutorial http://www.w3schools.com/php/php_ajax_database.asp
I want to send the value from a select(with onchange) to change the sql query.
function myfunctionTime(time) {
if (time=="") {
document.getElementById("txtHint").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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","book.php?id=<?php echo $FILM_ID; ?>&q="+time,true);
xmlhttp.send();
}
Here is the select with the onchange:
<p for="session">Time:</p>
<select class="form-control" id="session" name="session"onchange="myfunctionTime(this.value)">
<option selected="selected" value="12:00">12:00</option>
<option value="16:00">16:00</option>
<option value="20:00">20:00</option>
</select>
Here is the PHP where I want to get the variable.
// Print all the get variables
print_r($_GET);
// Film session or time
$session = "12:00";
$session = $_GET['q'];
echo "Session: ".$session;
$query = "SELECT * FROM booking WHERE (FILM_ID = '$film_id' AND BOOKING_SESSION = '$session')";
And this is the error I get:
Notice: Undefined index: q in C:\xampp\htdocs...\book.php on line 271

Change your $session value to this
$session = $_GET['id'];

time is empty. validation is not working as it is undefined and not "". so check if (time=="" || time == undefined) for validation.
also in the beginning of the function myfunctionTime(time) check for time value like console.log(time);

Related

Need help converting AJAX method of passing variables

I am decent with PHP but brand new to AJAX. I am currently using AJAX to pull data dynamically from CMS and display within a div on the same page. Currently I am doing this with a selection / option using a form. I am wondering if there is a way i can do this with an A Href and how that might look. I don't want it to refresh the page but work like an A Href would do pass variable values.
Here is what I have.
<script>
function showOrder(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","getorder.php?q="+str,true);
xmlhttp.send();
}
}
</script>
<form>
<select name="orders" onchange="showOrder(this.value)">
<option value="">Select an order:</option>
<? foreach($orders as $order){ ?>
<option value="<? order::num(); ?>"><? order::customer(); ?></option>
<? } ?>
</select>
</form>
I have found out a way to do it what I wanted, it ultimately led to scrapping the A HREF method and going with a button instead.
Here is how I had to structure the button
<button onclick="showOrder(this.value)" value="<? echo order::num(); ?>"><? echo order::customer(); ?></button>

Find items in database from multiselect box

I have a multiple select box which onchange runs a function that collects the selected options, turns them into an array, and then sends them using AJAX to my php file. I then would like the php file to add each option in the sql WHERE field so that it returns results with any of the options in.
Can anyone please give me advice on how to do this?
My code is as follows:
HTML FILE SELECT BOX
<select name="gift" id="gift" class="multiple-select" multiple="multiple" onchange="change()">
<option value=""></option>
<option value="him">Him</option>
<option value="her">Her</option>
<option value="kids">Kids</option></select>
JAVASCRIPT FILE
function change()
{
var giftarray = new Array();
$('#gift > option:selected').each(
function(i){
giftarray[i] = $(this).text();
});
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("product").innerHTML=xmlhttp.responseText;
}
}
var url="results.php"
url=url+"&gift="+gift;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
PHP FILE:
include 'dblogin.php';
$gift = $_GET["gift"];
$gift=str_replace("\\","",$gift);
$where = "WHERE gift IN $gift";
$sql= "SELECT *
FROM $itemstable
$where";
$result = mysql_query($sql) or die ('Unable to run query:'.mysql_error());
while($item = mysql_fetch_array($result))
{
DISPLAY ALL ITEMS IF SELECT BOX BLANK OR JUST ITEMS THAT MATCH SELECTED OPTIONS
}
mysql_close();
?>
Any help will be appreciated as i've spent ages on this with no luck.
Thanks in advance

Need to pass two element value on ajax

I create a program for giving appointments to the users. Date and time this is two different element.I save time dynamically to the database and user can select date and time. now i am create a Ajax request to match the date & time ! give it to any one or not.
function Filter(str)
{
var xmlhttp;
if (str=="")
{
document.getElementById("txtHint").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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","filter.php?id="+str,true);
xmlhttp.send();
}
<input type="text" class="form-control hide_date" value="" id="appoint" name="appoint" placeholder="Date" readonly>
<select type="select" name="appoint_time" class="form-control appoint_time" id="time-app" onchange="Filter(this.value)">
<option value="">Time</option>
<?php
$sql5 = mysqli_query($link, "SELECT `id` FROM `time_slots` where `status` = '1'");
$query = mysqli_fetch_assoc($sql5);
$solt_id = $query['id'];
$sql6 = mysqli_query($link, "SELECT `time` FROM `time_picker` where `time_slot` = '$solt_id'");
while($row = mysqli_fetch_assoc($sql6))
{
?><option value="<?php echo $row['time']; ?>"><?php echo $row['time']; ?></option>
<?php
}
?>
</select>
In this code the ajax work fine but and this only send appointment time value to filter page. I need to pass also the appointment date value to filter page. whenever i try it display empty. please tell how i use to both element value pass in one request.
Thanks.
enter image description here
this code will work when both element value received
function Filter(str)
{
var xmlhttp;
var date=document.getElementById("appoint").value;
if (date=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (str=="")
{
document.getElementById("txtHint").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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","filter.php?id="+str+"&date="+date,true);
xmlhttp.send();
}
you can get value of date in this way
var date=document.getElementById("appoint").value;
xmlhttp.open("GET","filter.php?id="+str+"&date="+date,true);
Try this
<select type="select" name="appoint_time" class="form-control appoint_time" id="time-app" onchange="Filter(this.value,appoint.value)">
in script function
function Filter(str,datz)
xmlhttp.open("GET","filter.php?id="+str+"&date="+datz,true);
xmlhttp.send();

Post data from javascript to php

I have two dropdowns in my web-page where I select manager and project.
If I choose any manager then I want to get the project which are assigned to particular manager.
I think I can't do this without the help of javascript and ajax.
So I have passed the selected value of manager to javascript file and again I have posted the value using ajax. But it seems the code is not working.
Here is my php code.
<form method="post" action="<?php $_PHP_SELF ?>">
Select Manager <select id='managed' name="managed" onchange="getManager()">
<option value="">---select---</option>
<?php
$conn=mysqli_connect('localhost','root','root','projmanagement');
$result=mysqli_query($conn,'SELECT manager_id,manager_name FROM manager');
while($row=mysqli_fetch_assoc($result)) {
echo "<option value='$row[manager_id]'>$row[manager_name]</option>";
}
?>
</select>
Select Project <select name="projectsd">
<option value="">---select---</option>
<?php
$temp = $_POST['managed'];
var_dump($temp);
die();
$result1=mysqli_query($conn,'SELECT project_id,project_name FROM project inner join manager on project.m_id=$temp');
while($row1=mysqli_fetch_assoc($result1)) {
echo "<option value='$row1[project_id]'>$row1[project_name]</option>";
}
?>
This is my javascript code.
function getManager() {
var myvar=document.getElementById('managed').value;
var xmlhttp;
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("managed").innerHTML = xhr.responseText;
}
}
xmlhttp.open("POST","TaskMaster.php",true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("managed=" + myvar);
}
I'am a beginner to php and javascript.
Please give me an idea to solve my problem.
Try This :
<form method="post" action="<?php $_PHP_SELF ?>">
Select Manager <select id='managed' name="managed" onchange="getManager()">
<option value="">---select---</option>
<?php
$conn=mysqli_connect('localhost','root','root','projmanagement');
$result=mysqli_query($conn,'SELECT manager_id,manager_name FROM manager');
while($row=mysqli_fetch_assoc($result)) {
echo "<option value='$row[manager_id]'>$row[manager_name]</option>";
}
?> </select>
Select Project <div id="project_container"><select name="projectsd"></div>
JS :
function getManager()
{
var myvar=document.getElementById('managed').value;
var xmlhttp;
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("project_container").innerHTML = xhr.responseText;
}
}
xmlhttp.open("POST","TaskMaster.php",true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("managed=" + myvar);
}

Javascript pass title attribute through function

I have a function that gets the value of a select menu and this work great. But i am trying to add another value to the function. So I thought I would use the title attribute for option (please see code below). The problem is the username parameter in my JavaScript function is undefined.
Does anybody have any ideas of what im doing wrong?
FORM
<form action="">
<select id="acyear" name="acyear" onchange="showyearlogdays(this.value, this.title)">
<option value="" label="">- Year -</option>
<?php
$is_business_result = mysql_query('SELECT DISTINCT(academic_year)FROM holiday_entitlement_business_manual WHERE employee = \'' . $username . '\'');
while($acyear_filter = mysql_fetch_array($is_business_result)) {
echo '<option value="'.$acyear_filter['academic_year'].'" title="'.$username.'"';
$datestr = $acyear_filter['academic_year'];
$currentyear = substr($datestr, 0, 4);
if(intval(substr($datestr,4,2)) < 8){$ayear = ($currentyear - 1).'/'.$currentyear;}
else{$ayear = ($currentyear).'/'.($currentyear + 1);}
echo '>';
echo $ayear;
echo '</option>';
}
?>
</select>
</form>
Javascript
function showyearlogdays(str, username)
{
if (str=="")
{
document.getElementById("txtHint").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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","days_yearlog.php?username="+username+"&q="+str,true);
xmlhttp.send();
}
You need to get the title attribute of the selected option. Your code is pointing to the title attribute of the select tag. Make the change below:
showyearlogdays(this.value, this.options[this.selectedIndex].title)
You should also address the security concern mentioned in the comments. The way your query is setup would make for a really simple SQL Injection attack. If you don't want to rearchitect it the way the commenter suggested, I would at least escape $username so that SQL can't be injected.

Categories

Resources