window.XMLHttpRequest combine with script .change - javascript

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.

Related

How to autofill textbox from suggestion list?

I am a beginner in jquery and ajax. I'm trying to get google like suggestion while typing in the textbox. However I've tried for hours and still can't get to view the suggestion as a list and autofill the textbox while selecting text from the list. Here is what I've tried so far.
The php file-
$conn = new mysqli("host", "user", "pass", "database");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT data1, data2 FROM table";
$result = $conn->query($sql);
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
while ($row = $result->fetch_assoc()){
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($row as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
}
else {
$hint .= "</br> <a href='#'>$name </a>";
}
}
}
}
}
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
The Javascript code-
function showHint(str) {
if (str.length == 0) {
document.getElementById("livesearch").innerHTML = "";
document.getElementById("livesearch").style.border="0px";
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 (this.readyState==4 && this.status==200) {
document.getElementById("livesearch").innerHTML=this.responseText;
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
}
xmlhttp.open("GET","getdb.php?q="+str,true);
xmlhttp.send();
}
The html file-
<p><b>Start typing a name in the input field below:</b></p>
<div>
<form>
First name: <input type="text" onkeyup="showHint(this.value)">
<div id="livesearch">
</div>
</div>
Another problem is the first suggestion from the list isn't appearing as a link like rest of the suggestion.
Screenshot
How can I list my suggestions properly and how can I can fill the textbox when a user selects text from the list. Pl's help!
Solved it myself few days ago. Here is what the code looks like so far.
The php file-
$q = $_REQUEST["q"];
//$hint = "";
$sql = "SELECT data FROM tables WHERE Firstdata LIKE '%" . $q . "%' OR Lastdata LIKE '%" . $q ."%'";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()){
$FirstData =$row['Firstdata'];
$LastData =$row['Lastdata'];
$ID=$row['ID'];
//-display the result of the array
if ($q !== "") {
echo "<li class="."list-group-item".">"
. "<a href=\"phpfile.php?id=$ID\">" .
$FirstData ." ". $LastData . "</a>
</li>";
}
}
The Javascript code-
function showHint(str) {
if (str.length == 0) {
document.getElementById("livesearch").innerHTML = "";
document.getElementById("livesearch").style.border="0px";
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 (this.readyState==4 && this.status==200) {
document.getElementById("livesearch").innerHTML=this.responseText;
document.getElementById("livesearch").style.border="0px solid";
}
}
xmlhttp.open("GET","php/ajaxphpfile.php?q="+str,true);
xmlhttp.send();
}
The html file-
<input type="text" class="search-query form-control" onkeyup="showHint(this.value)" id="type" name="name"placeholder="Search" />
<button type="submit" name="submit" value="oldsearch" class="btn btn-danger" type="button"></button>
<div id="livesearch"></div>

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

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

How to pass two php variables in JavaScript function

This is my code for fetching values from DB in a Table.
After fetching values I'm simply taking the ID of user in function to Activate and Deactivate that user.
<?php
$sql = "SELECT * FROM registration";
$result = mysqli_query($con, $sql);
while ($test = mysqli_fetch_array($result)) {
$id = $test['id'];
$status = $test['status'];
echo "<tr align='center'>";
echo"<td><font color='black'>".$test['username']."</font></td>";
echo"<td><font color='black'>".$test['firstname']." " .$test['lastname'] .
"</font></td>";
echo"<td><font color='black'>" . $test['status'] . "</font></td>";
echo"<td><a id='link' onclick=\"activate(" . $id . ");\">Activate</a></td>";
echo"<td><a id='link' onclick=\"deactivate(" . $id . ");\">Deactivate</a></td>";
echo "</tr>";
}
?>
Now, this is my AJAX code for activate()
function activate(item)
{
var id = item;
if (confirm("Do you wants to Activate user"))
{
$("#wait").css("display", "block");
var id = item;
var status = status;
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)
{
window.location.reload();
}
}
xmlhttp.open("GET", "php/update_act.php?id=" + id + "&req=activate", true);
xmlhttp.send();
}
}
I want to write or update the activate function so that,
I will get the current status of the user so that I'll check if the User is already Activated or not.
And if user is already Activated it should prompt me that this user is already activated else I should be able to Activate the User.
I assume you want to pass $status in the function as well so you can do something as
In Php code
echo '<td><a id="link" onclick="activate(\''.$id.'\',\''.$status.'\');">Activate</a></td>';
And you can change the JS function signature as
In Javascript
function activate(yourItem,uStatus){ }

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

Categories

Resources