I want to autofill the dropdownlist using jquery and php - javascript

Below is my php file to apply query
$host = "localhost";
$user = "root";
$pass = "abc123";
$databaseName = "class";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT id, name FROM lecturer");
if (mysql_num_rows($result)) {
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[] = array(
'id' => $row['id'],
'name' => $row['name']
);
}
header('Content-type: application/json');
echo json_encode( $data );
}
And this is my other file where i am applying javascript. I have searched a lot of same queries but could not find solution. Please help me
<script type="text/javascript">
function lecturer(){
$("#a1_title").empty();
$("#a1_title").append("<option>Default</option>");
$.ajax({
type:'POST',
url : 'get-data.php',
contentType :"application/json; charset-utf8",
dataType:'json',
type:'POST',
success:function(data){
$('#a1_title').empty();
$('#a1_title').append("<option>Default</option>");
$.each(data, function(i, data){
$('#a1_title').append('<option value="'+data[i].id+'">'+data[i].name+'</option>');
});
},
complete: function(){
}
)};
}
$(document).ready(function(){
lecturer();
});
</script>
Please help me I have tried to solve this problem buy i am not able to do it.

Your PHP code had bad syntax since you had your array() was surrounded with curly braces rather than parentheses. You also had some errors in your $.ajax, a misplaced parentheses. In addition, you do not need an iterator ([i]) in your $.each() function - you can just get each item's bit of information by associating this iteration's values. And as #Jay Blanchard said, mysqli would be used best here.
Try the following editions:
PHP:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "test";
$con = mysqli_connect($host, $user, $pass, $databaseName);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT id, name FROM lecturer");
if (mysqli_num_rows($result)) {
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
header('Content-type: application/json');
echo json_encode($data);
}
?>
JS:
<script type="text/javascript">
function lecturer() {
$("#a1_title").empty();
$("#a1_title").append("<option>Default</option>");
$.ajax({
type: 'POST',
url: 'get-data.php',
contentType: "application/json; charset-utf8",
dataType: 'json',
type: 'POST',
success: function (data) {
$('#a1_title').empty();
$('#a1_title').append("<option>Default</option>");
$.each(data, function (k, v) {
$('#a1_title').append('<option value="' + v.id + '">' + v.name + '</option>');
});
},
complete: function () {
}
});
}
$(document).ready(function () {
lecturer();
});
</script>

Related

Returning an itterable object to Ajax from php

How can I iterate through the object sent back from the php script below in my jquery/ajax call?
I tried result[0] whiche gave me back c. That means that I'm being returned a string.What code should I write to be returned company1 etc. ?
DROP DATABASE IF EXISTS test;
CREATE DATABASE test;
USE test;
CREATE TABLE company(
name VARCHAR(255),
id INT PRIMARY KEY AUTO_INCREMENT
);
INSERT INTO company(name) VALUES( 'company1');
INSERT INTO company(name) VALUES( 'company2');
INSERT INTO company(name) VALUES( 'company2');
$.ajax({
type: "GET",
url: "manager-get-company.php",
success: function (response) {
//iterate through response here
//console.log(response[0]; -> log Company1
//console.log(response[1]; -> log Company2
}
});
<?php
//manager-get-company.php
$hostname = 'localhost';
$username = 'root';
$password = '';
$database_name = 'test';
$con = mysqli_connect($hostname,$username,$password,$database_name);
//Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$sql= mysqli_query($con, 'SELECT name FROM company');
while($row = mysqli_fetch_array($sql)){
echo $row['name'];
}
In ajax add dataType : "json",
$.ajax({
type: "GET",
dataType : "json",
url: "manager-get-company.php",
success: function (response) {
//iterate through response here
if(!response.error){
console.log(response[0]);
}
}
});
In php
$result = [];
//Check connection
if (mysqli_connect_errno()) {
$result['error'] = "Failed to connect to MySQL: " . mysqli_connect_error();
}else{
$sql= mysqli_query($con, 'SELECT name FROM company');
while($row = mysqli_fetch_array($sql)){
$result[] = $row['name'];
}
}
echo json_encode($result);
Edited : use $result['error'] not result['error']

how to get updated table values while the php page is running

I'm developing a website using php. I have some problems. I want to know know how to get modified table values while running the php page without refreshing the page.
<html>
<?php
function fun_get_user_name() {
$host_name = "localhost";
$db_user_name = "root";
$password = "";
$database_name = "database_name";
$connect = mysqli_connect($host_name, $db_user_name, $password, $database_name);
$query = "SELECT * FROM `users` ";
$result = mysqli_query($connect, $query);
$output = "";
while ($row = mysqli_fetch_array($result)) {
$output = $output."<br/>"..$row[0];
}
}
?>
<script>
function js_function() {
result = "<?php echo fun_get_user_name; ?>";
document.getElementById('div_body_users').innerHTML = result;
}
window.setInterval(function() {
js_function();
}, 1000);
</script>
<body>
<div id="div_body_users">
</div>
</body>
</html>
when I made a change in phpmyadmin table the change didn't affect the page. But I expected the updated table.
So move the fun_get_user_name to another file and then in a setInterval do a n ajax call to that file.
$.get( "users.php", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
For more info on ajax request look at this link
https://api.jquery.com/jquery.get/
On user.php you just need to add fun_get_user_name
You can do it with using ajax, here changed with your ajax url and database connection details.
<html>
<?php
function fun_get_user_name()
{
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
}
if($_GET['ajax']==1){
$data=fun_get_user_name();
echo $data;
exit(0);
}
?>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
$(document).ready(function(){
setInterval(js_function,1000);
function js_function()
{
$.ajax({
url: "http://localhost/test2/test.php?ajax=1",
data: '',
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function (result) {
document.getElementById('div_body_users').innerHTML=result;
}
});
}
});
</script>
<body>
<div id="div_body_users">
</div>
</body>
</html>
You for update page without page refresh you have to use AJAX along with setInterval function.
Please check below link
https://www.w3schools.com/asp/asp_ajax_intro.asp

Json_encode in While Loop

I need to get data from the database with ajax and put that data in the 'select' tag. I need to have every name in a different 'option'... View the code:
Index.php:
<label>Select:</label>
<select id="users"></select>
JS:
$(document).ready(function() {
setInterval(function() {
$.get("frombase.php", function(data) {
data = JSON.parse(data);
for (var id in data) {
$("#users").empty();
$("#users").append("<option value='"+ id +"'>"+ data[id] +"</option>")
}
});
}, 1000);
});
And frombase.php:
$sql = "SELECT * FROM `users`";
$result = mysqli_query($db, $sql);
$name = array();
while ($row = mysqli_fetch_assoc($result)) {
$name[] = $row['name'];
}
echo json_encode(array("name" => $name));
mysqli_close($db);
Look at the result (I do not need this)
(My english is not good, because I use Google Translate)
I would do in this way...
JS:
$(document).ready(function() {
$.ajax({
url :'frombase.php',
type: "POST",
dataType: "json",
success : function(data){
$("#users").empty();
$(data['options']).each(function(k,v){
$("#users").append("<option value='"+ v['id'] +"'>"+ v['name'] +"</option>");
});
},
error:function(){
alert('Error of server comunication');
}
});
});
PHP:
$db = 'YOUR CONNECTION';
$query = $db->prepare("SELECT id,name FROM users");
$query->execute();
$query->bind_result($id,$name);
while ($query->fetch()) {
$result[] = array('id'=>$id,'name'=>$name);
}
$root['options'] = $result;
$root = json_encode($root);
$db->close();
echo $root;

Return echo from php-function to ajax

I have a question re. receiving data from php-function to ajax.
Ajax (in html-file):
function showUser(name) {
$.ajax({
type: 'POST',
url: '/api.php',
data: {
name : "\""+name+"\"",
func_id : "1"
},
dataType: 'json',
success: function(data)
{
if (data == null) {
console.log("Something went wrong..");
} else {
console.log(data);
Php (separate php-file):
<?php
error_reporting(E_ALL);
//MySQL Database connect start
$host = "localhost";
$user = "root";
$pass = "root";
$databaseName = "TFD";
$con = mysqli_connect($host, $user, $pass);
if (mysqli_connect_errno()) {
echo "Failed to connect to database: " . mysqli_connect_error();
}
$dbs = mysqli_select_db($con, $databaseName);
//MySQL Database connect end
$func_id = $_POST['func_id'];
function showUser() {
global $con;
$name = $_POST['name'];
$sql = "SELECT * FROM users WHERE first_name=$name";
$result = mysqli_query($con, $sql);
$array = mysqli_fetch_row($result);
mysqli_close($con);
echo json_encode($array);
}
if ($func_id == "1") {
showUser();
}
?>
The question: Everything works if I don't have the showUser-function in the php, i.e. I receive correct output to ajax if I have all php code in the "root" directly, but when I put that part in a function I don't get anything sent to ajax. The Network-panel in Chrome shows correct query from the sql so $array contains correct data, but I don't receive it in ajax.
Is there a fix for this?
Thanks!
The reason may be that the variables inside a function're visible only for function itself. Try this way:
$name = $_POST['name'];
function showUser($name) {
global $con;
$sql = "SELECT * FROM users WHERE first_name=$name";
$result = mysqli_query($con, $sql);
$array = mysqli_fetch_row($result);
mysqli_close($con);
echo json_encode($array);
}
Note: If you'll use 'mysql_escape_string' to prevent sql injections, don't forget to connect to db first, otherwise 'mysql_escape_string' will return empty string.

Getting the value

I just need some ideas how i get the value from the dropdown
<select id="ins" name="instructor" required>
<?php
//dropdown instructor name
echo "<option value=\"\">"."Select"."</option>";
$qry = "select * from instructor";
$result = mysqli_query($con,$qry);
while ($row = mysqli_fetch_array($result)){
echo "<option value=".$row['insA_I'].">".$row['insname']."</option>";
}
?>
</select>
and put the value in this .php file in $_POST['instructor']
<?php
session_start();
require 'connection.php'; //connection
$qry = "select course from instructor where insA_I = '".$_POST['instructor']."'";
$result = mysqli_query($con,$qry);
$_SESSION['row'] = mysqli_fetch_array($result);
$data = $_SESSION['row']['course'];
echo $data;
?>
am still new in ajax
$(document).ready(function() {
$('#ins').change(function(){
$.ajax({
type: "POST",
url: "json_php.php",
data: '',
datatype: 'json',
success: function(result){
alert(result);
}
});
});
});
i already searched this in internet but didn`t get my answer after some modifcation
just need idea, techniques .etc.
Try this ajax code
$(document).ready(function() {
$('#ins').change(function(){
$.ajax({
type: "POST",
url: "json_php.php",
data: {instructor:$(this).val()},
success: function(result){
alert(result);
}
});
});
});
php code for query
$qry = "select course from instructor where insA_I = '".$_POST['instructor']."'";
$result = mysqli_query($con,$qry);
$fetch = mysqli_fetch_array($result);
$_SESSION['row']['course']=$fetch['course'];
$data = $_SESSION['row']['course'];
echo $data;
Since you're using jQuery, use jQuery:
data: { instructor: $('#ins').val() }
Also, please note that your SQL query is wide open to SQL injection. This is a good place to start reading about that.

Categories

Resources