Passing JavaScript variable to PHP through AJAX - javascript

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()?

Related

display value in two text box using xmlhttprequest object?

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"];

Populate a dropdownlist after selecting a value from a different list using Ajax

I have 2 dropdownlists. The first contains Car Brands like seat,bmw,audi etc.
The second i want to contain the models from the specific Brand the user selected in list 1.
In my current code state, when i select A brand from List 1 the second list is getting Filled with the same elements from List 1. So I Have a Duplicated List with exactly the same records.
The main file:
<?php
defined( '_JEXEC' ) or die( 'Restricted access' );
$css='css.css';
$doc = JFactory::getDocument();
$doc->addStyleSheet('modules/mod_alpha_table/assets/'.$css);
$db= JFactory::getDbo();
$ready = $db->getQuery(true);
$query="SELECT category_name,virtuemart_category_id from uhhu_virtuemart_categories_el_gr INNER JOIN uhhu_virtuemart_category_categories ON uhhu_virtuemart_categories_el_gr.virtuemart_category_id = uhhu_virtuemart_category_categories.category_child_id WHERE uhhu_virtuemart_category_categories.category_parent_id = 105";
$db->setQuery($query);
$options=$db->loadObjectList();
$model="";
?>
<script>
function showUser(str) {
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("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","query.php?q="+str,true);
xmlhttp.send();
}
</script>
<div class="srchcr">
<div class="srch">
<form name="searchcar">
<form>
<select onchange="showUser(this.value)" name="cats">
<option value="none">Select Make</option>
<?php foreach ($options as $row) {
echo '<option value=' . $row->virtuemart_category_id . '>'. $row->category_name . '</option>';
}
?>
</select>
<select name="subcats" id="txtHint">
<option value="none">Select Model</option>
</select>
</form>
</div>
</div>
query.php file :
<?php
$doc = JFactory::getDocument();
$db= JFactory::getDbo();
$ready = $db->getQuery(true);
$q = htmlspecialchars($_REQUEST['q']);
$query='SELECT category_name,virtuemart_category_id from #__virtuemart_categories_el_gr INNER JOIN #__virtuemart_category_categories ON #__virtuemart_categories_el_gr.virtuemart_category_id = #__virtuemart_category_categories.category_child_id WHERE #__virtuemart_category_categories.category_parent_id = $q';
$db->setQuery($query);
$options=$db->loadObjectList();
foreach ($options as $row) {
echo '<option name='. $q .' value=' . $row->virtuemart_category_id . '>'. $row->category_name . '</option>';
}
?>
Query tested at phpmyAdmin and working fine. It seems somehow the first query is getting executed twice instead of the query inside the $query.php file. I also tried include the code from the external file inside the main but its the same story.I also renamed the second $query as $query2 and executed $query2 but nothing changed.Could someone enlight me on what is going wrong ?
EDIT:
After a break and bit more debugging i think that this is where the problem start:
xmlhttp.open("GET","query.php?q="+str,true);
It seems like the request for some reason, instead of query.php is sent at index.php and triggers the same query again.I added die(); at the start of query.php and nothing happened.So may i need to use a joomla syntax or something ?
Looks like you have a copy-paste-error here. When comparing the creation of your option-tags, I see the exact same code for both the brands and the models, meaning query and dom-creation.
So basically, your code is perfectly fine. But in your query.php you are creating this same brand-list again ;)
Some general comments on your code:
Do not create your own implementation of the XmlHttpRequest, use a library like jquery or mootools
You are vulnerable to sql-injections when using values from userland ($_REQUEST['q']) without sanitizing them. See this question on stackoverflow: Best way to prevent SQL injections in Joomla
if it is true that you gather the information for your 2 lists with the same query, try to implement your logic (user selects brand, model-list is updated) through javascript. So your main.php still creates the brand-list, but renders all model-lists as well. These are shown/hidden when the user changes the brand accordingly. This would avoid the additional roundtrip to the server each time a brand is selected.

onchange in onchange won't work

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.
}

dynamic select list AJAX and insertion in database table through posting form

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

window.XMLHttpRequest combine with script .change

I have a problem with combinning two scripts.
Fisrt script is working perfectly and taking stuf from mysql:
<script type="text/javascript">
function showUser(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','includes/test-search.php?q='+str,true);
xmlhttp.send();
}
</script>
The second one is working perfectly and it's simple script for inserting data after change:
<script type="text/javascript">
$("document").ready(function(){
$("#selection").change(function () {
$("#someDivName").html( $("#selection option:selected").val() );
});
});
</script>
now the hole point is to combine them.
It's look like, when I load the site it don't have id selection and second script stops but after taking data from php and mysql file test-search.php the missing id selection is on site but the first script is not checking if id selection apear and don't work.
The php code:
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("table", $con);
$sql="SELECT * FROM prod_models WHERE prod_main_group_id = '".$q."'";
$result = mysql_query($sql);
echo '
<select id="selection" name="prod_main_group_id" onchange="change_val()">
<option value="">Wybierz produkt</option>
';
while($row = mysql_fetch_array($result))
{
echo '<option value="'.$row['id'].'">';
echo $row['product_name'] . "</option>";
}
echo "</select>
";
mysql_close($con);
?>
Code to display changed script:
<input type="text" id="someDivName" value="" />
if any one can help with solving the problem will be realy nice.
Thx i'm waiting for it now and trying to solve this for my self but now I don't have other ideas for it.

Categories

Resources