PHP Insert doesn't work anymore - php

I've had my code working some time ago. Actually, I've asked for test and it still works in other pcs.
I formated mine, installed eclipse, wamp AND easyphp for double check and all the stuff, and now I have this issue.
It's a simple insert, a HTML with 2 textboxes, the table exists and it works directly by the MySQL workbench.
When I run the script via Browser, I wrote some echoes along the code, and it starts the ajax, calls the insert.php, and inside it it echoes before the require_once config.php
After that, no response at all.
I have put alert status and thown error in the error section in the ajax call, but nothing at all.
What may have happened to it ?
I use Windows, and I suspect of something deeper, but it can be an obvious mistake, I just have no idea where to search, as it works in other computers.
Here goes the code:
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>CRUD</title>
</head>
<body>
<form id="myForm" method="post" action="" >
Nome:
<input type="text" name="nome" required />
<br/>
Tipo:
<input type="text" name="tipo" required />
<br/>
<input type="submit" name="submit" value="save" id="sub"/>
</form>
<script src="script/jquery-2.1.0.js" type="text/javascript"></script>
<script src="script/ajaxInclude.js" type="text/javascript"></script>
</body>
</html>
ajax call
$(document).ready(function(){
$('#myForm').submit(function(){
var data = $(this).serialize();
$.ajax({
url: "DAO/insert.php",
type: "POST",
data: data,
dataType: "html",
success: function( data )
{
alert( data );
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
return false;
});
});
config.php
<?php
echo "DENTRO DO CONFIG";
define('HOST', 'localhost');
define('DB_NAME', 'wms');
define('PORT', '3306');
define('USER', 'root');
define('PASS', '');
$dsn = 'mysql:host='.HOST.'; port='.PORT.'; dbname='.DB_NAME;
try {
$bd = new PDO($dsn, USER, PASS);
// $bd->setAttribute(PDO::ATT_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Houve algum erro no Banco de Dados';
}
?>
insert.php
<?php
echo "FORA DO INSERT";
require_once('config.php');
if(isset($_POST['submit'])){
echo "DENTRO DO INSERT, SUBMIT POSTED";
$nome = $_POST['nome'];
$tipo = $_POST['tipo'];
$sql = 'INSERT INTO produto(id, nome, tipo, criado_em) ';
$sql .= ' VALUES (NULL, :nome, :tipo, NOW())';
try {
echo "DENTRO DO TRY";
$query = $bd->prepare($sql);
$query->bindValue(':nome', $nome, PDO::PARAM_STR);
$query->bindValue(':tipo', $tipo, PDO::PARAM_STR);
if($query->execute()){
echo "Dados inseridos com sucesso";
}else{
echo "Falha na insercao de dados";
}
} catch (Exception $e) {
echo $e->getMessage();
}
die();
}
?>

On insert.php, change:
if(isset($_POST['submit'])){
for
if(isset($_POST['nome']) && isset($_POST['tipo'])){

Related

Trouble with posting data to database using jquery ajax

I have looked up tutorials multiple times and am having trouble figuring out where my code is wrong. I am able to run my php file and get my information sent into my database, so I know my connection isn't the issue, so I am thinking its my index.html file. It may have something to do with how i tried to implement jquery, but I don't know about that either
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="login.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#login').click(function(event){
event.preventDefault();
var username =$('#use').val();
var pass = $('#pass').val();
$.ajax({
url: 'login.php',
method:'POST',
data:
{
User: username,
Pass: pass
},
success:function(result){
alert(result);
}
});
});
});</script>
</head>
<body>
<div class="login-page">
<div class="form">
<form class="register-form">
<input type="text" placeholder="name"/>
<input type="password" placeholder="password"/>
<input type="text" placeholder="email address"/>
<button>create</button>
<p class="message">Already registered? Sign In</p>
</form>
<form class="login-form">
<input type="text" id="use" placeholder="username"/>
<input type="password" id="pass" placeholder="password"/>
<button type="submit" id="login">login</button>
<p class="message">Not registered? Create an account</p>
</form>
</div>
</div>
</body>
</html>
PHP code connecting to my DB
<?php
$dbname = 'project test';
$dbuser = 'root';
$dbpass = '';
$dbhost = 'localhost';
$username=$_POST['use'];
$password=$_POST['pass'];
$conn= mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO user (User, Pass)
VALUES ('{$username}','{$password}')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close(); ;
?>
In your index.html file, you are sending User and Password values However, when you are trying to get them in your php file, you are trying to get use and pass values. Their names don't match. The names need to match in order to get the values correctly.

Why header('location: ') is not working in php using ajax but session is working? [duplicate]

This question already has an answer here:
Redirect after POST using the Location header with jQuery
(1 answer)
Closed 2 years ago.
I am using ajax to post in the login part and create session. the session is working but in there header('location: chat.php') is not working(not redirected). while I am trying to log in session is created but not redirected to chat.php. I checked jQuery and ajax is working and successful to create a session and log in but not redirected to chat.php. Can any help me plz
jQuery('.userlogin').submit(function(){
var email = jQuery("input[name='email_address']").val();
var password = jQuery("input[name='password']").val();
$.ajax({
'url' : 'login.php',
'type' : 'POST',
'data' : {
'loginajax' : '',
'email' : email,
'password' : password
},
'success' : function(output){
jQuery('.ama-input').val('');
}
});
});
<?php
session_start();
require_once('functions.php');
if(isset($_POST['loginajax'])){
$email=$_POST['email'];
$password=$_POST['password'];
$query = mysqli_query($connection, "SELECT * FROM users WHERE email='$email'");
$info = mysqli_fetch_assoc($query);
$pass= $info['password'];
if($pass==md5($password)){
$_SESSION['login'] = "successful";
header('location: chat.php');
}
die();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Log In</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="box">
<h2 class="heading">Log In</h2>
<form action="" method="POST" class="userlogin">
<input class="ama-input" type="email" name="email_address" placeholder="Email Address" />
<input class="ama-input" type="password" name="password" placeholder="Password" />
<input type="submit" name="login" value="Log In" />
</form>
<a class="registration" href="register.php">Create an account</a><br />
</div>
<script src="js/jquery-3.5.1.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>
PHP redirection won’t work because you are making a ajax call.
Try returning the result and redirect from your script like this.
$(function () {
jQuery('.userlogin').submit(function(e){
e.preventDefault();
var email = jQuery("input[name='email_address']").val();
var password = jQuery("input[name='password']").val();
$.ajax({
'url': 'login.php',
'type': 'POST',
'data': {
'loginajax': '',
'email': email,
'password': password
},
'success': function (output) {
console.log(output);
if (output.status == 'success') {
window.location.href = "your url here";//<- your url here
}
}
});
});
});
Your PHP code should look something like this:
<?php
session_start();
require_once 'functions.php';
if (filter_input(INPUT_POST, 'loginajax')) {
$result['status'] = 'unsuccessful';
$result['message'] = 'login unsuccessful.';
$email = filter_input(INPUT_POST, 'email_address');
$password = filter_input(INPUT_POST, 'password');
$sql = "SELECT id,email,password FROM users WHERE email=?";
$stmt = mysqli_prepare($connection, $sql);
mysqli_stmt_bind_param($stmt, "s", $email);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
if (mysqli_stmt_fetch($stmt)) {
if (password_verify($password, $hashed_password)) {
$_SESSION['login'] = "successful";
$result['status'] = "success";
$result['message'] = "login successful.";
}
}
mysqli_stmt_close($stmt);
header('Content-Type: application/json'); // <-- header declaration
echo json_encode($result, true);
}

How do i include ajax in PHP coding to display data in the same page

I want to display data retrieved from the table in the same page. I know if i use ajax, work becomes easier. But how do i do it? I don't know anything about ajax. My current program is combined with html and php. The program is below. All i want is, when i click the button, the requested action and the data must be displayed in the same page.
<!DOCTYPE html>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'DB';
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_error())
{
die("couldn't connect" . $conn->connect_error());
}
$id = $_POST['Id'];
$name = $_POST['Name'];
$blood = $_POST['BloodGroup'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST['insert'])){
$insert = "Insert into ins(Id, name, BloodGroup) values ('$id','$name', '$blood')" ;
if($conn->query($insert) === TRUE) {
echo ("Input data entered successfully");
} else {
echo ("Input data failed to be entered" . $conn->error());
}
$conn->close();
} elseif(isset($_POST['update'])) {
$update = "update ins set Name='".$name."', BloodGroup='".$blood."' where Id='".$id."'";
mysql_query($update);
if($conn->query($update) === TRUE) {
echo ("Data updated successfully");
} else {
echo ("Data cant be updated" . $conn->error());
}
$conn->close();
} elseif(isset($_POST['delete'])) {
$id = $_POST['Id'];
$delete = "delete from ins where Id='".$id."'";
if($conn->query($delete) === TRUE) {
echo ("Data deleted successfully");
} else {
echo ("Data cant be updated" . $conn->error());
}
$conn->close();
}
else {
$id = $_POST['Id'];
$retrieve = "SELECT * FROM ins WHERE Id = ".$id;
if ($result=mysqli_query($conn,$retrieve))
{
while ($row=mysqli_fetch_row($result))
{
echo '<table>
<tr>
<td>Id</td>
<td>Name</td>
<td>Blood Group</td>
</tr>
<tr>
<td>'.$row[0].'</td>
<td>'.$row[1].'</td>
<td>'.$row[2].'</td>
</tr>
</table>';
//$row[0],$row[1],$row[2]';
}
mysqli_free_result($result);
}}}
$conn->close();
?>
<h2>SELECT THE OPERATION YOU WANT TO PERFORM<h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Id: <input type="text" name="Id" />
Name: <Input type="text" name="Name" />
BloodGroup: <input type="text" name="BloodGroup" /><br /><br />
<input type="submit" name="insert" value="Insert" />
<input type="submit" name="update" value="Update" />
<input type="submit" name="delete" value="Delete" />
<input type="submit" name="retrieve" value="retrieve" />
</form>
</body>
</html>
$.ajax({
method: "POST",
url: "{php file url}",
data: { name: "John", location: "Boston" } // data list need to sent
})
.done(function( msg ) {
$("#div1").html(result); //#div1 is container element where you want to show output of ajax
});
For more details refer
http://api.jquery.com/jquery.ajax/
Just start learning jquery and jquery ajax
http://api.jquery.com/jquery.ajax/
you will find something like this:
$.ajax({
type: "POST",
url: '', //write your php file url from where you want to get data
data:{}, //to post data like data:{customerName:'xyz'},
success: function(res){ //data returned from your php file
console.log(res); //use data as per your need
}
});

Ajax not inserting data into database

I am trying to insert data into a database with ajax. The problem is that everything works excepting the insertion of data in the database.
When I click the submit button I get the proper message "You have been subscribed" just that it doesn't insert the data in the database. And don't understand exactly why.
I have dbconn.php
<?php
$db = new mysqli($dbhostname, $dbuser, $dbpass, $dbname);
if ($db->connect_errno) {
echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}
?>
common-functions.php
<?php
require_once('dbconn.php');
function subscribe() {
global $db;
if(isset($_POST['semail'], $_POST['sname'])) {
$name = $_POST['sname'];
$email = $_POST['semail'];
$db->query("INSERT INTO subscribers (`name`, `email`, 'confirmed') VALUES ('".$db->escape_string($name)."', '".$db->escape_string($email)."', 0)");
echo "You have been subscribed";
}
}
subscribe();
?>
subscribe.php
HTML
<form name="subscribe" class="subscribe">
<label class="lablabel">Name:</label><input type="text" class="subscribe-field" id="sname" name="sname"></br>
<label class="lablabel">Email:</label><input type="text" class="subscribe-field" id="semail" name="semail">
<input type="submit" id="ssub" value="Subscribe">
</form>
AJAX
<script type="text/javascript">
$(document).on('submit','.subscribe',function(e) {
e.preventDefault(); // add here
e.stopPropagation(); // add here
$.ajax({ url: 'lib/common-functions.php',
data: {action: 'subscribe',
sname: $("#sname").val(),
semail: $("#semail").val()},
type: 'post',
success: function(output) {
alert(output);
}
});
});
</script>
Remove the quotes and substitute with backticks here
$db->query("INSERT INTO subscribers (`name`, `email`, 'confirmed')
^ ^

Attempting to write a livesearch script

I am attempting a bit of ajax for the first time. I'm trying to write a live search where on every character entered a search of a MySQL database is run.
This is my code so far:
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<script type="text/javascript">
function getStates(value){
$.post(
"getstates.php",
{partialState:value},
function(data){
$("#results").html(data);
});
}
</script>
</head>
<body>
<input type="text" name="input" onkeyup="getStates(this.value)" /><br />
<div id="results"></div>
</body>
</html>
getStates.php
//test the connection
try{
//connect to the database
$dbh = new PDO("mysql:host=127.0.0.1;dbname=livesearch","root", "usbw");
//if there is an error catch it here
} catch( PDOException $e ) {
//display the error
echo $e->getMessage();
}
$partialState = $_POST['partialState'];
$query = $dbh->prepare("SELECT state_name FROM tbl_state WHERE state_name LIKE '%$partialSate%'");
$query->execute();
$result = $query->fetchAll();
foreach($result AS $state){
echo '<div>'.$state['state_name'].'</div>';
}
The mySQL database is constructed correctly using the correct table names etc.
Why is it not returning the resulting states from the database?
The problem is that you have made a typo in your query:
$query = $dbh->prepare("SELECT state_name
FROM tbl_state
WHERE state_name
LIKE '%$partialSate%'");
^^^^Missing t
Should be
$query = $dbh->prepare("SELECT state_name
FROM tbl_state
WHERE state_name
LIKE '%$partialState%'");
But you should also use prepared query's correctly:
Fixed code:
<?php
if(isset($_POST['partialState'])){
//test the connection
try{
//connect to the database
$dbh = new PDO("mysql:host=127.0.0.1;dbname=livesearch","root", "usbw");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
//if there is an error catch it here
} catch( PDOException $e ) {
//display the error
echo $e->getMessage();
}
$query = $dbh->prepare("SELECT state_name
FROM tbl_state
WHERE state_name
LIKE :like");
$query->execute(array(':like'=>'%'.$_POST['partialState'].'%'));
$result = $query->fetchAll();
foreach($result AS $state){
echo '<div>'.$state['state_name'].'</div>';
}
die();
}
?>
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
function getStates(value){
$.post("index.php", { "partialState":value },
function(data){
$("#results").html(data);
});
}
</script>
</head>
<body>
<input type="text" name="input" onkeyup="getStates(this.value)" /><br />
<div id="results"></div>
</body>
</html>

Categories