I have posted the code below.
there are two files..
getvendorname.php
sales.htm (containing the javascript function)
Here what i am did is when blur i need to retrieve the values without page reload from getvendorname.php and show the vendor name and id in the different textbox.
Here i have to store the values into different textbox retrieved from database with the use of xmlhttprequest object.Here the values are retrieved,but i can't store into the different textbox.Its working,but it shows like this
o/p:201anne.I need to display vendor id and vendor name on different textbox.please help me
sales.htm
<script type='text/javascript'>
function getname()
{
var vendorID = document.getElementById("idvid").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("iddiv1").innerHTML=xmlhttp.responseText;
document.getElementById("iddiv2").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getvendorname.php?vendorid="+vendorID,true);
xmlhttp.send();
}
</script>
<html>
<head><title>vendor info</title> </head>
<body>
<td>Vendor Primary ID:</td>
<td><input type="text" id="idvid" name="vendor_primary_number" onblur="getname()">
</td>
<td> <div id="iddiv1"> </div></td>
<td> <div id="iddiv2"> </div></td>
</body>
</html>
getvendorname.php
<?php
$vid = $_GET['vendorid'];
$connection = mysql_connect('localhost','root','root');
mysql_select_db('bgm_score', $connection);
$r ="select vendorid,vendorname from vendor_info where vendorid ='$vid'";
$result = mysql_query($r, $connection);
$row = mysql_fetch_assoc($result);
echo $row["vendorid"];
echo $row["vendorname"];
?>
I made a few corrections to your code to make it work. First, replace this line:
document.getElementById("iddiv1").innerHTML=xmlhttp.responseText;
with:
document.getElementById("iddiv1").innerHTML=vendorID;
The reason is you don't need to retrieve the vendor ID from the database since that's the data you're sending. Just use the variable you have. That also means you need to change your PHP code.
Remove the vendorid field from your query:
$r ="select vendorid,vendorname from vendor_info where vendorid ='$vid'";
Now it looks like this:
$r ="select vendorname from vendor_info where vendorid ='$vid'";
Also remove this line since it's not needed:
echo $row["vendorid"];
Related
I am following the guide from http://www.w3schools.com/php/php_ajax_database.asp, and I get the basic concept of how this works.
My code:
PHP:
<?php
include('./db.php');
$PM = mysqli_query($con, "SELECT DISTINCT PMName FROM report WHERE PMname <> '' ORDER BY PMName ASC");
?>
<select class="navbar-inverse" placeholder="PM Name" name="PMName"onchange="showUser(this.value)">
<?php
while ($row = mysqli_fetch_row($PM)) {
$selected = array_key_exists('PMName', $_POST) && $_POST['PMName'] == $row[0] ? ' selected' : '';
printf(" <option value='%s' %s>%s</option>\n", $row[0], $selected, $row[0]);
}
?>
</select>
<div id="txtHint"><b></b></div>
JavaScript:
<script>
function showUser(str) {
if (str !==".PM") {
alert(str);
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","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
and the getuser.php page:
<?php
$q = intval($_GET['q']);
include('./db.php');
$sqlPM= "SELECT * FROM report WHERE PMName = '".$q."'";
$result = mysqli_query($con, $sqlPM);
?>
<table>
<?php
echo $q ;
?>
</table>
I have read through about 12 posts here and tried to make sense of the fact that most of these use some form of $.post('getuser.php'to send the variable over to the new PHP page, but the example from w3schools does not do this. On the initial page, my dropdown is populating fine from my database, and the value I select is being passed into the JavaScript function. I check this with alert(str);, but from there, it doesn't ever seem to get to the second PHP page. I tried testing that it came over using echo $q ;, but that comes up as empty.
What am I doing wrong that is causing the variable that the JavaScript function captures to not be passed over to the second PHP page?
From what I can see, I am following the instructions on the tutorial just fine.
$.post('getuser.php' This syntax is exclusive to a javascript library called jQuery. Furthermore, $q is not an integer it is a string considering the DB query you perform initially, so why are you wrapping $_GET['q'] with intval()?
When I am building 2 dropdowns filling them from the database, the second dropdown is created when a value is picked from the first dropdown. But then, when I select an option in the second, my ajax is being executed. But when I have only one value in the second dropdown, it won't work. Even if I call the javascript function manualy.
The 2nd dropdown:
<?
include ('../dbconnect.php');
$query = "CALL get_projects(".$userid.",".$q.")";
$result = mysql_query($query);
$countprojects = mysql_num_rows($result);
if ($countprojects != 0){
echo '<select class="form-control" onchange="showContent(this.value)">'."\n";
if ($countprojects > 1){
echo "<option value='none' selected>Select project</option>";
}
while($rowprojecten = mysql_fetch_assoc($result)){
echo '<option value='.$rowprojecten['projectID'].'>'.$rowprojecten['projectname'].'</option>';
$lastvalue = $rowprojecten['projectID']; // see below why i did this
}
echo '</select>';
?>
the javascript function I wrote/copied:
function showContent(str)
{
if (str=="")
{
document.getElementById("project").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("project").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","./includes/ajax/getcontent.php?q="+str,true);
xmlhttp.send();
}
The phpfile what is called from this javascript:
<?
$q = intval($_GET['q']);
include ('../dbconnect.php');
$query = "CALL get_project(".$userid.",".$q.")";
$return = '<div id="project">';
$return .= $query;
$return .= '</div>';
echo $return;
mysql_close($con);
?>
Why do I see the div 'project' change when I select one, but does'nt it change when it is created?
I tried to call the function manualy with adding this to the first php file. But it also doesn't work.
if ($countprojects == 1){
echo '<script type="text/javascript">
showContent('.$lastvalue.')
</script>';
}
sorry for my bad english, I hope you can help me solve this.
This is because there is only one option in your second drop down list. you cannot fire change event if there is only on or zero options in drop down list. what you can do is add this code where your first Ajax call get fired when selection changes. and place your second Ajax call in inside below code.
if ($('#selectproject').children().length == 1) {
// make sure you have imported latest jquery. if not add this inside HTMl head : <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
var selectedProject = $('#selectproject').children()[0].value;
showContent(selectedProject); // i hope this is the function you are calling when executing. if not please replace your function call here.
}
I am fetching live value i.e. ftse from yahoo finance, using ajax and php.
I want to store all value in an array format and want to compare last 2 recently updated values.
following is my javascript:
<script>
function loadXMLDoc()
{
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("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ftse.php",true);
xmlhttp.send();
}
setInterval(loadXMLDoc,1000);
</script>
following is my php code.
<div id="myDiv">
<?php
// Setup Variables
$stockList = "^ftse";
$f = "l1";
$host = "http://finance.yahoo.com/d/quotes.csv";
$requestUrl = $host."?s=".$stockList."&f=".$f."&e=.csv";
// Pull data (download CSV as file)
$filesize=2000;
$handle = fopen($requestUrl, "r");
$raw = fread($handle, $filesize);
fclose($handle);
// Split results, trim way the extra line break at the end
$quotes = explode("\n\n",trim($raw));
foreach($quotes as $quoteraw) {
$quoteraw = str_replace(", I", " I", $quoteraw);
$quote = explode(",", $quoteraw);
// output the first element of the array, the Company Name
}
echo "<br><center><font size='30' color='green'>".$raw."<br>";
?>
</div>
following is my ftse.php code.
<?php
// Setup Variables
$stockList = "^ftse";
$f = "l1";
$host = "http://finance.yahoo.com/d/quotes.csv";
$requestUrl = $host."?s=".$stockList."&f=".$f."&e=.csv";
// Pull data (download CSV as file)
$filesize=2000;
$handle = fopen($requestUrl, "r");
$raw = fread($handle, $filesize);
fclose($handle);
// Split results, trim way the extra line break at the end
$quotes = explode("\n\n",trim($raw));
foreach($quotes as $quoteraw) {
$quoteraw = str_replace(", I", " I", $quoteraw);
$quote = explode(",", $quoteraw);
// output the first element of the array, the Company Name
}
echo "<br><center><font size='30' color='green'>".$raw."<br>";
?>
Problem is if the value is smaller then should be printed in red and if greater then in green color.
There's no property color on the element. You want to set a style to set the color to green, so you would write:
echo "<br><center><font size='30' style='color=green'>".$raw."<br>";
Ideally you wouldn't do this because it just pollutes the DOM. Annotate with a class:
echo "<br><center><font size='30' class='up'>".$raw."<br>";
echo "<br><center><font size='30' class='down'>".$raw."<br>";
Then in your CSS file you just have:
.up {
color: green
}
.down {
color: red
}
While you are at it, also move the font size and other style decorations to the CSS.
I hope this helps.
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.
I am wondering to find a solution for my dynamic select list of cities, now I am successfully populated the cities but now unable to post the selected city to database.
here is php file:
<html>
<head>
<script type="text/javascript" src="show_cities.js"> </script>
</head>
<body>
<?php
session_start;
//library
include("conn.php");
?>
<form enctype='multipart/form-data' action='posting_process.php' method='post'>");
<!-- **************************** Country select list ********************** -->
Country:
<select name="country" onChange="showCities(this.value)">
<?php $sql = 'SELECT country_no, country_name FROM country '.'ORDER BY country_no';
$rs = mysql_query($sql);
echo "<option value='0'>"."Select a Country"."</option>\n ";
while($row = mysql_fetch_array($rs))
{
echo "<option value=\"".$row['country_no']."\">".$row['country_name']."</option>\n ";
}
?>
</select>
City: <div id="txtCity" class="city_no">
<input type=submit name=action value=Post>
</body>
</html>
here is javascript: show_cities.js
// JavaScript Document
/* <script type="text/javascript"> */
function showCities(str)
{
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("txtCity").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","get_cities.php?q="+str,true);
xmlhttp.send();
}
/* </script> */
here is php file: get_cities.php
<?php
session_start;
//library
include("conn.php");
$q=$_GET["q"];
$sql="SELECT * FROM city WHERE country_no = ".$q;
$result = mysql_query($sql);
echo "<select name='city'>";
while($row = mysql_fetch_array($result))
{
echo "<option value=\"".$row['city_no']."\">".$row['city_name'] . "</option>\n";
}
echo "</select>";
?>
I don't know how to mention the following which return / display the city
regards:
Why don't you use the jQuery Ajax to send the data to the backend php code and receive the response.
Your php code seems fine, I would suggest to use the following mechanism to work with ajax.
Please add id as "countrylist" to your country list in the front end html page.
And use the following code instead of your javascript for ajax calls.
$(function (){
$('#countrylist').change(function() {
var sel_val=$("#countrylist").val();
$.ajax({
url: 'get_cities.php?q='+sel_val,
success: function(data) {
$('#txtCity').html(data);
}
});
});
});
Also make sure you have added the jquery libraries before adding this javascript code.
Hope this helps.
Thanks