onchange in onchange won't work - javascript

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

Related

Pass a current page's php variable through to XMLHttpRequest2 (i.e. $user_id)

I am trying to figure out if a current page's php $var can be passed through to the XMLHttpRequest2. The file that is being called is located outside of the views(where the current php page is located) folder in the /assets/js directory. I am using CodeIgniter as well. Trying to pass the $user_id along to use in a SQL query in side the XMLHttpRequest2 requested file.
publication_call.php (current file)
<form>
<input type="hidden" id="someid" value="<?= $idz ?>"/>
<?php
echo form_label('Validation: (Enter Publication keywords, Matches will appear in Dropdown > )');
echo form_label('Matching<br>Publications:');
?>
<select name="matched_pub" id="matched_pub"></select>
</form>
<script>
jQuery(function($){
//still want to bind the change event
$('#matched_pub').bind('change', function(){
$('#title').val($('#matched_pub option:selected').text());
});
$('#validation').keyup(function() {
showKeywords( $('#validation').val() );
document.getElementById('matched_pub').style.display='block';
});
});
</script>
<script>
function showKeywords(str)
{
if (document.getElementById("matched_pub")) {
if (str.length==0)
{
document.getElementById("matched_pub").innerHTML="";
document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp2=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange=function()
{
if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
{
document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
}
}
xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str,true);
xmlhttp2.send();
}
}
</script>
searchwords.php (requested/external file)
<?php
$user = 'root';
$pass = 'root';
$db = 'hey_there';
$host = 'localhost';
$conn = mysql_connect($host, $user, $pass);
$db_selected = mysql_select_db($db, $conn);
//trying to display special chars
mysql_query("set names 'utf8'");
if(!$db_selected) {
echo 'broke';
}
//echo 'db connected';
$q = $_GET["b"];
//explode and parse $q into all the fragments separated by spaces and do full text search +word1 +word2 +word3, this will ignore HTML tags as it ignores word order, will also solve the middle initial problem [db setup is not compatible with full text search, but can do likes per word, less efficient, but how it must be done]
$queryWords = explode(' ', $q);
//for services query, explode the query into words and search for each separately
$query = "SELECT DISTINCT(pub_title)
FROM teacher_publications
JOIN users ON teacher_publications.user_id = users.id
WHERE keywords IS NOT NULL
AND pub_title IS NOT NULL
AND teacher_publications.user_id = 103 <-- $var will go here
";
$queryServicesLoop = '';
$queryServicesEnd = ' ORDER BY pub_title ASC';
//loop through all words in string
foreach($queryWords as $queryWord) {
$queryServicesLoop .= " AND (keywords LIKE '%{$queryWord}%')";
}
$queryServices = $queryServices.$queryServicesLoop;
$queryServices = $queryServices.$queryServicesEnd;
$resultServices = mysql_query($queryServices);
$services ='';
if(mysql_num_rows($resultServices) > 0){
while($rowServices = mysql_fetch_assoc($resultServices)) {
$services .= '<option value="' . $rowServices['pub_title'] . '">' . $rowServices['pub_title'] . '</option>';
}
}
if( mysql_num_rows($resultServices) == 0 )
{
echo '<option value="">Your search failed to find any matching results.</option>';
}
else
{
echo '' . $services . '';
}
/* ==============================
Edited Code
============================== */
publication_call.php (current file)
<input type="hidden" id="someid" value="<?= $user_id ?>"/>
<script>
function showKeywords(str)
{
if (document.getElementById("matched_pub")) {
if (str.length==0)
{
document.getElementById("someid");
document.getElementById("matched_pub").innerHTML="";
document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp2=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange=function()
{
if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
{
document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
}
}
xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str+"&user_id="+document.getElementById('someid'), true);
// xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str,true);
xmlhttp2.send();
}
}
</script>
searchwords.php (requested/external file)
$usr = $_GET["user_id"];
$query = "SELECT DISTINCT(pub_title)
FROM teacher_publications
JOIN users ON teacher_publications.user_id = users.id
WHERE keywords IS NOT NULL
AND pub_title IS NOT NULL
AND teacher_publications.user_id = ".$usr."
";
You can put $user_id inside of a hidden input field, and using Javascript, read the value of it to use in your Ajax request
You can do it like this:
<input type="hidden" id="someid" value="<?= $user_id ?>
And then after you've done that, you can get the value by doing this:
document.getElementById('someid'); using plain Javascript or $('#someid').value(); if you use jquery
This will get you the user ID value which you can then use in the request.
Like so:
xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str+"&user_id="+document.getElementById('someid').value, true);
Replace your current xmlhttp2.open with the one above
Now you can access the value of user ID in $_GET['user_id'] in the requested file.

Passing JavaScript variable to PHP through AJAX

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

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.

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