Opening modal from dropdown list to add client - javascript

Linked to my prior post yesterday on how to have a value of a selector change the behaviour of my javascript, I run into trouble opening a modal window.
The idea is that if "add client" is selected from the first dropdown list, instead of dynamically populating the second dropdown list with "projects", a modal window pops-up to allow the user to add a client.
I have index3.php:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include 'dbconnect.php';
?>
<script type="text/javascript" src="scripts/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
function fetch_select(val)
{
if (val != "add_client")
{
$.ajax({
type: 'post',
url: 'fetch_data.php',
data: {
get_option:val
},
success: function (response) {
document.getElementById("projects").innerHTML=response;
}
});
}
else
{
//code to open modal below
success: function overlay() {
el = document.getElementById("overlay");
el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
}
//code to open modal above
}
}
</script>
<?php
echo "<table>";
echo "<form action='index3.php method='post'>";
echo "<tr>";
echo "<td>";
echo "<select name='client' id='client' onchange='fetch_select(this.value);'>";
echo "<option>Name of Firm</option>";
$select = mysqli_query($Verbinding,"SELECT client FROM clients GROUP by client");
while ($row = mysqli_fetch_array($select))
{
echo '<option value="'.$row['client'].'">'.$row['client'].'</option>';
}
echo "<option value='add_client'>Add Client</option>";
echo "</select>";
echo "</td>";
echo "<td>";
echo "<select name='project' id='projects'>";
echo "<option>Select Project</option>";
echo "</select>";
echo "</td>";
echo "</tr>";
echo "</table>";
echo "</form>";
echo "<div id='overlay'>";
echo "<div>";
echo "<p>Content of modal window.</p>";
echo "</div>";
echo "</div>";
?>
The stylesheet modal.css works and is included through dbconnect.php and contains:
modal.css
#overlay {
visibility: hidden;
position: absolute;
left: 0px;
top: 0px;
width:100%;
height:100%;
text-align:center;
z-index: 1000;
}
#overlay div {
width:300px;
margin: 100px auto;
background-color: #fff;
border:1px solid #000;
padding:15px;
text-align:center;
}
Hope anyone can help, thanks and with kind regards, Paul

success: function overlay() {
el = document.getElementById("overlay");
el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
}
is not doing anything. You've confused the "success" callback of the ajax call (which defines an option, containing a function to run later) with regular everyday code.
Assuming your modal has its id defined as "overlay", then you can just do:
else
{
//code to open modal below
el = document.getElementById("overlay");
el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
//code to open modal above
}

Related

Why does reload specific section not work?

I've tried different codes, but the codes always not working. I want to reload just the specific section every 5 seconds, not reloading the whole page. It's important not to refresh the whole page, because it includes an chat function. If I would reload the whole page, people can't enter text without loosing it every 5 seccond. Like I said, I've tried some codes from stackOverflow but somehow they don't work for me.
Here's my code
<script type="text/javascript">
$(document).ready(function(){
setInterval(function(){
$("#context").load(window.location.href + " #context" );
}, 5000);
});
</script>
<--variables explained --->
$fid = $_GET['fid']
$username = $_SESSION['username']
$db :
$servername = "localhost";
$dbname = "psychopath";
$username = "root";
$password = "";
try{
$dsn = "mysql:host=" . $servername . ";dbname=" . $dbname;
$db = new PDO($dsn, $username, $password);
echo "";
}catch(PDOException $e){
echo $e.getMessage();
}
<--- variables END ----->
$display_messages = $db->prepare("SELECT * FROM mychat_from WHERE (user_to_name = ? OR userfrom_name = ?) AND (user_to_id = ? OR userfrom_id = ?)");
$display_messages->execute([$username , $username, $fid, $fid]);
while($row=$display_messages->fetch(PDO::FETCH_ASSOC)){
$userfrom = $row['userfrom'];
if($userfrom != $username){
$messagefrom2 = $row['message_from'];
$messagefrombreak2 = wordwrap($messagefrom2, 27, "\n", true);
?>
<?php
?><section id="context" name="context"><?php echo '<b> '.$userfrom.'</b>said:<br>';
echo "<section style='background: black; float: left; margin-left: 5px; border-radius: 7px; color: white;'> <font style='float: left;'> ".$messagefrombreak2."</font></section>";?>
</section>
<?php echo "<br><br>";
?>
And here is full code:
<!-- end snippet -->if(isset($_GET['fid'])){
$fid = $_GET['fid'];
?>
<section>
<section>
<?php
$get_friend = $db->prepare("do stuff");
$get_friend->execute([$fid]);
while($row=$get_friend->fetch(PDO::ROW STUFF)){
}
?>
</section>
<section>
<?php
$username = $_SESSION['username'];
$get_id = $db->prepare("do stuff");
$get_id->execute([$fid]);
while($row=$get_id->fetch(ROW STUFF)){
$get_your_id = $db->prepare("do stugg");
$get_your_id->execute([$username]);
while($row=$get_your_id->fetch(ROW STUFF)){
$display_messages = $db->prepare("DO STUFF");
$display_messages->execute([$your_id, $your_id, $fid, $fid]);
while($row=$display_messages->fetch(DO STUFF)){
$userfrom = $row['userfrom'];
if($userfrom != $username){
$messagefrom2 = $row['message_from'];
$messagefrombreak2 = wordwrap($messagefrom2, 27, "\n", true);
?>
<?php
?><div id="container" name="container"><div id="context" name="context"><?php echo '<b> '.$userfrom.'</b>said:<br>';
echo "<section style='background: black; float: left; margin-left: 5px; border-radius: 7px; color: white;'> <font style='float: left;'> ".$messagefrombreak2."</font></section>";?>
</div></div>
<?php echo "<br><br>";
?>
<script type="text/javascript">
$(document).ready(function(){
setInterval(function(){
$("#context").load(window.location.href + " #container" );
}, 5000);
});
</script>
<?php
}else{
$messagefrom = $row['message_from'];
$messagefrombreak = wordwrap($messagefrom, 27, "\n ", true);
echo "<font style='float: right;'><b>You </b>said: </font><br>";
echo "<section style='background: #960505; float: right; margin-right: 5px; border-radius: 7px; color:
white;'><font style='float: right;'> ".$messagefrombreak." </font></section><br><br>";
}}}}
?>
</section>
use ajax and json
ajax to make a call to server within the page
json little simple format
use setInterval
like
var myVar = setInterval(my_func, 5000);
my_func is a function that will hold ajax action. and do what do you need

Autocomplete Arrow Key Scroll

I am making a Ajax driven live search . But now I want to click the dropdown list to fill the html textbox. How can I modify my codes to include a function where the user can scroll through the results list using the up/down arrow keys. Here is the JavaScript code.
<script type="text/javascript">
function fill(Value) {
$('#name').val(Value);
$('#display').hide();
}
$(document).ready(function() {
$("#name").keyup(function() {
var name = $('#name').val();
if (name == "") {
$("#display").html("");
} else {
$.ajax({
type: "POST",
url: "ajax.php",
data: "name=" + name,
success: function(html) {
$("#display").html(html).show();
}
});
}
});
});
and here is the code in ajax.php page
if(isset($_POST['name'])) {
$name=trim($_POST['name']);
$query=mysqli_query($con,"SELECT * FROM mobile WHERE name LIKE '%$name%' LIMIT 0,5");
echo "<ul>";
while($query2=mysqli_fetch_array($query))
{ ?>
<div class="ajaxcontainer">
<li onclick='fill("<?php echo $query2[' name ']; ?>")'>
<a href="preview.php?id=<?php echo $query2['name']; ?>">
<div class="ajaximage">
<img src="<?php echo $query2['photo'];?>">
</div>
<div class="ajaxh1">
<h1><?php echo $query2['name']; ?></h1>
</div>
</a>
</li>
</div>
<?php } } ?>
good news.. after working 3 hours.. i got the solution to ur problem. Checkout the solution. let me know if you have any problems in this solution.I
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<style type="text/css">
ul{
position: absolute;
top: 5px;
left: 36px;
list-style: none;
}
li{
border: 1px solid grey;
width: 202px;
margin: 0px;
}
input{
width:200px;
}
</style>
<script>
function showHint(str){
if(str=="" || !str){
$("ul").empty();
return;
}
$.ajax({
type: "GET",
url: "gethint.php",
data: "q="+str,
success: function(html) {
var names = html.split(",");
var listItems ="";
var dropDown =$("#dropDown");
dropDown.innerHTML="";
$("ul").empty();
names.forEach(name =>{
var li = document.createElement("li");
li.appendChild(document.createTextNode(name));
dropDown.append(li);
$("li").click(function(){
$("#txt1").val($(this).text());
});
});
}
});
}
</script>
<h3>Start typing a name in the input field below:</h3>
<form action="">
<div style="position:relative">
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)">
<ul id="dropDown"></ul>
</div>
</form>
</body>
</html>
This is my php file.
<?php
require("connection.php");
$sql ="SELECT name FROM users";
$a=array();
// OR $a=[];
$result=$conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$a[]=$row["name"];
//echo $row["name"];
}
}
else{
echo "No data to generate suggestions";
}
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
?>

Calling Javascript from a Form using Onsubmit

I am newbie in PHP and AJAX, and I am in trouble and don't know how to solve it.
I am creating this page that shows a recordset that resulted from a query.
There are 2 pages: getdata.php and phpajax.php. phpajax.php calls getdata.php via Javascript.
What I have done:
I manage to make it work by using button "Try it" (using static value)
What I want:
How to display the data properly using "Submit" button on a single click (ATM the data appears for a couple of seconds after I click Submit twice, then disappears because the page suddenly refreshes) ?
How to pass the value of SELECT and TEXT into fshowdata() using the Submit Button ?
How to pass the value of SELECT and TEXT into fshowdata() using the "Try It" Button ?
Here is the for the phpajax.php:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script>
function fshowdata(str1,date1) {
//alert("The form was submitted");
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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;
}
}
//document.getElementById("demo").innerHTML = str1 + " " + date1;
xmlhttp.open("GET","getdata.php?q="+str1+"&"+"t="+date1,true);
xmlhttp.send();
}
}
</script>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<p id="demo">Click the button to change the text in this paragraph.</p>
<?php
$con = mysql_connect('localhost','root','123');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb')or die('Could not select database');
$sql="SELECT DISTINCT(rides) FROM t_trx ORDER BY rides ";
$result = mysql_query($sql) or die('Query failed: ' . mysql_error());
echo "<form onsubmit='"."fshowdata(`some rides`,`a date`)"."' action='".""."'>";
echo "Choose Rides : "." "."<select id='"."rides"."' name='"."rides"."'>";
echo "<option value='"."ALL"."'>ALL</option>";
while($row = mysql_fetch_array($result)) {
echo "<option value='".$row["rides"]."'>".$row["rides"]."</option>";
}
mysql_free_result($result);
echo "</select>";
mysql_close($con);
echo "<input id='"."date2"."' type='"."TEXT"."' name = '"."date2"."'>";
echo "<input id='"."button1"."' type='"."SUBMIT"."' value = '"."SUBMIT"."'>";
echo "</form>";
echo "<button onclick='"."fshowdata(`ROLLER COASTER`,`18/07/2015`)"."'>";
echo "Try it";
echo "</button>";
?>
<br>
<div id="txtHint"><b>Data will be shown here...</b></div>
</body>
</html>
And for the getdata.php:
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<?php
$q = $_GET['q'];
echo $q;
$date_ = $_GET['t'];
echo $date_;
$con = mysql_connect('localhost','root','123');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb')or die('Could not select database');
$sql="SELECT * FROM t_trx WHERE rides = '".$q."' AND date1 = '".$date_."' LIMIT 10";
echo $sql;
$result = mysql_query($sql) or die('Query failed: ' . mysql_error());
echo "<table>
<tr>
<th>Rides</th>
<th>Number</th>
<th>Date</th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['Rides'] . "</td>";
echo "<td>" . $row['Number'] . "</td>";
echo "<td>" . $row['Date'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
</body>
</html>
Thanks guys. I appreciate your help...
use below code to skip refresh page
onsubmit="return fshowdata(`some rides`,`a date`)"
in the fshowdata function, you should return false.

How to pass a value from Codeigniter's form_hidden to javascript?

I want to pass the value of my form_hidden from the view to a javascript function.
VIEW:
<?php echo validation_errors(); ?>
<?php
$mode = (isset($is_editing))? 'disabled' : 'disabled';
$client_name = (isset($is_editing))? $clientcontent->client_name : NULL;
$process = (isset($is_editing))? 'Edit' : 'Add';
$form_action = (isset($is_editing))? 'client/update_client/' . $id : 'client/create_client';
?>
<style type="text/css">
.check_exists
{
margin-top: 4px;
margin-left: 9px;
position: absolute;
width: 16px;
height: 16px;
}
</style>
<?php echo form_open($form_action, 'id="frm" class="form-horizontal" style="margin: 0;"'); ?>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
<h4 class="modal-title"><?php echo $process ?> Client</h4>
</div>
<div class="span6" style="padding-top:20px;padding-bottom:10px;">
<!-- Project Content Fields -->
<div class="control-group">
<p class="control-label">Client Name*</p>
<div class="controls">
<?php echo form_input('client_name', $client_name, 'id="client_name" style="height: 30px;"'); ?><span id="client_verify" class="check_exists" ></span>
</div>
</div>
<?php echo form_hidden('old_name',$client_name); ?>
</div>
<?php echo form_close(); ?>
<script type="text/javascript">
$(document).ready(function()
{
check_client("#client_name", "<?php echo base_url(); ?>client/check_availability", "#client_verify", "#old_name");
})
// </script>
Javascript File:
function check_client( id, url, spanid, old)
{
var oldname = $(old).val();
$('body').on('keyup', id, function(){
if($(id).val().length >= 3)
{
var newname = $(id).val();
console.info("The new name is " + newname + ":old name is" + oldname);
$.ajax({
url : url,
data : {client_name : $(id).val()},
type : 'POST',
success : function(data){
if( data.is_available == 0 ){ // Here
//start fading the messagebox
$(spanid).css({ "background-image": "url('http://localhost/mapmces_3.4.2/assets/img/no.png')" });
$(spanid).attr( "title", "Already Exists" );
available = false;
}else if( data.is_available ){ // Here the json response
//start fading the messagebox
$(spanid).css({ "background-image": "url('http://localhost/mapmces_3.4.2/assets/img/yes.png')" });
$(spanid).attr( "title", "Available" );
available = true;
}else{
alert("Some error occured! Check Console");
console.error(data.reason);
}
}
});
}
else
{
$(spanid).css({ "background-image": "none" });
}
});
}
Everything works fine. No errors are displayed by firebug. The function also works, but i want to add another validation which is checking if the oldname = newname. The function is able to get the value of the newname but it can't get the value of oldname which is from form_hidden.
Please tell me what I'm doing wrong. Many thanks!
What I would do is load the script in. after that, in your html, create some script tags and echo your form-hidden to a variable.
ex.
<script src='main.js'></script>
<script>
var hello=<?php echo form_Hidden; ?>;
thisIsAFunction(hello);
</script>
</body>
</html>
Just changed
<script type="text/javascript">
$(document).ready(function()
{
check_client("#client_name", "<?php echo base_url(); ?>client/check_availability", "#client_verify", "#old_name");
})
</script>
into
<script type="text/javascript">
var old_name = "<?php echo $client_name; ?>";
$(document).ready(function()
{
check_client("#client_name", "<?php echo base_url(); ?>client/check_availability", "#client_verify",old_name);
})
</script>

Keydown functionality in a input field

I want to key down my search results and for this i am using this jquery below:
$('#ChangeAccountInput').keydown(function(e)
{
if(e.keyCode==40)
{
$('#results').css("background-color", "yellow");
}
});
But the problem is, it is applying to the full div not on a single value.
Above jquery applying to all like:
html:
<input id='ChangeAccountInput' class="InputBorder" placeholder="Search" style="display: none; margin-top: -79px; margin-left: -226px; border: 1px solid rgb(133, 133, 133); font-family: calibri; font-size: 15px; color: rgb(68, 68, 68); padding-left: 6px; padding-right: 21px; width: 182px"/>
<i class="icon-search" id="iconsearch1" style="display: none; margin-top: -37px; margin-left: -22px;"></i>
<div id="results" stlye='display: none'></div>
php:
while($row = oci_fetch_assoc($query))
{
echo "<a href='#'>";
echo '<font>'.$row['ACCOUNT_TYPE'].'</font>';
echo '<br>';
echo "<div style='border: 1px solid #AAAAAA; margin-left: -4px'></div>";
echo "</a>";
}
ajax:
$.ajax
({
type: 'GET',
url: 'Reports/Account Search.php',
data: 'GetAccountInput='+GetAccountInput,
success: function(data)
{
$('#results').html(data);
$('#results').show();
}
});
Account Search File:
<?php
error_reporting(0);
$user = "fyp";
$pass = "fyp";
$host = "localhost/CRMP";
// Connection with the Oracle.
$con = oci_connect($user, $pass, $host);
// If connection is established with the Oracle or not.
if (!$con)
{
//header('location:../../../Extra/Error_Other.php');
}
else
{
//echo "Connected to Oracle.";
}
?>
<?php
$GetAccount = $_GET['GetAccountInput'];
if($GetAccount != '')
{
$query = oci_parse($con, "SELECT DISTINCT ACCOUNT_TYPE FROM ACCOUNTS WHERE ACCOUNT_TYPE LIKE '%".$GetAccount."%'");
oci_execute($query);
$check = oci_fetch_array($query);
if(empty($check))
{
echo "<a href='#'>";
echo "No Result Found";
echo "</a>";
}
while($row = oci_fetch_assoc($query))
{
echo "<a>";
echo $row['ACCOUNT_TYPE'];
echo '<br>';
echo "</a>";
echo "<div style='border: 1px solid #777A79; margin-left: -6px'></div>";
}
}
else
{
}
?>
Help would be apprciated.
I thought about this some more and I came up with a solution that will work for you. All you should have to do is add the kind of styling that you want and other animations as needed.
http://jsfiddle.net/2wk6Q/1095/
$('#ChangeAccountInput').keydown(function (e) { //not actually the down key though :-)
if ($('a').hasClass('yellowBack')) { // do any links have this class?
var selected = $('a.yellowBack'); // if the do, they are the 'selected' link
selected.removeClass('yellowBack'); // this cleans up the one that we move from
if (40 == e.keyCode) { // going down the list
if (selected.next().length == 0) {
// if there isn't another list item, highlight the first
$('#results a:first').addClass('yellowBack');
} else {
// add the class to the next item
selected.next().addClass('yellowBack');
}
} else { // going up the list
if (selected.prev().length == 0) {
// add the class to the last item if you have gone to the top of the list
$("#results a:last").addClass("yellowBack");
} else {
// add the class to the next one up the list
selected.prev().addClass('yellowBack');
}
}
} else {
// if none were initially selected, select the first one
$("#results a:first").addClass("yellowBack");
}
});
This will allow you to move up and down the returned list, no matter what length the list is. Proper styling will prevent scrollbar issues that you mentioned above.
EDIT: modifying PHP so that output matches latest fiddle -
while($row = oci_fetch_assoc($query))
{
echo "<div style='border-bottom: 2px solid #777A79; margin-left: -4px'>";
echo "<a href='#'>";
echo '<font>'.$row['ACCOUNT_TYPE'].'</font>';
echo "</a>";
echo "</div>";
}
The reason for the modification is because the PHP is essentially outputting HTML that is hard to work with in JavaScript. The OP is learning how to format ALL of his code, from back to front, so that it plays nicely together.

Categories