getting data from query sql database to javascript - javascript

I have a problem with my code.
case like this:
I have a dropdown, if selected "personal" it appeared the new dropdown that contains the data that is retrieved from a database query, if selected "public", then the dropdown disappear.
HTML code like this:
<select name="use" class="dropdown" id="sender" onChange='changeSend()'>
<option value=1>Public</option>
<option value=0>Personal</option>
</select>
<div id='send2'></div>
Query like this:
<?php
$query = mysql_query("select * from data where id_user = '$id_user' order by date asc");
$i = 0;
$id = array();
$name = array();
while($data = mysql_fetch_array($query)){
//id from result database query
$id[$i] = $data['id'];
//name from result database query
$name[$i] = $data['name'];
$i++;
}
?>
JavaScript code like this:
function changeSend() {
var selectBox = document.getElementById("sender");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
if (selectedValue==0) {
$('#send2').html("<select class='dropdown'><option value='-id from result database-'>-name from result database query-</option></select>");
} else {
$('#send2').html('');
}
}
I dont know how to send value/result ($id[0],$name[0],$id[1],$name[1], etc..) to javascript code(value and name in select options).

In javascript you have to make an ajax call to your php file:
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("send2").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","yourFile.php",true);
xmlhttp.send();
And in your php file you have to echo your data in JSON format:
echo json_encode(array('id'=>$id,'name'=>$name));
UPDATE
in your case use the following code:
(not tested)
php code:
<?php
$query = mysql_query("select * from data where id_user = '$id_user' order by date asc");
$i = 0;
$options = array();
while($data = mysql_fetch_array($query)){
$options[$data['id']] = $data['name'];
}
echo json_encode($options);
?>
javascript code:
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){
var response = JSON.parse(xmlhttp.responseText);
var select = '<select class='dropdown'>';
for( var index in response ){
select = select + "<option value='"+ index +"'>"+response[index]+"</option>";
}
select += "</select>";
document.getElementById("send2").innerHTML= select;
}
}
function changeSend() {
var selectBox = document.getElementById("sender");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
if (selectedValue==0) {
xmlhttp.open("GET","yourFile.php",true);
xmlhttp.send();
}
else {
$('#send2').html('');
}
}
USING jQuery
javascript code:
function changeSend() {
var selectBox = document.getElementById("sender");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
if (selectedValue==0) {
$.get("yourFile.php", function(data){
var response = JSON.parse(data);
var select = '<select class='dropdown'>';
for( var index in response ){
select = select + "<option value='"+ index +"'>"+response[index]+"</option>";
}
select += "</select>";
$("#send2").html(select);
});
}
else {
$('#send2').html('');
}
}

The best way would probably be with an ajax call, anyway if you are declaring the script in the same page with the php, you can json encode the array with the options so that you will be able to access it into the javascript, like this:
var optionIds = <php echo json_encode($id); ?>
var optionNames = <php echo json_encode($name); ?>

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>

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.

Using Php, mySql, ajax, (xmlhttp) and JS,how can i create a php multidimensional send it to JS and use it?

I looked a lot on the internet and wasn't able to find the answer i need, so here i come to you.
What i have : A database which look like this :
name latitude longitude
---- --------- ----------
foo 13.323 -51.356
foo 54.698 2.487
What i want to do : I need to retrieve the latitude and longitude from a mysqli request done with php and use it in a function that i defined.
My problem : I'm trying to use xmlrequest but it apparently doesn't work.
The code : JS :
var selI = document.getElementById("nameIti");
selI.onchange = function(){
var val = this[this.selectedIndex].getAttribute("value");
showMark(val);
}
function showMark(str){
var xhr;
if(str==""){
return;
}
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}
else{
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange=function(){
if(xhr.readyState==4 && xhr.status ==200){
var object = JSON.parse(xhr.responseText);
for(var a in object){
newMark(v['lat'], v['lng']);
document.getElementById("pi").innerHTML=JSON.parse(xrh.responseText); // This is a test to display any kind of result.
}
}
}
xhr.open("GET", "getpos.php?q="+str, true);
xhr.send();
}
PHP :
<?php
$nom = $_GET['q'];
include("connexion.php");
$con = connect_LIF4();
$req1= "SELECT Latitude, Longitude FROM etape LEFT JOIN itineraires ON NomLieu=nomEtape WHERE nomIti LIKE '%$nom%'";
$result1 = mysqli_query($con, $req1);
$data = array();
while($row = mysqli_fetch_array($result1){
$data['lat'] = $row['Latitude'];
$data['lng'] = $row['Longitude'];
$resp[] = $data;
}
echo json_encode($resp);
mysqli_close($con);
?>
I tried to use newMark(lat, lng)(Which i coded and works fine) with random values, in showMark outside the onreadystatechange and it works, but i need to use it with the values retrieved from the php.
One problem with your PHP is that
while($row = mysqli_fetch_array($result1){
is missing the second brace. It should be:
while($row = mysqli_fetch_array($result1)){
Also the URL in the ajax request should be the full URL, not just getpos.php
Thirdly you have written xrh.responseText (should be xhr).
Basically there's loads of syntax errors in your code - you should use the javascript console to debug the front end ones, and PHP logging or error display for the back end ones. You should only need help here once you've debugged all obvious syntax errors.
EDIT - below is a working example (although I haven't done the MySQL part)
JS + HTML:
<span id='pi'></span>
<select id='nameIti'>
<option value='foo'>foo</option>
<option value='bar'>bar</option>
</select>
<script>
function newMark(lat,lng) {
console.log(lat);
console.log(lng);
}
var selI = document.getElementById("nameIti");
selI.onchange = function(){
var val = this[this.selectedIndex].getAttribute("value");
showMark(val);
}
function showMark(val){
var str=val;
var xhr;
// if(str==""){
// return;
// }
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}
else{
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange=function(){
if(xhr.readyState==4 && xhr.status ==200){
var result = JSON.parse(xhr.responseText);
console.log(result);
for(var a in result){
newMark(result[a]['lat'], result[a]['lng']);
document.getElementById("pi").innerHTML = result[a]['lat'] + ', ' + result[a]['lng'];
}
}
}
// xhr.open("GET", "getpos.php?q="+str, true);
xhr.open("GET", "getpos.php?q="+str, true);
xhr.send();
}
</script>
PHP:
<?php
$nom = $_GET['q'];
$data = array();
if($nom == 'foo') {
$data['lat'] = '5.12';
$data['lng'] = '0.34';
$resp[] = $data;
}
else if($nom == 'bar') {
$data['lat'] = '2.34';
$data['lng'] = '1.34';
$resp[] = $data;
}
echo json_encode($resp);
?>

Ajax is not working on my customize component in joomla

I'm having problem on my joomla article which i customize the code with Sourcerer.
Here is some of my example code for the ajax javascript:
<script type="text/javascript">
function showBox1(element) {
document.getElementById('hideBox1').style.display = "";
if (element == "")
{
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", "home/matedis/public_html/joomla/Add_Edit_Intake/getuser.php?q=" + element, true);
xmlhttp.send();
}
</script>
The code for passing the value to the function is here:
<?php
// Get default database object
$db = JFactory::getDBO();
// Get a new JDatabaseQuery object
$query = $db->getQuery(true);
// Build the query
$query->select($db->quoteName('campusid'));
$query->from($db->quoteName('campus'));
$query->where($db->quoteName('collegeid') . '=' . $db->quote('1'));
// Set the query for the DB oject to execute
$db->setQuery($query);
// Get the DB object to load the results as a list of objects
$results = $db->loadObjectList();
if ($results) {
foreach ($results as $result) {
echo "<label class='option block spacer-t10'>";
echo "<input type='radio' id ='campusID' name='campusID' value='$result->campusid' onChange='showBox1(this.value)'><span class='radio'></span>";
echo $result->campusid;
echo '</label>';
}
} else {
echo 'Error';
}
?>
Here is my getuser.php code:
<?php
$q = intval($_GET['q']);
define( 'JPATH_BASE', $_SERVER[ 'DOCUMENT_ROOT' ] ); // define JPATH_BASE on the external file
require_once( JPATH_BASE . DS . 'libraries' . DS . 'import.php' ); // framework
require_once( JPATH_BASE . DS . 'configuration.php' ); // config file
$db = JFactory::getDBO();
$sql="SELECT courseid FROM course WHERE campusid = '".$q."'";
// Build the query
$query->select($db->quoteName('courseid'));
$query->from($db->quoteName('course'));
$query->where($db->quoteName('campusid').'='. $db->quote($q)); //This later must change to retrieve id from current user
// Set the query for the DB oject to execute
$db->setQuery($query);// Get the DB object to load the results as a list of objects
$results = $db->loadObjectList();
if($results){
foreach($results as $result)
{
echo $result->courseid;
}
}
else{ echo 'Error';}
?>
Is there any mistake i had made? Because it does not show up the output i want which i refer the code from here http://www.w3schools.com/php/php_ajax_database.asp. Sorry if any inconvenience cause because i still new to joomla and php ajax.
xmlhttp.open("GET","home/matedis/public_html/joomla/Add_Edit_Intake/getuser.php?q="+element,true);
This is real path of public_html? No..

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){ }

Categories

Resources