Send data to the server with AJAX - mysql

I want some help with the following issue. The following code is not working for me. Is there anyone who can help me with that? I've watched this in a youtube video and i can't find why it is not running..
I want to inform you that i am running a WAMP Server at 127.0.0.1 and it is very weird that the browser does not give me any response for errors, etc..
Here is my PHP code:
<?php
$host="127.0.0.1";
$username = "root";
$password = "";
$db = "data";
$conn = mysqli_connect($host, $username, $password, $db);
if (isset($_POST['fname'])){
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$gender = $_POST['slct'];
$query = "Insert into users (firstname, lastname,gender) Values(?,?,?))";
$stmt = $conn->prepare($query);
$stmt->bind_param('sss', $fname, $lname, $gender);
$stmt->execute();
if(mysqli_affected_rows($conn) > 0){
echo "insert";
}
else{
echo "no";
}
}
?>
Here is my html code:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<h3> Insert Data into Database</h3>
<form id="form1" method="post">
<p> Enter FirstName</p>
<input type="text" name="fname" class="form-control">
<br>
<p> Enter lastName</p>
<input type="text" name="lname" class="form-control">
<br>
<p>Enter Gender</p>
<select class="form-control" name="slct">
<option value="Male">Male </option>
<option value="Female">Female</option>
</select>
<br><br><br>
<button class="btn btn-primary" onclick="insertData()">Submit</button>
</form>
</body>
<script>
function insertData(){
var formData = $('#form1').serialize();
$.ajax({
url:'http://127.0.0.1/PHP/insert.php',
data:formData,
type:'Post',
success:function(response){
console.log(response);
},
error:function(err){
console.log(err);
}
})
}
</script>
</html>
Any help will be appreciate.
Thank you in advance!

Your insert-command is incorrect. Change ...(?,?,?))"; to ...(?,?,?)";
Better use an IDE like netbeans, because they would highlight such errors. Also you should switch from mysqli to PDO. And you don't need to check affected rows. The $stmt->execute() returns a boolean

Related

When submiting html form, dont open new page but show pop-up window

I have a form with a submit button. When i click this button i dont want to be redirected to the page connection.php, that is listed in action="". But insteed i want it to just show pop-up window that says successful or not successful, and let the connection2.php do its thing in the background.
HTML:
<form action="connection2.php" method="post">
<input type="date" name="date" placeholder="Name" required="">
<input type="submit" name="submit" id="submit" class="strelka-send" value="Insert">
<div class="clear"> </div>
</form>
CONNECTION2.PHP:
<?php
# Connection
$servername = "";
$connectionInfo = array(
"Database"=>"",
"UID"=>"",
"PWD"=>""
);
$conn = sqlsrv_connect($servername, $connectionInfo);
if( $conn === false ) {
echo "Error (sqlsrv_connect): ".print_r(sqlsrv_errors(), true);
exit;
}
# Parameters
$Date = $_POST['date'];
$params = array
(&$Date);
# Statement
$sql = "INSERT INTO table([Date]) VALUES
(?)";
$stmt = sqlsrv_prepare($conn, $sql, $params);
if ($stmt === false) {
echo "Error (sqlsrv_prepare): ".print_r(sqlsrv_errors(), true);
exit;
}
if (sqlsrv_execute($stmt)) {
echo "Statement executed.\n";
} else {
echo "Error (sqlsrv_execute): ".print_r(sqlsrv_errors(), true);
}
# End
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
?>
<!DOCTYPE html>
<html>
<body>
<br>
<h1>SUCCESS</h1>
<script>
setInterval(function(){
window.location.href="link_to_index.html" }, 5000);
</script>
</body>
</html>
So far i have set timer on the page connection2.php that opens after form is submited, and then goes back to previous page. But it is not the nicest solution.
if you dont want redirection in form submit , you have to use AJAX technology for example JQUERY
take a look at Submitting HTML form using Jquery AJAX
Use this code to submit the form into a popup window.
This code submits the form to a popup window after its submission.
<form action="connection2.php" method="post" target="popupwindow" onsubmit="window.open('connection2.php', 'popupwindow', 'scrollbars=yes,width=550,height=520');return true">
<input type="date" name="date" placeholder="Name" required="">
<input type="submit" name="submit" id="submit" class="strelka-send" value="Insert">
</form>
I haven't tested this code.
But hoping that this will work for you.

Save PHP Session data across different directories

I'm trying to save PHP session data across directories. This code does not work for me and I need it to redirect to a different directory.
index.html:
<html>
<form action='login.php' method='get'>
Username: <input type='text' name='user' /><br>
Password: <input type='password' name='pass' /><br>
<input type='submit' />
</form>
</html>
login.php:
<?php
$user = $_POST['user'];
$conn = mysqli_connect('localhost', 'root' ,'a91c95n00', 'db_games2');
$sql = "SELECT username FROM userdata WHERE username='$user'";
$query = mysqli_query($conn, $sql);
$count = mysqli_num_rows($query);
if ($count == 0){
session_start();
$_SESSION['user'] = $user;
header('location:games.php');
}elseif ($count == 1){
header ('location:error.html');
}
?>
games.php:
<?php
session_start();
session_save_path('/var/www/html/1/');
session_save_path('/var/www/html/2/');
?>
<html>
<a href='http://76.29.204.37/1'>Product 1</a><br>
<a href='http://76.29.204.37/2'>Product 2</a>
</html>
/1/index.php
<?php
session_start();
if (!isset($_SESSION['user'])){
header ('location:error.html');
}elseif (isset($_SESSION['user'])){
header('location:success.php');
}
?>
Every time I go to the product 1 directory, it goes to error.html..
When a session is set, it is supposed to go to success.php. Please help me! Thanks!

AUSU jquery-Ajax Autosuggest Multiple values

I have a form which has the following fields:
Company Name,
Address,
City
Using the AUSU jquery autosuggest scripts I am able to populate the address field based on the search done in the company field but what I can't seem to be able to accomplish is also populating the city field with the appropriate value. All data is stored in a mysql database.
I've gotten as far as being able to have the address and city populate the address field but I need these 2 values to go into their respective fields (shiptoaddress and shiptocity).
Any suggestions?
This is my php to obtain data from mysql database:
<?php
$con = mysql_connect("localhost","userid","password");
if (!$con){ die('Could not connect: ' . mysql_error()); }
mysql_select_db("dbase", $con);
$id = #$_POST['id']; // The id of the input that submitted the request.
$data = #$_POST['data']; // The value of the textbox.
if ($id && $data)
{
if ($id=='clients')
{
$query = "SELECT shiptoaddress,company, shiptocity
FROM Clients
WHERE company LIKE '%$data%'
LIMIT 5";
$result = mysql_query($query);
$dataList = array();
while ($row = mysql_fetch_array($result))
{
$toReturn = $row['company'];
$dataList[] = '<li id="' .$row['shiptoaddress'] .$row['shiptocity'] . '">' . htmlentities($toReturn) . '</li>';
}
if (count($dataList)>=1)
{
$dataOutput = join("\r\n", $dataList);
echo $dataOutput;
}
else
{
echo '<li>No Results</li>';
}
}
}
?>
And this is part of the html form code:
<script>
$(document).ready(function() {
$.fn.autosugguest({
className: 'ausu-suggest',
methodType: 'POST',
minChars: 2,
rtnIDs: true,
dataFile: 'data.php'
});
});
</script>
</head>
<body>
<div id="wrapper">
<form action="index.php" method="get">
<div class="ausu-suggest">
<input type="text" size="100" value="" name="clients" id="clients" autocomplete="off" />
<input type="text" size="100" value="" name="shiptoaddress" id="shiptoaddress" autocomplete="off"/>
<input type="text" size="100" value="" name="shiptocity" id="shiptocity" autocomplete="off"/>
</div>
</form>
I solved my problem by using the Jquery autocomplete widget.

no mysql insert if header() is added

I'm trying to get my form to submit and then use header() to redirect.
MYSQL update works fine as long as I DON'T include header('location: setup2.php'); on line 9. When I add it, the redirect works, but the MYSQL doesn't update. Ideas?
<?php
$link;
#mysql_select_db(stevensp_beattrack) or die( "Unable to select database");
$inst=$_POST['inst'];
$id=$_SESSION['user_id'];
if(isset($_POST['submit'])) {
$query = "UPDATE users SET inst='$inst' WHERE id=$id";
mysql_query($query);
header('location: setup2.php'); //adding this line stops the update from working
}
?>
<HTML>
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<select name="inst">
<option value="None">Select a Specialty:</option>
<option value="Voice">Voice</option>
<option value="Guitar">Guitar</option>
</select><br/><br/>
<input type="submit" name="submit" value="Next"/>
</form>
</HTML>

Covert mysql to postgresql query

I have an example that works perfectly in mysql but when I converts to postgresql don't works.
Mysql Code: (index.php):
<?php
require('includes/connection.php');
include('func.php');
?>
<html>
<head>
</head>
<body>
<p>
<form action="" method="post">
<select name="drop_1" id="drop_1">
<option value="" selected="selected" disabled="disabled">Select a Category</option>
<?php getTierOne(); ?>
</select>
</form>
</body>
</html>
Mysql code(func.php):
function getTierOne()
{
$result = mysql_query("SELECT DISTINCT tier_one FROM three_drops")
or die(mysql_error());
while($tier = mysql_fetch_array( $result ))
{
echo '<option value="'.$tier['tier_one'].'">'.$tier['tier_one'].'</option>';
}
}
POstgreSql Code: (index.php):
<?php
require('includes/connection.php');
include('func.php');
?>
<html>
<head>
</head>
<body>
<p>
<form action="" method="post">
<select name="drop_1" id="drop_1">
<option value="" selected="selected" disabled="disabled">Select a Category</option>
<?php getTierOne(); ?>
</select>
</form>
</body>
</html>
PostgreSql code(func.php):
function getTierOne()
{
$sth = $dbh->query("SELECT DISTINCT tier_one FROM three_drops");
while($tier = $sth->fetch())
{
echo '<option value="'.$tier['tier_one'].'">'.$tier['tier_one'].'</option>';
}
}
Connections (Postgresql):
require("constants.php");
$dbh = new PDO('pgsql:host=' . DB_SERVER . ';dbname=' . DB_NAME, DB_USER, DB_PASS,
array (PDO::ATTR_PERSISTENT => true ));
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
The connection is working but I get an error: Call to a member function query() on a non-object.
Try defining the $dbh global.
connection.php:
require("constants.php");
global $dbh;
func.php:
function getTierOne()
{
global $dbh;