I've a select populated by a php query, that loads the nicknames of the users logged in a specific div, called “UserList”.
<div id=”UserList” name=”UserList”>
</div>
This select is placed in a php page, “userlist.php”, loaded by jquery. The php query works fine, so I've avoided writing here the db connection.
<select name="User" id=”User”>
<?
$MySql = "SELECT Name FROM Users WHERE Loc = '$Loc' ORDER BY Name";
$Result = mysql_query($MySql);
while ($rs = mysql_fetch_array($Result)) {
echo '<option value="'.$rs['Name'].'">'.htmlspecialchars($rs['Name']).'</option>';
}
$rs->close;
mysql_free_result($Result); ?>
</select>
My problem is that I need to reload only the select and refreshing it when a user clicks the select itself, so new users that enter the page are added by the php query and those that changed page are removed from the list. But whit every event that I tried the jquery loops, instead of activating the reload only once every time a user clicks the form and the first click event not even reload properly the php query.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#UserList").load('userlist.php');
$("#UserList").click(function() {
$("#UserList").load('userlist.php');
evt.preventDefault();
});
});
</script>
Thanks for your help.
I would suggest using AJAX to do this. AJAX allows you to query the web-server with out refreshing the entire page. This example
seems like almost exactly what you want to do.
Edit:
Put this inside your template:
<div id=”UserList” name=”UserList”>
<select name="User" id=”User”>
<?
$MySql = "SELECT Name FROM Users WHERE Loc = '$Loc' ORDER BY Name";
$Result = mysql_query($MySql);
while ($rs = mysql_fetch_array($Result))
{
echo '<option value="'.$rs['Name'].'">'.htmlspecialchars($rs['Name']).'</option>';
}
$rs->close;
mysql_free_result($Result);
?>
</select>
</div>
Then Change the Javascript
<script type="text/javascript">
$(document).ready(function() {
$("#User").click(function() {
$("#User").load('userlist.php');
});
});
</script>
And finally change the userlist.php file:
<?
$MySql = "SELECT Name FROM Users WHERE Loc = '$Loc' ORDER BY Name";
$Result = mysql_query($MySql);
while ($rs = mysql_fetch_array($Result)) {
echo '<option value="'.$rs['Name'].'">'.htmlspecialchars($rs['Name']).'</option>';
}
$rs->close;
mysql_free_result($Result); ?>
Related
I have created a simple dropdown with html and php/mysql
<select name="location_id" id="location_id" class="form-control">
<?php
$sql = "SELECT * FROM locations";
$result = mysqli_query($conn, $sql);
while($row=mysqli_fetch_assoc($result)){ ?>
<option value="<?php echo $row['location_id'];?>">
<?php echo $row['location_name'];?></option>
<?php } ?>
</select>
It is working great until a new record is inserted from another page. I need to refresh the page to get the newly inserted record in the dropdown.
In my current application I need to refresh the dropdown options without refreshing the whole page whenever a user click on the dropdown list. The options should be fetched in realtime from the mysql database.
I have searched for the solution, but not able to find the similar solution.
To refresh only a part of a page you need to use JavaScript, AJAX to be specific.
Ajax lets you send HTTP requests and update page elements without a full page reload.
You could try something like this
<script>
function refresh_items() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("location_id").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "refresh_list.php", true);
xhttp.send();
}
</script>
<select name="location_id" id="location_id" class="form-control" onclick="refresh_items();">
</select>
Now that you've made your client side scripts you want you server side PHP on refresh_list.php to look something like this
<?php
//all your SQL settings and stuff here
$sql = "SELECT * FROM locations";
$result = mysqli_query($conn, $sql);
while($row=mysqli_fetch_assoc($result)){ ?>
<option value="<?php echo $row['location_id'];?>">
<?php echo $row['location_name'];?></option>
<?php } ?>
I am working on creating a like counter for quotes. I am trying to increment the like counter when the user clicks on the like button and display the number of likes.
Problems I encountered:
Like counter gets incremented when I refresh the page (Not because I am actually hit the like button).
I tried implementing jQuery for the updation of the like counter in real time but failed :(
I referred to all the QnA related to this couldn't find the desired solution. I went through this [question]PHP/MySQL Like Button, and made the necessary changes but now there is no updation in the database when I click the button.
This is the code for one quote.
<div class="testimonial text-sm is-revealing">
<div class="testimonial-inner">
<div class="testimonial-main">
<div class="testimonial-body">
<p id="q1">
<?php
$sql = "select quotes from voted where voted.quote_id = 1";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result);
echo "$row[0]";
?></p>
</div>
</div>
<div class="testimonial-footer">
<div class="testimonial-name">
<button method="POST" action='' name="like" type="submit" class="like"><b>Like</b></button>
<?php
if(isset($_POST['like'])){
$link = mysqli_connect("localhost","root","","success");
$sql = "UPDATE voted SET likes = likes+1 WHERE voted.quote_id = 1";
$result = mysqli_query($link,$sql);
}
?>
<label>
<?php
$link = mysqli_connect("localhost","root","","success");
$sql = "SELECT likes from voted WHERE voted.quote_id = 1";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result);
echo "$row[0]";
?>
</label>
<button class="btn" id="clipboard" onclick="copyFunction('#q1')"></button>
</div>
</div>
</div>
How do I make the like counter implement when I click on the like button?
How do I implement jQuery and AJAX to this, so that the counter is updated without a page refresh?
Please pardon my poor code structure.
Thanks for any help.
P.S This how a single quote will look like
You need three things for an asynchronous setup like this to work:
Your back-end script to handle ajax requests
Your front-end page
Your JQuery script to send ajax requests and receive data
Your back-end PHP script would look something like this (async.php):
<?php
if(isset($_POST['get_quotes'])) {
$sql = "select quotes from voted where voted.quote_id = 1";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result);
echo "$row[0]";
}
if(isset($_POST['like'])) {
$link = mysqli_connect("localhost","root","","success");
$sql = "UPDATE voted SET likes = likes+1 WHERE voted.quote_id = 1";
$result = mysqli_query($link,$sql);
}
?>
Your front-end page will include an element with an ID to hook onto with the JQuery, and a button with a class or ID to capture the click event (page.html):
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="core.js"></script>
<body>
<button id="increment-like" value="Like" type="button" />
<p id="like-count">
</p>
</body>
<html>
Finally, your JavaScript file should look something like this, for a basic ajax request using JQuery (core.js):
$(document).ready(function() {
// initially grab the database value and present it to the view
$('#like-count').text(getDatabaseValue());
$('#increment-like').on('click', function() {
incrementDatabaseValue();
});
});
function getDatabaseValue() {
$.post("async.php",
{
get_quotes: true
},
function (data, status) {
// check status here
//return value
return data;
});
}
function incrementDatabaseValue() {
$.post("async.php",
{
like: true
},
function (data, status) {
// check status here
// update view
$('#like-count').text(getDatabaseValue());
});
}
I haven't tested this code but it should be clear and detailed enough to get you on the right track.
What I am trying to do is create a drop down container of 32 different locations in Scotland and when one of the selections is selected, for example, Glasgow it should go to a URL which displays content such as heading, text, for each article in a div WHERE location = Glasgow.
I have no error messages or any sort of recognition that my code has worked as when I select one of the four on the drop down it does absolutely nothing.
Can come clean up and put right what I've done so far? I would be extremely greatful!
Here is my files which are being used:
header.php
<html>
<head>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#location').change(function(){
//Retrieve Content from the back-end PHP page, and pass the ID selected
var url = 'location.php?location=' + $(this).val();
$('#txtHint').load(url);
});
});
</script>
</head>
<body>
<div id="header">
<div class="headerLeftContent">
<select id='location'>
<option href="Link to a dynamic page with all the content from glasgow" value="Glasgow">Glasgow</option>
<option href="Link to a dynamic page with all the content from x" value="x">x</option>
<option href="Link to a dynamic page with all the content from test" value="test">test</option>
<option href="Link to a dynamic page with all the content from edinburgh" value="Edinburgh">Edinburgh</option>
</select>
<div id='txtHint'></div>
</div>
</div>
</body>
</html>
location.php
<?php
$connect = mysql_connect('xxxxxx', 'xxxxxx', 'xxxxxx');
$select_db = mysql_select_db('xxxxxx');
$location = $_REQUEST['location'];
$query = "SELECT * FROM podContent WHERE location = '.$location.'";
while($row = mysql_fetch_array($query))
{
echo $row['text'];
}
mysql_close($connect);
?>
And please any comments regarding 'SQL injection' or how 'mysql' should be 'PDO' are unwanted as I do understand this but I am simply testing at the moment and will amend this.
Thanks.
You seem to have a mistake concatenating your location name inside your MySQL query, and it's not matching anything (so nothing is echoed back). Change this:
$query = "SELECT * FROM podContent WHERE location = '.$location.'";
to
$query = "SELECT * FROM podContent WHERE location = '$location'";
(Unless you have stuff like .Glasgow. in your database...)
Then you have to call mysql_query($query) as Alon suggested.
You need to use mysql_query and pass the resource to the mysql_fetch_array function:
$query = "SELECT * FROM podContent WHERE location = '.$location.'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
echo $row['text'];
}
I have 2 dropdown select boxes in my form. The first one allows the user to choose a car make "vmake". Once a vmake is chosen a "vmodel" select box appears from thin air and then the user can choose the vmodel. However, I want the vmodel box to be there on page load, so it doesnt just appear out of thin air. It would be empty if the user tries to open it until they select a vmake. Heres my html
<select name="vmake" id="vmake">
<option value"" selected="selected">Make</option>
<?php getTierOne()l ?>
</select>
<select name="vmodel" id="vmodel">
<option value"" selected="selected">Model</option>
</select>
<span id="wait_1"></span>
<span id="result_1"></span>
Heres the jquery:
$(document).ready(function(){
$('#wait_1').show();
$('#vmake').change(function(){
$('#wait_1').show();
$('#result_1').hide();
$.get("func.php", {
func" "vmake",
drop_varL $('#vmake').val()
}, function(response){
$('#result_1').fadeOut();
setTimeout(finishAjax('result_1', '"+escape(response)+"')", 400);
});
return false;
]);
});
lastly the php which connects to my database
function getTierOne()
{
$result = mysql_query("SELECT DISTINT vmake FROM vmake")
or die(mysql_error());
while($tier = mysql_fetch_array( $result ))
{ echo '<option value="'.tier['vmake'].'">'.$tier['vmake'].'</option>';
}}
if($_GET['func'] == "vmake" && isset ($_GET['func'])) {
vmake($_GET['drop_var']);}
function vmake($drop_var)
{ include_once('db.php');
$result = mysql_query("SELECT * FROM vmake WHERE vmake='$drop_var'")
or die(mysql_error());
echo '<option value=" " selected="selected">Model</option>';
while($drop_2 = mysql_fetch_array( $result))
{ echo '<option value="'.$drop_2['vmodel'].'">'.$drop_2['vmodel'].'</option>';
}}
I got some help with the original code form an open source website and now I just need to change it a little to make it do what I want. As it stands it will create a new vmodel select box next to the existing one, but I just want it to populate the select box that appears on page load. Any help is very much appreciated. Thanks for everything.
Did you try using jQuery .load?
Example:
$('#vmodel').load('func.php',{vmake:$('#vmake').val()});
Would need to change the PHP as well, so you make a normal array of values and then send it through json_encode().
I have this function http://jsfiddle.net/wnFsE/ . As you can see every time the user writes a languages on the textfield and then hits the button add a new language is added to the list. Then when the user hits save, all the info is sent with POST.
Until now, everything is ok. BUT, when the user sends the info, the info is stored on my MySQL database. So, every time when the user comes again to the page, he needs to see the languages already saved in the last session.
In my PHP script every time the user comes, I retrieve the languages from my database, but I don't know how to add them to the list. The solution would be call the $("#add").click(function() { from the PHP script who retrieve the data from the MySQL, but I don't know how to do this.
If it serves for any help, this is the simple PHP function which retrieves the languages from the user:
function list_lang() {
$this->DBLogin();
$result = mysql_query("SELECT * FROM ".table_lang." WHERE id_user=1");
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo $row['lang']." ".$row['level']."<br>";
//instead of the echo, here will be the call to jquery (if possible)
}
}
A simple soloution:
$buildHTML = '';
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$buildHTML .= '<li>'.$row['lang'].'<input type="hidden" name="languages[]" value="'.$row['lang'].'" />Remove</li>';
}
And then have
<script type="text/javascript">
var UserLangs = <?php echo $buildHTML; ?>;
$('#langs').append(UserLangs);
</script>
You can do this way:
<?php
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<script type="text/javascript">
...
...
listitem_html += <?php echo $row['lang']. $row['level'] . '<br>'?>;
...
...
</script>
<?php
}
?>