Need help converting AJAX method of passing variables - javascript

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>

Related

Ajax/PHP - autocomplete value not recognised

I am using this example to run an ajax data query from an mysql db, that returns a table.
This is working fine when text is manually typed into this input form eg:
But the search form has an autocomplete jquery script that will help the user along. When a value is chosen from the dropdown autocomplete values, the onchange event isn't recognized, no table shows.
My question is, how would I put a button at the end of the search form, to change this to 'onclick' event, rather than 'onchange'? The hurdle I am facing is that the input for 'client_address' is part of a larger form, and clicking submit on any button causes the page to try submit the entire form.
create_wt.php:
// autocomplete
<script type="text/javascript">
$(function() {
$( "#clientsearch" ).autocomplete({
source: 'backend_search_addressWT.php'
});
});
</script>
// retrieve data in table
<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","ajax_get_client_info.php?q="+str,true);
xmlhttp.send();
}
}
</script>
<div class="form-group <?php echo (!empty($client_address_err)) ? 'has-error' : ''; ?>">
<label>Address</label>
<div class = "input-group">
<input id="clientsearch" type="text" name="client_address" onchange="showUser(this.value)" class="input-group form-control" value="<?php echo $client_address; ?>" placeholder="Search by address..." style="width: 500px;">
<!---<span class="input-group-btn">
<button class="btn btn-success" value="submit" id="ajaxbtn" type="submit">Get Client Info</button>
</span> -->
</div>
<br><div id="txtHint"><b>Person info will be listed here...</b></div>
<span class="help-block"><?php echo $client_address_err;?></span>
</div>
ajax_get_client_info.php:
<?php
require_once 'config.php';
$q = trim($_GET['q']);
$query = $mysqli->query("SELECT * FROM client WHERE client_address LIKE '%".$q."%'");
//$data = array();
//while ($row = $query->fetch_assoc()) {
// $data[] = ($row);
//}
//echo json_encode($data);
echo "<table>
<tr>
<th>client_id</th>
<th>Client Name</th>
<th>Phone Number</th>
</tr>";
while($row = mysqli_fetch_array($query)) {
echo "<tr>";
echo "<td>" . $row['client_id'] . "</td>";
echo "<td>" . $row['client_name'] . "</td>";
echo "<td>" . $row['client_phone'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
EDIT:
create_wt:
<script type="text/javascript">
$(function() {
$( "#clientsearch" ).autocomplete({
select: 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","ajax_get_client_info.php?q="+str,true);
xmlhttp.send();
}
}
}
{
source: 'backend_search_addressWT.php'
});
});
</script>
According to jQuery UI Autocomplete documentation:
http://api.jqueryui.com/autocomplete/#event-select
the select event of the autocomplete input does not accept the user's input as an argument but has 2 other: event, ui.
So you are trying to access the value: ui.item.value that is the selected item's value.
So that must be your problem.
CBroe has the same answer in the comments.
....
function getHint(value) {
if ((value !== "") && (typeof value !== 'undefined')) {
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","ajax_get_client_info.php?q=" + value, true);
xmlhttp.send();
return true; // return true to accept the selection of the user
} else {
document.getElementById("txtHint").innerHTML = "";
$(this).autocomplete( "close" ); // Close the autocomplete popup manual because by returning false negates the selection but it does not close the popup.
return false; // return false to negate the selection of the user
}
}
$( "#clientsearch" ).autocomplete({
select: function showUser(event, ui) {
return getHint(ui.item.value);
},
change: function showUser(event, ui) {
return getHint(ui.item.value);
},
{
source: 'http://www.example.com'
}
});
....
Be sure to read the documentation so you know how to treat this case from the start.
Hope this helps.
Change onchange in input box to onkeyup, that should solve, onchange is mainly used for radio buttons and checkboxes.
<input id="clientsearch" type="text" name="client_address" onkeyup="showUser(this.value)" class="input-group form-control" value="<?php echo $client_address; ?>" placeholder="Search by address..." style="width: 500px;">
Use a input type button:
<input type="button" name="" id="">
and use its click event. Input type will not submit the form.

Multicombobox not visible on clicking back button

I am trying to develop an online booking system which has different options for each course. When a course is selected a combobox opens where you choose the week that you want the course.
There is an validation function to ensure that certain fields are completed. If you need to go back to complete the form, the combobox is not visible.
Is there any way to make combobox visible?
html as follows
course 1
course 2
course 3
Select your course...
The combobox is lifted out of Wordpress as follows:
<input type="hidden" name= "course1a" value="<?php echo $title;?>,<?php echo the_field('cost_of_course',$week1a); ?>" />
<select name="date1a" id="date1a">
<option value="">Select Week</option>
<?php
$categories =get_the_category($week1a);
foreach ($categories as $category) {
if($category->name !== '6 +')
if($category->name !== '7+')
if($category->name !== '8+')
if($category->name !== '9+')
if($category->name !== '10 +')
if($category->name !== '11+')
if($category->name !== 'All')
$option = '<option value="'.$category->cat_name.'">';
$option .= $category->cat_name;
$option .= '</option>';
echo $option;
}
?>
The javascript driving this is as follows:
function showWeek(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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","dates.php?week="+str,true);
xmlhttp.send();
}
}
Any thoughts on how we can make the dropdown show on hitting back button.
booking system can be seen at
https://www.chiswickcourses.co.uk/wp/online-booking/
Cheers
Ian

html form not posting from javascript and php

I have a html form that posts the data to a php file for processing, on this form there is a dynamically produced combo box that is produced from a php file using javascript. The combo box displays and functions fine when the page is loaded but when the form is submitted the value from this box isn't posted.
the JavaScript function is
function showUser(str) {
if (str == "") {
document.getElementById("selSubCat").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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("selSubCat").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getSubCats.php?Cat="+str,true);
xmlhttp.send();
}
}
The html is
<td >Category:</td>
<td >
<select name="Cats" onchange="showUser(this.value)" ><?
$qryCats="SELECT * FROM tblCategories";
$resCats=mysql_query($qryCats,$dbMain);
while($rowCats = mysql_fetch_array($resCats)){
echo "<option value='".$rowCats['Name']."'>".$rowCats['Name']."</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td >Sub Category:</td>
<td id="selSubCat">
</td>
</tr>
And the php file:
<?
include("dbconfig.php");
$cat=$_GET['Cat'];
$qryCats="SELECT * FROM tblSubCats WHERE Parent='" .$cat. "'";
$resCats=mysql_query($qryCats,$dbMain);
if ($numrow=mysql_num_rows($resCats)>0){
echo "<select name='subCats'>";
while($rowCats = mysql_fetch_array($resCats)){
echo "<option value='" .$rowCats['Name']. "'>" .$rowCats['Name']. "</option>";
}
echo "</select>";
}
else{
echo " There are no sub categories ";
}
?>
Any suggestions will be appreciated, I can't figure out why everything else apart from the subcategory is posted
Check out the name attribute. In HTML its Cats but in your code you are using $_GET['Cat'];
It should be
$cat=$_GET['Cats'];
Solved, I had a table on the html page which the form was inside. I swapped the tags around so that the table is inside the form and the dynamic fields post just fine. Not sure why having a form within a table stopped these from posting but at least it works now.

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