Replicate the same data request query, but use a JavaScript Ajax post so that it doesn’t refresh the page on button press, just requests another page and display in a section on the page.
i need some help changing this to a ajax post
my code
*<?php
if(isset($_POST['submit']))
{
$success = $_POST['success'];
$dates = $_POST['dates'];
$datee = $_POST['datee'];
/*** mysql hostname ***/
$hostname = 'localhost';
$dbname = '*******';
/*** mysql username ***/
$username = 'root';
/*** mysql password ***/
$password = '*******';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$tablename = 'login_attempts';
$sql = 'SHOW COLUMNS FROM `'.$tablename.'`';
$fields = array();
$csv = array();
$stmt = $dbh->query($sql);
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
array_push($fields, $row['Field']);
}
array_push($csv, $fields);
$success = mysql_real_escape_string($success);
$sql = "SELECT * FROM $tablename WHERE success = '".$success."' AND attempted >='".$dates."' AND attempted <='".$datee."'";
$stmt = $dbh->query($sql);
$stmt->execute();
$csv = array();
while($row = $stmt->fetch(PDO::FETCH_NUM))
{
array_push($csv, $row);
}
$fp = fopen('file.csv', 'w');
foreach ($csv as $row) {
fputcsv($fp, $row);
}
fclose($fp);
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=export.csv");
header("Pragma: no-cache");
header("Expires: 0");
readfile('file.csv');
$dbh = null;
} catch(PDOException $e) {
echo $e->getMessage();
}
exit();}
?>
<html>
<head>
<title>csv with criteria</title>
</head>
<body>
<form action="csv2.php" method="post" enctype="multipart/form-data">
Select data range
<br>
<input type="date" name="dates" id="dates"> Starting date
<br>
<input type="date" name="datee" id="datee"> Ending date
<br>
Select what data you'd like
<br>
<input type="radio" name="success" value="1" checked> Yes<br>
<input type="radio" name="success" value="0"> No<br>
<input type="submit" value="show" name="submit">
<br>
</form>
</body>
</html>*
If you want to use AJAX request on form submit you should:
Import the jQuery library: e.g. <script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
Create a new JavaScrpit file where you will catch the form submit event, send jQuery request and analize the response, e.g.:
$(document).ready(function(){
$("#myForm").submit(function(e){
e.preventDefault(); //stop sending the form
//here you should validate your form
//submit it via AJAX:
$.ajax({
url: "csv2.php",
data: { dates: $("#dates").val(), datee: $("#datee").val(), $('input[name='success']:checked', '#myForm').val() }
})
})
});
You can use another functions of AJAX object such as success or error callback functions: jQuery.ajax(). Don't forget to add ID to your form.
You can see this post where it's explained how to make a good ajax call to POST parameters. But you will need to separate this portion of code :
<?php
if(isset($_POST['submit']))
{
$success = $_POST['success'];
$dates = $_POST['dates'];
$datee = $_POST['datee'];
/*** mysql hostname ***/
$hostname = 'localhost';
$dbname = '*******';
/*** mysql username ***/
$username = 'root';
/*** mysql password ***/
$password = '*******';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$tablename = 'login_attempts';
$sql = 'SHOW COLUMNS FROM `'.$tablename.'`';
$fields = array();
$csv = array();
$stmt = $dbh->query($sql);
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
array_push($fields, $row['Field']);
}
array_push($csv, $fields);
$success = mysql_real_escape_string($success);
$sql = "SELECT * FROM $tablename WHERE success = '".$success."' AND attempted >='".$dates."' AND attempted <='".$datee."'";
$stmt = $dbh->query($sql);
$stmt->execute();
$csv = array();
while($row = $stmt->fetch(PDO::FETCH_NUM))
{
array_push($csv, $row);
}
$fp = fopen('file.csv', 'w');
foreach ($csv as $row) {
fputcsv($fp, $row);
}
fclose($fp);
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=export.csv");
header("Pragma: no-cache");
header("Expires: 0");
readfile('file.csv');
$dbh = null;
} catch(PDOException $e) {
echo $e->getMessage();
}
exit();}
?>
into one another php file.
Related
Here is my code, and while running it's not giving anything in the console.
This is how I am trying to check the data. If the data correctly I want the mentioned console in success code. But if it is not then I want else code to run. But the if-else conditions are not working properly. I am including PHP code and ajax code which I have tried. Am I doing it right?
<?php
$host = "dpydaldermt01.******.com";
$username = "test";
$password = "Test";
$database_name = "test";
$conn = mysqli_connect($host, $username, $password, $database_name) or die("Connection failed: " . mysqli_error());
$sql = "select ID, user_email from ci_iwp_wp_users limit 10";
$result = mysqli_query($conn, $sql);
$users = array();
?>
<script>
(function($) {
<?php
while($row = mysqli_fetch_assoc($result)) {
$email = $row['user_email'];
?>
var mail = "<?php echo $email ?>";
$.ajax({
type:'POST',
url:'http://bluepages.ibm.com/BpHttpApisv3/wsapi?byInternetAddr='+mail,
dataType:'someData',
success: function(data) {
if(data === '# rc=0, count=0, message=Success') {
console.log(data);
}
}
});
<?php
$users[]=$row;
}
?>
});
</script>
<?php
echo json_encode($users);
?>
Just Remove dataType:'someData', from your code because it always request and response in json so you dont have to declare separately.
What I'm trying to do is very simple.
Have a simple input, that allows me to input a name+link, add it to a list and save it to a DB so it's saved.
In my HTML file I currently have:
<form id="form">
<input id="create-input" type="text" placeholder="To do">
<input id="create-link" type="text" placeholder="http://">
<button id="submit" type="button">Add Item</button>
</form>
In my JS file I have:
$(function(){
$('#submit').on('click', addListItem);
});
function addListItem() {
// Grab Input Data
var text = $('#create-input').val();
var link = $('#create-link').val();
// Creating To Do List
$('#todo').append('<li>' +text+' - '+link+ ' <button class="delete">Edit</button> <button class="delete">Delete</button> <button class="delete">Bukkaked!</button></li>');
$('#create-input').val('');
$('#create-link').val('http://');
}
In my PHP file (connecting to DB) I have:
<?php
$servername = "localhost";
$database = "bucketlist";
$username = "bucketuser";
$password = "125632";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$sql = "INSERT INTO bucketlist (item, link) VALUES ('Thom', 'www.google.com')";
// Check for Success
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
}
// Check for Fail
else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Now I know I need to somehow pass the vars (text and link) through to the PHP file:
$sql = "INSERT INTO bucketlist (item, link) VALUES ('Thom', 'www.google.com')";
But I have no idea how.
Any tips?
Why do you need JQuery you can pass values using php only
here is a change in your code:-
<form id="form" method="post" action="process.php">
<input id="create-input" name="item" type="text" placeholder="To do">
<input id="create-link" name="link" type="text" placeholder="http://">
<button id="submit" type="button">Add Item</button>
</form>
<ul>
<?php include('conn.php');
$sql = "SELECT * FROM bucketlist";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<li>Item-'. $row["item"].' & Link-'. $row["link"].'</li>';
}
} else {
echo "<li>No List</li>";
}
?>
</ul>
conn.php
<?php
$servername = "localhost";
$database = "bucketlist";
$username = "bucketuser";
$password = "125632";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
process.php
<?php
include('conn.php');
$item = $_POST['item'];
$item = $_POST['link'];
$sql = "INSERT INTO bucketlist (item, link) VALUES ($item,$link)";
// Check for Success
if (mysqli_query($conn, $sql)) {
header('location:yourpage.php');
}
// Check for Fail
else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Hope this helps.
Use ajax to post the values of the item and link in your html form to your PHP script.
Something like :
var myItem = $('#create-input').html();
var myLink = $('#create-link').html();
$.ajax({
type: 'POST',
url: 'https://yoururl/api/post.php',
data: {item:myItem,link:myLink},
success: SuccessCall,
error : FailureCall,
cache:false,
async:true,
dataType: 'html'
});
function SuccessCall(data,status){
alert("response from server is "+data);
}
function FailureCall(data,status){
alert("Server connection error");
}
Use the PHP script posted by SYB to retrieve the values of item and link that were sent from your html form.
i want to fetch data from my database which is linked to the website,i have created a search box,whenever i enter a particular value in search box,it should display all the related content from the database.i have done the following code,it is not fetching the data from the database,it just shows a blank screen.
<?php
define('db_name','njgh');
define('db_user','root');
define('db_password','');
define('db_host','localhost');
session_start();
$link=mysql_connect(db_host,db_user,db_password);
if(!$link)
{
die('couldnot connetc:'.mysql_error());
}
$db_selected=mysql_select_db(db_name,$link);
if(!$db_selected)
{
die('cant connect to db');
}
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
$value = clean($_POST['searchtext']);
$qry = "SELECT * FROM database WHERE Site_ID = '$value'";
$result = mysql_query($qry);
print_r($result);
mysql_query function return resource ID not your data , use mysql_fetch_array, mysql_fetch_object to get data
$value = ($_POST['searchtext']);
$result = mysql_query("SELECT * FROM database WHERE Site_ID = '$value'");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
printf("ID: %s Name: %s", $row[0], $row[1]);
}
mysql_* has been removed entirely as of PHP 7.0. Prevent SQL injection and use the mysqli statement class.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "njgh";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$value = $_POST['searchtext'];
/* create a prepared statement */
if($stmt = $conn->prepare("SELECT * FROM database WHERE Site_ID =?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $value);
/* execute query */
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row['db_table_field_name'];
}
//or
$row = $result->fetch_assoc();
print_r($row);
} else {
}
/* close statement */
$stmt->close();
}
/* close connection */
$con->close();
?>
The original MySQL extension is now deprecated, and will generate E_DEPRECATED errors when connecting to a database. Instead, use the MySQLi or PDO_MySQL extensions.
Hope this will work for you......
<?php
define('db_name','sports');
define('db_user','root');
define('db_password','');
define('db_host','localhost');
$link=mysqli_connect(db_host,db_user,db_password,db_name);
if(!$link)
{
die('couldnot connect:'.mysql_error());
}
function clean($str) {
$link=mysqli_connect(db_host,db_user,db_password,db_name);
$str = #trim($str);
if(get_magic_quotes_gpc())
$str = stripslashes($str);
return mysqli_real_escape_string($link, $str);
}
if(isset($_POST['searchtext'])){
$value = clean($_POST['searchtext']);
$qry = "SELECT * FROM cricket WHERE id = '$value'";
$qrydb = mysqli_query($link, $qry);
while($row=mysqli_fetch_array($qrydb)){
$name = $row['name'];
}
echo $name ;
}
?>
<body>
<form method="post">
<input type="text" name="searchtext">
<input type="submit" name="submit">
</form>
</body>
I am selecting input values from the database and I want to send it to the javascript function addVal() so that I can retrieve this value. I do not want to use echo. It is not working right now and I don't know how I can make it work.
<h1>trial,</h1>
<div id ="val"> </div>
<?php
$name = $_POST['postname'];
$host = 'localhost';
$user = 'root';
$pass = 'root';
$db_name="big";
$conn = new mysqli($host, $user, $pass, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "connected";
$sql = "SELECT input FROM trial_db";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while( $row = $result->fetch_assoc()) {
$value = $row['input'];
addVal ($value);
}
}
?>
<script>
function addVal (value){
document.getElementById("val").innerHTML+= value ;
}
</script>
Calling js function from php will not work remove that code from php.
And change in js.
<script>
function addVal (){
var value = "<?php echo $value; ?>";
document.getElementById("val").innerHTML+= value ;
}
</script>
Will only work if js and php codes are in same php file.
I am new with ajax somebody help me I want to create a form that include input field.
Whenever I click the button I will get the value of input field and it declared it as data in AJAX and the value from ajax it pass to PHP script. It will display a table.
My question is how to get the value of input field and declared it as data in AJAX. After click the table will declared in success in AJAX Script that will show a table.
Thank you in advance
UPDATE:
#J_D, Here's my html code for my form:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<table cellpadding="15px">
<tr>
<td>Transmittal #</td>
<td><input type="text" class="form-control" style="padding-left:5px;" name="transmittal_number_inquiry" id="transmittal_number_inquiry" class="transmittal_number_inquiry" onKeyPress="return isNumberKey(event)" required></td>
</tr>
</table>
<div style="float:right; padding-right:110px; padding-top:10px;">
Inquire
<?php /*?><input type="submit" class="btn btn-info" data-toggle="modal" id="btn-inquire-transmittal-number" name="btn-inquire-transmittal-number" data-backdrop="false" value="Inquire"><?php */?>
<?php /*?><button type="submit" class="btn btn-info" data-toggle="modal" id="btn-inquire-transmittal-number" name="btn-inquire-transmittal-number" data-backdrop="false">Inquire</button><?php */?>
</div>
</form>
Here's my AJAX Code:
$(document).ready(function(){
$('.btn-inquire-traensmittal-number').click(function(){
$inputtextval = $('#transmittal_number_inquiry').val();
$.ajax({
type: 'POST',
url: getTransmittalNum.php,
data: {'transmittal_number_inquiry' : $inputtextval},
success: function(res){
}
});
});
});
Here's the getTransmittalNum.php code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "etransmittal";
$selectedTransmittal = $_GET['q'];
$con = mysqli_connect($servername,$username,$password,$dbname);
if(!$con){
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST['inquire-transmittal-number'])){
$query = "SELECT en.transid, en.transdate, CONCAT(userlist.lname, ', ', userlist.fname, ' ', userlist.mname) AS sender_name,
userlist.`department`, en.document_number, doctype.document_type, doctype.document_description, vendor.`vendor_name`, en.`remarks`,
en.status_id, stat.status_name, en.total_amount
FROM tbl_encode_transmittal en
LEFT JOIN tbl_vendor vendor ON vendor.`vendor_id` = en.vendor_id
LEFT JOIN tbl_doctype doctype ON doctype.`doc_id` = en.doctype_id
LEFT JOIN tbl_userlist userlist ON userlist.userid = en.sender_id
LEFT JOIN tbl_userlist userlist1 ON userlist1.userid = en.`receiver_id`
LEFT JOIN tbl_status stat ON stat.status_id = en.status_id
WHERE en.`transid` = '{$_POST['transmittal_number_inquiry']}'";
$result = mysqli_query($con, $query);
$rows = array();
if($result){
while($row = mysqli_fetch_assoc($result)){
$rows[] = $row;
}
}
else{
echo 'MYSQL Error: ' . mysqli_error();
}
$json = json_encode($rows);
echo $json;
mysqli_close($con);
}
?>
Try following code :
$(document).ready(function(){
$('#btn-inquire-transmittal-number').click(function(){
$inputtextval = $('#transmittal_number_inquiry').val();
$.ajax({
type: 'POST',
url: 'getTransmittalNum.php', // wrap code with quote
data: {'transmittal_number_inquiry' : $inputtextval},
dataType : 'json', // expecting result type json
success: function(res){
// once you got result,
// populate table here
}
});
});
});
PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "etransmittal";
//$selectedTransmittal = $_GET['q']; //<---- u need this?????
$con = mysqli_connect($servername,$username,$password,$dbname);
if(!$con){
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST['transmittal_number_inquiry'])){ // <-- check for existence
$query = "SELECT en.transid, en.transdate, CONCAT(userlist.lname, ', ', userlist.fname, ' ', userlist.mname) AS sender_name,
userlist.`department`, en.document_number, doctype.document_type, doctype.document_description, vendor.`vendor_name`, en.`remarks`,
en.status_id, stat.status_name, en.total_amount
FROM tbl_encode_transmittal en
LEFT JOIN tbl_vendor vendor ON vendor.`vendor_id` = en.vendor_id
LEFT JOIN tbl_doctype doctype ON doctype.`doc_id` = en.doctype_id
LEFT JOIN tbl_userlist userlist ON userlist.userid = en.sender_id
LEFT JOIN tbl_userlist userlist1 ON userlist1.userid = en.`receiver_id`
LEFT JOIN tbl_status stat ON stat.status_id = en.status_id
WHERE en.`transid` = '{$_POST['transmittal_number_inquiry']}'";
$result = mysqli_query($con, $query);
$rows = array();
if($result){
while($row = mysqli_fetch_assoc($result)){
$rows[] = $row;
}
}
else{
echo 'MYSQL Error: ' . mysqli_error();
}
$json = json_encode($rows);
echo $json;
mysqli_close($con);
}
?>