How to show data from mysql using AJAX into text field - php

Previously I could not know about ajax. therefore I want to ask.
I want to display my wordlist from mysql into a text field but in array. this is the index.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="container" >
<h2>View data</h2>
<h4>Word List : </h4>
<div class="form-group">
<input id="wordlist" type="text" class="form-control" name="wordlist">
</div><br>
<button id="display" title="Generate Word">Generate</button>
<div class="input-single">
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({
type: "GET",
url: "view_ajax.php",
dataType: "html",
success: function(){
$('').html();
}
});
});
});
</script>
And then this is the process.php
<?php
$host = "localhost";
$user = "root";
$password = "";
$dbname = "posts";
$con = mysqli_connect($host, $user, $password, $dbname);
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "select wordlist from word";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('wordlist'=>$row[0]));
}
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>
I will be very helpful if you can give an answer. Thank you

Change your PHP loop to something like this:
$result = array();
while($row = mysqli_fetch_array($res)){
$result[]= $row[0];
}
echo json_encode(array('wordlist'=>$result));
Then, in your JS, see below
$(document).ready(function() {
$("#display").click(function() {
/*$.ajax({
type: "GET",
url: "view_ajax.php",
dataType: "json",
success: function(response){
// use the code below in this area
}
});*/
let response = {
"wordlist": ["This", "is", "the", "return", "from", "your", "server"]
} // this is what the response object will look like in your success function above
let output
// normal comma delimited response
output = response.wordlist.join(",");
// or if you want to keep the quotes
output = JSON.stringify(response.wordlist);
output = output.substr(1, output.length - 2);
// use .val() to set the value of an input
$('#wordlist').val(output);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<h2>View data</h2>
<h4>Word List : </h4>
<div class="form-group">
<input id="wordlist" type="text" class="form-control" name="wordlist">
</div><br>
<button id="display" title="Generate Word">Generate</button>
<div class="input-single">
</div>

Related

Searchbox (AJAX) won't load requested data

so I have a problem I can't find the error.
By default the page should load all data and when I hit search, only the requested ones (no refreshing page).
(Even better would be if I could also change the outcome/request by changing the url without having to type in in the input field:
entering url: .../searchpage.php?search=banana --> results for banana
entering url: .../searchpage.php?search=apple --> results for apple
but small steps first.)
Do you have maybe see where my problem is? Or so you know some good pages where I can find solutions/information for my problem? \
A big thankyou in advance!
index.php:
<script src="assets/js/jquery.min.js"></script> //v3.4.1
<section class="wrapper">
<div class="formpost">
<div class="searchpannel">
<input type="text" class="searchBox" name="searchBox" id="searchBox" placeholder="Search..">
<button type="submit" id="searchBtn">SEARCH</button>
</div>
<div id="SearchResult"> <?php include 'startdata.php'?> </div>
</div>
</section>
<script>
$(document).ready(function(){
$('#searchdata').click(function(e){
e.preventDefault();
var searchtext = $('input[name=searchBox]').val();
$.ajax({
type: "POST",
url: "fetchdata.php",
data: {
"search_post_btn": 1,
"searchBox": searchBox,
},
dataType: "text",
success: function (response) {
$("#SearchResult").html(response);
}
})
})
})
</script>
fetchdata.php:
<?php
$conn = mysqli_connect("localhost", "root", "");
$db = mysqli_select_db($conn, 'ajax');
if(isset($_POST['search_post_btn'])) {
$search = $_POST['searchBox'];
$query = "SELECT * FROM ajaxtest WHERE name LIKE '%$search%' ";
$query_run = mysqli_query($conn,$query);
if(mysqli_num_rows($query_run) > 0){
WHILE ($row = mysqli_fetch_assoc($query_run)) {
echo "<h2>Hallo, my name is ";
echo $row['name'];
echo "<strong>";
echo $row['famname'];
echo "</strong></h2><p> On the list I'm place ";
echo $row['id'];
echo "</p>";
}
}
}
?>
Hi you have to do some modification in your code
$.ajax({
type: "POST",
url: "fetchdata.php",
data: {
"search_post_btn": 1,
"searchBox": searchBox,
},
dataType: "json",
success: function (response) {
$("#SearchResult").html(response);
}
})
----- PHP CODE ----
<?php
$conn = mysqli_connect("localhost", "root", "");
$db = mysqli_select_db($conn, 'ajax');
if(isset($_POST['search_post_btn'])) {
$search = $_POST['searchBox'];
$query = "SELECT * FROM ajaxtest WHERE name LIKE '%$search%' ";
$query_run = mysqli_query($conn,$query);
if(mysqli_num_rows($query_run) > 0){
$design = "";
WHILE ($row = mysqli_fetch_assoc($query_run)) {
$design .= "<h2>Hallo, my name is ".$row['name']."<strong>".$row['famname']."</strong></h2><p> On the list I'm place ".$row['id']."</p>";
}
print_r(json_encode($design));
die;
}
}
?>

Unable to save timestamp to sql database from form data

Im trying to save the current timestamp of the video being played as soon as I click submit. But in the table only 0 is getting saved and Im unable to fetch & save the current timestamp of video. Although its getting displayed but not getting saved in SQL table.
NOTE : timestamp(tstamp) : Is a dynamic value, which is the timestamp of the video file being played in the browser( for example 1.935771),
fileUpload.php
<body>
<h1>VIDO LABELLING TOOL</h1>
<video id="my_video_1" class="video-js vjs-default-skin" controls preload="auto" width="640" height="268"
data-setup='{ "playbackRates": [0.5, 1, 1.5, 2, 4] }'>
<source src="project.m4v" type='video/mp4'>
<track src='br.srt' kind="subtitles" srclang="en" label="English" default>
</video>
<script>
// Get the audio element with id="my_video_1"
var aud = document.getElementById("my_video_1");
// Assign an ontimeupdate event to the audio element, and execute a function if the current playback position has changed
aud.ontimeupdate = function () {
myFunction()
};
</script>
<div class="container" style="max-width:800px;margin:0 auto;margin-top:50px;">
<form name="contact-form" action="" method="post" id="contact-form">
<label for="email">Comments about the frame</label>
<textarea name="message" class="form-control" id="message"></textarea>
<div class="error" id="error_message"></div>
<label>Vehicle Type:</label>
<input name="veh_type_1" id="veh_type_1" type="checkbox" value="lmv">lmv
<input name="veh_type_2" id="veh_type_2" type="checkbox" value="2w">2w
<p>TimeStamp: <span id="tstamp"></span></p>
</div>
<p class="submit">
<button type="submit" class="btn btn-primary" name="submit" value="Submit" id="submit_form">Submit</button>
</p>
<div class="display-content">
<div class="message-wrap dn"> </div>
</div>
</form>
</div>
<script>
function myFunction() {
document.getElementById("tstamp").innerHTML = aud.currentTime;
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#contact-form").on("submit", function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: "saveFile.php",
data: $(this).serialize(),
success: function () {
alert("form was submitted");
}
});
return false;
});
});
</script>
</body>
and the php file for db update as :-
saveFile.php
<?php
$servername = "localhost";
$database = "stackover";
$username = "root";
$password = "123456";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$tstamp = addslashes($_POST['tstamp']);
$message = addslashes($_POST['message']);
$veh_type_1 = addslashes($_POST['veh_type_1']);
$veh_type_2 = addslashes($_POST['veh_type_2']);
mysqli_query($conn, "insert into saveData(message,tstamp,veh_type_1, veh_type_2) values ('$message','$tstamp','$veh_type_1', '$veh_type_2')");
$sql = mysqli_query($conn, "SELECT message,tstamp,veh_type_1,veh_type_2 id FROM saveData order by id desc");
$result = mysqli_fetch_array($sql);
echo '<div class="message-wrap">' . $result['message'] . '</div>';
?>
Please add this into your form
<input name="tstamp" id="hidden-tstamp" type="hidden">
and inside your script add below code
function myFunction() {
document.getElementById("tstamp").innerHTML = aud.currentTime;
document.getElementById('hidden-tstamp').value = aud.currentTime;
}

AJAX: How do I get the label and value of a field to be different?

I have the below two files.
How do I get AJAX to populate a label and a value
For example if value is Chicago, IL. How do I get the value to be only Chicago on Submitting the form?
Below the field populates as, for example, Chicago, IL
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</head>
<body>
<br /><br />
<div class="container" style="width:600px;">
<h2 align="center"></h2>
<br /><br />
<label>Search Country</label>
<input type="text" name="city" id="city" class="form-control input-lg" autocomplete="off" placeholder="Type City Name" />
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#city').typeahead({
source: function(query, result)
{
$.ajax({
url:"TypeaheadTest2.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data)
{
result($.map(data, function(item){
return item;
}));
}
})
}
});
});
</script>
Below is file TypeaheadTest2.php
<?php
$connect = mysqli_connect("localhost", "", "", "");
$request = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT * FROM state WHERE state LIKE '".$request."%' OR city LIKE '%".$request."%'
";
$result = mysqli_query($connect, $query);
$data = array();
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row['city'] . ' ' . $row['state'];
}
echo json_encode($data);
}
?>
If I am getting you right, you are so close to what you are expecting.
I see that you are concatenating the city and state name on the server side. But you want to display only city name on typeahead options.
I would suggest you pass on the city name and state name as separate attributes of an object from PHP and then use them as you want on Javascript side.
Here is the sample code,
PHP:
<?php
$connect = mysqli_connect("localhost", "", "", "");
$request = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT * FROM state WHERE state LIKE '".$request."%' OR city LIKE '%".$request."%'
";
$result = mysqli_query($connect, $query);
$data = array();
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$data[] = array('city'=>$row['city'], 'state'=>$row['state']);
}
echo json_encode($data);
}
?>
Javascript:
$(document).ready(function(){
$('#city').typeahead({
source: function(query, result) {
$.ajax({
url:"TypeaheadTest2.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data) {
result($.map(data, function(item){
return item.city;
}));
}
});
}
});
});

MaterializeCSS Autocomplete PHP MySQL

I need to make a autocomplete input in materialize css page,
I've tried this code but did not work. Do you have any idea how to make this possible?
From here Autocomplete Textbox using jQuery, PHP and MySQL
index.php
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#skills" ).autocomplete({
source: 'search.php'
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="skills">Skills: </label>
<input id="skills" type="text">
</div>
search.php
<?php
$dbHost = 'localhost';
$dbUsername = 'u969692298_dogs';
$dbPassword = 'dogs123';
$dbName = 'u969692298_dogs';
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
$searchTerm = $_GET['term'];
$query = $db->query("SELECT * FROM kennels WHERE name LIKE '%".$searchTerm."%' ORDER BY name ASC");
while ($row = $query->fetch_assoc()) {
$data[] = $row['name'];
}
echo json_encode($data);
?>
What about something like this:
The result from this snippet suggests country name when you start typing in input box with materialize css framework.
Example with API GET request
$(document).ready(function() {
//Autocomplete
$(function() {
$.ajax({
type: 'GET',
url: 'https://restcountries.eu/rest/v2/all?fields=name',
success: function(response) {
var countryArray = response;
var dataCountry = {};
for (var i = 0; i < countryArray.length; i++) {
//console.log(countryArray[i].name);
dataCountry[countryArray[i].name] = countryArray[i].flag; //countryArray[i].flag or null
}
$('input.autocomplete').autocomplete({
data: dataCountry,
limit: 5, // The max amount of results that can be shown at once. Default: Infinity.
});
}
});
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/css/materialize.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/js/materialize.min.js"></script>
<div class="row">
<div class="col s12">
<div class="input-field">
<input type="text" id="autocomplete-input" class="autocomplete" autocomplete="off" name="name">
<label for="autocomplete-input">Country Name</label>
</div>
</div>
</div>
Above code by Jaikhlang Brahma answer
Example with POST request
Jquery
$(document).ready(function() {
//Autocomplete
var inp_val = document.getElementById("myInput").value;
var dataString = "name="+inp_val;
$(function() {
$.ajax({
type: 'POST',
url: 'suggest-country.php',
data: dataString,
success: function(response) {
var countryArray = response;
var dataCountry = {};
for (var i = 0; i < countryArray.length; i++) {
//console.log(countryArray[i].name);
dataCountry[countryArray[i].name] = countryArray[i].flag; //countryArray[i].flag or null
}
$('input.autocomplete').autocomplete({
data: dataCountry,
limit: 5, // The max amount of results that can be shown at once. Default: Infinity.
});
}
});
});
});
HTML
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/css/materialize.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/js/materialize.min.js"></script>
<div class="row">
<div class="col s12">
<div class="input-field">
<input type="text" id="autocomplete-input" class="autocomplete" autocomplete="off" name="name">
<label for="autocomplete-input">Country Name</label>
</div>
</div>
</div>
PHP (suggest-country.php)
<?
header('Content-type: text/html; charset=UTF-8');
$dbHost = 'localhost';
$dbUsername = 'u969692298_dogs';
$dbPassword = 'dogs123';
$dbName = 'u969692298_dogs';
$conn = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
$query = trim(str_replace(" ", " ", $_POST['name']));
$str = htmlspecialchars($query);
$q = filter_var($str, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$sql = $conn->prepare("SELECT * FROM kennels WHERE name = ? ORDER BY name ASC");
$sql->bind_param("s", $q);
$sql->execute();
$rs = $sql->get_result();
$arr = array();
while($row = $rs->fetch_assoc()){
$arr["name"] .= $row["name"];
$arr["flag"] .= $row["flag"];
}
// echo "<pre>".json_encode($arr)."</pre>";
echo json_encode($arr);
?>
This PHP code is pretty secure and working nicely.
For more relevancy use MYSQL FULL TEXT SEARCH or replace this SQL query
$sql = $conn->prepare("SELECT * FROM kennels WHERE name = ? ORDER BY name ASC");
$sql->bind_param("s", $q);
$sql->execute();
To this
$sql = $conn->prepare("SELECT *, " . " MATCH(name) AGAINST(? IN BOOLEAN MODE) AS relevance " . " FROM kennels" . " ORDER BY relevance DESC LIMIT 8");
$sql->bind_param("s", $q);
$sql->execute();
$rs = $sql->get_result();
Hope this is helpful to you, I know how old this post is, but I want to help other newbies who are experiencing this problem.
Thank you 😊

Getting all the content of table and append it using ajax with jquery

I made a simple sample on how to insert using AJAX and retrieving it then append it in a <div> after getting it. But I am having trouble on getting all the content of the table, it's returning a null values.
<div id="wrap-body">
<form action method="post">
<input type="text" name="username" id="username">
<input type="text" name="msg" id="msg">
<input type="button" id="submit" value="Send">
</form>
<div id="info">
</div>
</div>
jQuery:
<script>
$(document).ready(function (){
$('#submit').click(function (){
var username = $('#username').val();
var msg = $('#msg').val();
$.ajax({
type: 'POST',
url: 'get.php',
dataType: 'json',
data:'username='+username+'&msg='+msg,
success: function (data){
$('#info').append("<p> you are:"+data.username+"</p> <p> your message is:"+data.mesg);
}
});
});
});
</script>
PHP:
<?php
$host='localhost';
$username='root';
$password='12345';
$db = 'feeds';
$connect = mysql_connect($host,$username,$password) or die("cant connect");
mysql_select_db($db) or die("cant select the".$db);
$username = $_POST['username'];
$msg = $_POST['msg'];
$insert = "INSERT INTO info(user_name,message) VALUES('$username','$msg')";
if(#!mysql_query($insert)){
die('error insertion'.mysql_error());
}
$get = "SELECT * FROM info ";
$result=mysql_query($get)or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$return = $row['user_name'];
$return = $row['message'];
}
echo json_encode($return);
?>
Your while should create array and then do json_encode
Try below code
$data=array();
while ($row = mysql_fetch_array($result))
{
$data[] = array(
'username'=>$row['user_name'],
'mesg'=>$row['message']
);
}
echo json_encode($data);
exit
Now write your javascript success handler as below
$.ajax({
type: 'POST',
url: 'get.php',
dataType: 'json',
data:'username='+username+'&msg='+msg,
success: function (data){
$.each(data, function(i, item) {
$('#info').append("<p> you are:"+data[i].username+"</p> <p> your message is:"+data[i].mesg);
});​
}
});
There are several issues you have to fix, but you have to start with returning the same type as expected by the ajax call:
$return = array()
if ($row = mysql_fetch_array($result))
{
$return['username'] = $row['user_name'];
$return['mesg'] = $row['message'];
}
echo json_encode($return);

Categories