How to pass two php variables in JavaScript function - javascript

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

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.

getting data from query sql database to 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); ?>

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

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

Categories

Resources