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>
Related
I'am trying to get php response data with ajax. I want to check if there is a specific string in testing.txt from my input and if the string is found, php should echo "1" but no matter what I try AJAX always says the output isn't 1
This is my code:
<?php
if (isset($_POST['table'])) {
$file = file("testing.txt");
if (in_array($_POST['table'], $file)) {
echo "1";
} else {
echo "0";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<input type="text" name="text" id="text">
<button id="button">NEXT</button>
<script type="text/javascript" src="jquery.js"></script>
<script>
var text;
document.getElementById('button').onclick = function () {
text = document.getElementById('text').value;
post(text);
};
function post(vally) {
var table = vally;
$.post('test.php', {table:table}, function(data) {
})
.done(function (data) {
if (data == 1) {
console.log("the output is 1")
} else {
console.log("the output isn't 1")
}
});
console.log('posted');
}
</script>
</body>
</html>
testing.txt:
abc
def
ghi
The response I get if i console.log(data):
0<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<input type="text" name="text" id="text">
<button id="button">NEXT</button>
<script type="text/javascript" src="jquery.js"></script>
<script>
var text;
document.getElementById('button').onclick = function () {
text = document.getElementById('text').value;
post(text);
};
function post(vally) {
var table = vally;
$.post('test.php', {table:table}, function(data) {
})
.done(function (data) {
if (data == 1) {
console.log("the output is 1")
} else {
console.log(data)
}
});
console.log('posted');
}
</script>
</body>
</html>
I have tried using .done(), .fail() and .always() but I always get the output isn't 1(I am using JQuery 3.2.1).
Can someone tell me what I'm doing wrong?
EDIT: I would like to point out something I haven't before. I'm looking for a one page solution. I know that it can easily be done with two pages but I was wondering if there was a one page solution.
The problem is the Ajax request is sent to the home page, so it receives everything after '0' or '1'. Split that.
Move your PHP code in anoter file, say 'ajax.php'
And change your $.post() settings to call ajax.php instead of test.php.
So the Ajax request will only receive the '0' or '1' string.
Notice how your AJAX response is the entire page, prepended with the single digit that you're looking for. You don't need to send the whole page to the browser twice. Move your PHP logic into its own file with nothing but that logic. Let's call it checkTable.php for the sake of demonstration:
<?php
if (isset($_POST['table'])) {
$file = file("testing.txt");
if (in_array($_POST['table'], $file)) {
echo "1";
} else {
echo "0";
}
}
?>
Then make your AJAX call to that page:
$.post('checkTable.php', {table:table})
Then the response will contain only what that PHP code returns, not the whole page. (It's worth noting that this PHP code will return an empty response if table isn't in the POST data.)
Aside from that, your code is currently returning a 0 for whatever input you're providing, so it's still going to be true that "the output isn't 1". For that you'll need to double-check your input and data to confirm your assumptions.
Because I wanted everything in one file I decided to use data.slice(0, 1); to trim off everything except the first character which will be a 0 or 1, and thanks to David for reminding me that there may be a whitespace issue, which there was. Now I added text.trim() to remove all of the whitespace from the input and array_filter(array_map('trim', $file)); to remove all of the whitespace from the strings written in the file.
This is the finished code:
<?php
if (isset($_POST['table'])) {
$file = file("testing.txt");
$file = array_filter(array_map('trim', $file));
if (in_array($_POST['table'], $file) == true) {
echo "1";
} else {
echo "0";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<input type="text" name="text" id="text">
<button id="button">NEXT</button>
<script type="text/javascript" src="jquery.js"></script>
<script>
var text;
document.getElementById('button').onclick = function () {
text = document.getElementById('text').value;
post(text.trim());
};
function post(vally) {
var table = vally;
console.log(vally);
$.post('test.php', {table:table}, function(data) {
var cut = data.slice(0, 1);
if (cut == 1) {
console.log("the output is 1")
} else {
console.log(cut);
}
});
console.log('posted');
}
</script>
</body>
</html>
I would like to thank everyone who helped me resolve my issue, which has been bugging me for the last 2 days.
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'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 );
?>
I'm new to PHP and Javascript/Ajax so please bear with me.
All I need to do is get a variable from Ajax and set it as a variable in php. I'm trying to do this with a super global GET but something is not right. I don't want to this by submitting the form.
Here's my JS:
function myFunction(){
var hora= document.getElementById("hora").value;
$.ajax({
type : 'GET',
url : 'reservation.php',
data : {hora: hora},
success : function(data) {
console.log(hora);//This is because I was curious as to
// what the console would say. I found
// that this sets the super global if I
// change the url to something else that
// doesn't exist. Console would say
// -GET http://localhost/bus/(somepage).php?hora=4
// 404 (Not Found)-
alert(hora);
}
})
}
Here's my PHP:
Hora:
<select name="hora" id="hora" onchange="myFunction()">
<?php
$query = "SELECT * FROM vans";
$horas_result = mysql_query($query);
while ($horas = mysql_fetch_array($horas_result)) {
echo "<option value=\"{$horas["van_id"]}\">{$horas["time"]}</option>";
}
?>
</select>
Asientos Disponibles:
<?php echo $_GET["hora"]; ?>
//Right now I only want to echo this variable..
As you can see, right now I only want to echo this variable, later on I'll be using this to write a query.
Look at the code i post, ajax is used to post/get data without need to refresh the page but if you just want to post the data and give the result in other page use a form instead.
<?php
if (isset($_GET["hora"]))
{
echo $_GET["hora"];
exit;
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Page title</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function()
{
$("#hora").change(function ()
{
$.ajax(
{
type : 'GET',
url : '',
data : $('select[name=\'hora\']'),
success : function(data)
{
$('#ajax_result').html('Asientos Disponibles: ' + data);
},
error: function(xhr, ajaxOptions, thrownError)
{
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
}
)
}
)
}
)
</script>
<select name="hora" id="hora">
<?php
$query = "SELECT * FROM vans";
$horas_result = mysql_query($query);
while ($horas = mysql_fetch_array($horas_result)) {
echo "<option value=\"{$horas["van_id"]}\">{$horas["time"]}</option>";
}
?>
</select>
<div id="ajax_result">
</div>
</body>
</html>
For example, the following script
$.ajax({
type: "POST",
url: "test.php",
data: {value:1}
}).done(function(msg) {
// msg contains whatever value test.php echoes. Whether it is code, or just raw data.
if(msg=="Success") {
alert("hello world");
} else {
alert("Hello Hell")
}
});
Will set the variable $_POST['value'] to 1
and my test.php looks like:
<?php
if($_POST['value'] == "1") {
echo "Success";
} else {
echo "Failure";
}
?>
If you run that example, the webpage will show you an alert box with the text "Hello World"
If you change the value to any other number, it will show you an alert with the text "Hello Hell"
Hope that answers your question.