I'm trying to show MySQL data using Ajax. Unfortunately, I am unable to find the correct way. I was trying to show MySQL data on a select box. When I click on "select category" option then all category will show as dropdown.
here is my HTML code.
<!DOCTYPE html>
<html>
<head>
<title>PHP MySQL Insert Tutorial</title>
<script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
</head>
<body>
<select id='category'>
</select>
<script src='fetch.js'></script>
</body>
</html>
I have used this JS code to send request. Here is my JS code.
$('#category').onclick(function(){
$.getJSON(
'fetch.php',
function(result){
$('#category').empty();
$.each(result.result, function(){
$('#category').append('<option>'+this['category']+'</option>');
});
}
);
});
I have used this php code to complete ajax request and database connection. Here is my PHP code.
<?php
define('HOST','localhost');
define('USERNAME', 'root');
define('PASSWORD','');
define('DB','ajax');
$con = mysqli_connect(HOST,USERNAME,PASSWORD,DB);
$category = $_GET['category'];
$sql = "select category from ajaxx where category='$category'";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('category'=>$row[0]));
}
echo json_encode(array('result'=>$result));
enter code here
mysqli_close($con);
?>
When you make the AJAX request, it's to this URL:
fetch.php
But then in the server-side code, you try to get a query string value:
$category = $_GET['category'];
You can't get a query string value that you never provided. So when you build your SQL query (which is wide open to SQL injection by the way), there's nothing to get from the database.
If you want to use a query string value, you have to provide one:
$.getJSON(
'fetch.php?category=someValue',
function(result){
//...
}
);
What value you provide or where you get that value is up to you. (Perhaps from $('#category').val()?) But it has to exist before you can use it.
You may have confused two things: (a) initially fetching the HTML code to populate the options of your <select> control, and (b) Catching the selected option and using it to perform another DB query, returning new data.
Please review this modified (untested) code sample:
<!DOCTYPE html>
<html>
<head>
<title>PHP MySQL Insert Tutorial</title>
<script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
</head>
<body>
<select id='category'>
</select>
<div id="resultDIV"></div>
<script src='fetch.js'></script>
</body>
</html>
javascript/jQuery:
//Run on document ready to populate the dropdown box
$(document).ready(function(){
$.getJSON(function(){
'fetch.php',
function(result){
$('#category').empty();
$.each(result.result, function(){
$('#category').append('<option>'+this['category']+'</option>');
});
}
});
$(document).on('click', '#category', function(){
//run on click to take dropdown value and perform lookup
myCat = $(this).val();
$.ajax({
type: 'post',
url: 'getcategory.php',
data: 'category=' +myCat,
success: function(d){
//if (d.length) alert(d);
$('#resultDIV').html(d);
}
});
});
}); //END document.ready
I have used this php code to complete ajax request and database connection. Here is my PHP code.
<?php
/*** getcategory.php ***/
define('HOST','localhost');
define('USERNAME', 'root');
define('PASSWORD','');
define('DB','ajax');
$con = mysqli_connect(HOST,USERNAME,PASSWORD,DB);
$category = $_GET['category'];
$sql = "select category from ajaxx where category='$category'";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('category'=>$row[0]));
}
echo json_encode(array('result'=>$result));
enter code here
mysqli_close($con);
?>
Here are some basic, simple AJAX examples to study (the three links at the bottom, but also note the information from the first link). Copy them to your server and make them work - play around with them:
AJAX request callback using jQuery
Your ajax code needs some changes :
<!DOCTYPE html>
<html>
<head>
<title>PHP MySQL Insert Tutorial</title>
<script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
<script type="text/javascript">
function myAjax ()
{ $.ajax( { type : 'POST',
data : { 'category' : $('#txt_cat').val() }, // SEND CATEGORY.
url : 'fetch.php',
success : function ( result )
{ $( '#category' ).empty();
var arr = JSON.parse( result );
var sel = document.getElementById("category");
for ( i = 0; i < arr.length; i++ )
{ var option = document.createElement( "option" );
option.text = arr[ i ];
sel.add( option );
}
},
error : function ( xhr )
{ alert( "error" );
}
}
);
}
</script>
</head>
<body>
Enter category <input type="text" id="txt_cat"/>
<button onclick="myAjax()">Click here to fill select</button>
<select id='category'>
<option> - empty - </option>
</select>
</body>
</html>
fetch.php
<?php
$category = $_POST[ "category" ]; // CATEGORY FROM HTML FILE.
// CONNECT TO DATABASE AND QUERY HERE.
$result = Array( "111","222","333","444" ); // SAMPLE DATA.
echo json_encode( $result );
?>
Related
I'm trying to populate a Select2 box with data from a t-sql query. The query is run on a PHP page which translates the output to JSON and is called in the javascript of the main page.
The main page looks like this:
<?php
header('Content-type: text/html; charset=UTF-8');
require('db.php'); // Bring in the database connection
include("auth.php"); // Make sure the user is logged in to an account
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" http-equiv="Content Type" charset="utf-8"/>
<!-- JQuery -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- SELECT 2 -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
</head>
<body style="background-color: #F5F5F5;">
<select class="js-data-example-ajax">
</select>
<script>
$('.js-data-example-ajax').select2({
width: '250px',
ajax: {
url: 'http://10.1.248.41/TFM-Project/ImportINjson.php',
dataType: 'json'
// Additional AJAX parameters go here
}
});
</script>
</body>
</html>
My JSON page looks like this:
<?php
require('db.php'); // Bring in the database connection
include("auth.php"); // Make sure the user is logged in to an account
$search = $_GET['search'];
//JSON Table Stuff
$sql = "SELECT DISTINCT [IN] AS id, Nom as text
FROM dbo.[TFM_NumérosIN2012]
;";
$stmt = sqlsrv_query($con,$sql);
$result = array();
do {
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
} while (sqlsrv_next_result($stmt));
sqlsrv_free_stmt($stmt);
$data2 = json_encode($result);
echo '{ "results":' . $data2 . '}';
?>
The data output by the JSON page looks like this:
{ "results":[{"id":2,"text":"SMITH Sean"},{"id":3,"text":"CHARLES charley"},{"id":4,"text":"TFC Madrid"},{"id":5,"text":"VAN DAMME jean claude"}]}
The data is loading into the select list without any problems. However, I've tried to filter the data multiple ways and nothing has worked. I've tried adding a data parameter and passing a search variable to the php/JSON page and referencing in the $sql variable as a where clause, but this doesn't return anything
To try and filter the data I changed the javascript to this:
$('.js-data-example-ajax').select2({
width: '250px',
ajax: {
url: 'http://10.1.248.41/TFM-Project/ImportINjson.php',
dataType: 'json',
data: function (params) {
var query = {
search: params.term
}
// Query parameters will be ?search=[term]&type=public
return query;
}
}
});
But this breaks my select and and it displays a message 'The results could not be loaded.'
Does anyone know what I'm doing wrong here?
Cheers,
At the end of your php file just echo the following line :
echo json_encode($result);
In your html/js file :
<link href='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css' rel='stylesheet' type='text/css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js'></script>
<select name='js-data-example-ajax' class='js-data-example-ajax'></select>
$(document).ready(function()
{
$('.js-data-example-ajax').select2({
placeholder: "Search for product",
minimumInputLength: 1,
width: '250px',
ajax: {
url: 'http://10.1.248.41/TFM-Project/ImportINjson.php',
dataType: 'json',
data: function (params) {
var query = {
search: params.term,
type: 'public'
}
console.log("query : "+query.search);
return query;
},
processResults: function (response) {
console.log("response : "+response);
return {
results: $.map(response, function(obj) {
console.log("response obj.id: "+obj.id);
console.log("response obj.text: "+obj.text);
return { id: obj.id, text: obj.text };
})
};
},
cache: false
}
});
});
I have 1 php page which establishes connection to the database and fetches data from the database using JSON array (this code is working fine).
index2.php
<?php
class logAgent
{
const CONFIG_FILENAME = "data_config.ini";
private $_dbConn;
private $_config;
function __construct()
{
$this->_loadConfig();
$this->_dbConn = oci_connect($this->_config['db_usrnm'],
$this->_config['db_pwd'],
$this->_config['hostnm_sid']);
}
private function _loadConfig()
{
// Loads config
$path = dirname(__FILE__) . '/' . self::CONFIG_FILENAME;
$this->_config = parse_ini_file($path) ;
}
public function fetchLogs() {
$sql = "SELECT REQUEST_TIME,WORKFLOW_NAME,EVENT_MESSAGE
FROM AUTH_LOGS WHERE USERID = '".$uid."'";
//Preparing an Oracle statement for execution
$statement = oci_parse($this->_dbConn, $sql);
//Executing statement
oci_execute($statement);
$json_array = array();
while (($row = oci_fetch_row($statement)) != false) {
$rows[] = $row;
$json_array[] = $row;
}
json_encode($json_array);
}
}
$logAgent = new logAgent();
$logAgent->fetchLogs();
?>
I created one more HTML page where i am taking one input (userid) from the user. Based on userid, i am fetching more data about that user from the database. Once the user enters userid and clicks on "Get_Logs" button, more data will be fetched from the the database.
<!DOCTYPE html>
<html>
<head>
<title>User_Logs</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$uid =$_POST["USERID"];
}
?>
<form method="POST" id="form-add" action="index2.php">
USER_ID: <input type="text" name="USERID"/><br>
<input type="submit" name="submit" id = "mybtn" value="Get_Logs"/>
</form>
</body>
</html>
My script:
$(document).ready(function(){
$("#mybtn").click(function(){
$.POST("index2.php", {
var myVar = <?php echo json_encode($json_array); ?>;
});
});
})
This code is working fine. However it is synchronous POST & it is refreshing my page, However i want to use asynchronous POST. How can i do that? I have never done this asynchronous POST coding. Kindly help.
i tried this & it not throwing error but there is no output. Can someone please check what is wrong in my code.
$(document).ready(function(){
$("#mybtn").click(function(e){
e.preventDefault();
$.post("index2.php", {data :'<?php echo json_encode($json_array);?>'
})
});
})
I assume that index2.php is another php page (not the same) and it is returning the data that you want to update on the page where you run this code on.
$(document).ready(function(){
$("#mybtn").click(function(e){
e.preventDefault();
$.POST("index2.php", {
var myVar = "<?php echo json_encode($json_array); ?>";
});
});
})
you need to add preventDefault in your click handler to prevent the form from being submitted. This will stop the form to be submitted and the page to be reloaded. Inside the POST you can setup the logic to refresh the page with the updated data (without reloading)
Can you try this,
$(document).ready(function(){
$("#mybtn").click(function(event){
event.preventDefault();
$.POST("index2.php", {
var myVar = <?php echo json_encode($json_array); ?>;
});
});
});
Also in HTML remove action in form
<form method="POST" id="form-add">
USER_ID: <input type="text" name="USERID"/><br>
<input type="submit" name="submit" id = "mybtn" value="Get_Logs"/>
</form>
Edit :
Can you try this please ? Second param for post takes an object .
$(document).ready(function(){
$("#mybtn").click(function(event){
event.preventDefault();
var myVar = <?php echo json_encode($json_array); ?>;
console.log(myVar);
$.post("submit.php", {
'id': myVar
},function(data){
console.log(data);
});
});
});
I want to submit data through ajax to the database and after inserting data into database this data should be displayed on the file Demo.html dynamically at the last i.e., after div in my case.
Well storing data through ajax i have done but i don't know how to display this newly inserted data to Demo.html.So do guide me how to achieve this.
Below is my code.
AjaxFile.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body >
<p><span id="get">Ajax response comes here</span></p>
<div id="divId">
<input type="text" name="i1" value="" /><br />
<input type="text" name="i2" value="" /><br />
<button onclick="ajaxFunction()">Click </button>
</div>
<script src="jquery-3.2.1.min.js" ></script>
<script type="text/javascript">
function ajaxFunction() {
$(function(){
var myData1 = $("input[name='i1']").val();
var myData2 = $("input[name='i2']").val();
$.ajax({
type : "post",
dataType : "text",
url : "controller.php",
data : { data1 : myData1, data2 : myData2},
success : function(msg){
document.getElementById('get').innerHTML = msg;
}
});
});
}
</script>
</body>
</html>
controller.php
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$databaseName = "mydb1";
try {
$conn = new PDO("mysql:host = $servername; dbname = $databaseName", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$conn->exec("use mydb1");
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['data1']) && isset($_POST['data2'])) {
$data1 = $_POST['data1'];
$data2 = $_POST['data2'];
$statement = $conn->prepare("Insert into mytable (data1, data2) values (:data1 , :data2)");
if( $statement->execute(array("data1"=>"$data1", "data2"=>"$data2")) ) {
echo "successfully inserted";
// want to display $data1 and $data2 at the last in Demo.html just after inserting.
} else {
echo "Not successfully inserted";
}
} else {
echo "something is not set";
}
}catch(PDOException $e) {
echo "connection failed ". $e->getMessage();
}
$conn = null;
?>
Demo.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style type="text/css">
body {
margin : 0;
}
#first {
width : 100%;
height : 100px;
margin : 30px auto auto auto;
border : 1px dashed black;
}
</style>
</head>
<body>
<div id="first" align="center"> I want to display newly inserted data below this div</div>
</body>
</html>
My solution does not involve php but JQuery & HTML5 LocalStorage and most importantly it will solve your issue.
Firstly inside your success function of ajaxFunction() you should store the value of data1 and data2 in Localstorage variables. Read about LocalStorage here
ajaxFunction()
$.ajax({
type : "post",
dataType : "text",
url : "controller.php",
data : { data1 : myData1, data2 : myData2},
success : function(msg){
document.getElementById('get').innerHTML = msg;
// store your values in LocalStorage
localStorage.setItem("StoredData1", myData1);
localStorage.setItem("StoredData2", myData2);
// redirect after storing
window.location.href = 'Demo.html'
}
});
Then in a script included in Demo.html or directly in its HTML write the below JavaScript code to fetch the LocalStorage variables we stored earlier and append to the div.
HTML body in Demo.html
<body>
<div id="first" class="afterThis" align="center"> I want to display newly inserted data below this div</div>
</body>
JavaScript in Demo.html
$(".afterThis").last().after("<div class='afterThis'>"+ localStorage.getItem("StoredData1") +"</div>");
$(".afterThis").last().after("<div class='afterThis'>"+ localStorage.getItem("StoredData2") +"</div>");
after insert to database use function file() to save to file with append subfunction, that write new row to your file, and the read file in demo.html -< BUT this need to be php file and php function to read your last inserted data, then simple redirection in ajax in success: section to your file, or for example read file to div exaclly where you want.
In your controller php use function file to save in append mode string to your file. look here: http://php.net/manual/en/function.file-put-contents.php
And after this call ajax to get for example read.php inside php use file() of php to read this file what you writed before.
It's based on answer from #Nikhil Nanjappa.
You can use an array to store more items in localStorage.
Store object in localStorage.
AjaxFile.html
success: function(msg) {
document.getElementById('get').innerHTML = msg;
StoredData = JSON.parse(localStorage.getItem("StoredData"));
if(!StoredData) StoredData = [];
StoredData.push(myData1);
StoredData.push(myData2);
localStorage.setItem("StoredData", JSON.stringify(StoredData));
window.location.href = 'Demo.html'
}
Demo.html (At the bottom of the body)
<script type="text/javascript">
StoredData = JSON.parse(localStorage.getItem("StoredData"));
StoredData.reverse().forEach( function(data) {
$('#first').after('<div>data = ' + data +'</div>')
});
</script>
Hello I'm trying to do a mysql query with ajax based on two select options in a joomla component I'm working on.
I don't want to post the whole HTML so I shortend it. I checked the values are passed trough to the php but I get nothing in return.
So this is the php and the js:
<html>
<head>
<!-- load necessary files here -->
</head>
<?php
function firstQuery(){
if(isset($_POST['adr'])){
$one = $_POST['adr']; //adr is the name of the first select
$two = $_POST['toadr']; //toadr is the name of the second select
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select(array('range', 'time', 'cost'));
$query->from('#__transfer_rang');
$query->where('from="'.$one.'" AND to="'.$two.'"');
$db->setQuery($query);
$results = $db->loadObjectList();
print_r($results);
exit;
}
}
firstQuery();
?>
<body>
<script>
$(function=(){
$("#click").click(function () {
$.ajax({
type: "POST",
data: $("#myform").serialize(),
success: function(data){
$('#test').html(data);
}
});
});
});
</script>
<div id="test">
</div>
<form id="myform" method="post" action=""><!-- form stuff here --></form>
</body>
What am I missing?
I am trying to create a feature on my website that automatically updates the database onchange of the textarea below (which is going to be act as a 'post-it note for reminders'). I am new to ajax, and I was wondering if someone can show me a basic example of how I would make an AJAX call to update my database onChange of the textarea below?
<?php
//Create mysql connect variable
$conn = mysql_connect('samplesource.com', 'example', 'pass');
//kill connection if error occurs
if(!$conn){
die('Error: Unable to connect.' . '<br>' . mysql_error());
}
//connect to mysql database
mysql_select_db("mydb", $conn);
session_start();
$userid = $_SESSION['id'];
$results = ("SELECT * FROM notes WHERE userid='$userid'");
?>
<html>
<head>
<title>practice</title>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".sometext").change(function(){
//make ajax call to update database onChange
});
});
</script>
</head>
<body>
<textarea class="note" style="resize:none; width:300px; height:200px;"> </textarea>
</body>
</html>
First, you'd need to move your database save script into a new file e.g save.php
On your <textarea> i'd add
<textarea onchange="saveChanges(this);"></textarea>
For the javascript save function that's called when a change is made:
function saveChanges(object){
$.ajax({
url: 'save.php',
data: 'content=' + object.value,
cache: false,
error: function(e){
alert(e);
},
success: function(response){
// A response to say if it's updated or not
alert(response);
}
});
}
This is a very quick and dirty way of doing it.