Fill html input from sql query using button in PHP - javascript

I have 2 inputs with name and surname, from a database I bring all the values ​​and when pressing a button on the form I would like the inputs to be completed with the data. When there is no data left to show, it should throw a warning. I leave the code of what I have done so far.
<?php
function customersData(){
try {
$pdo = conect();
$sql = "Select CTE_LASTNAME,CTE_NAME
From customers
Where id_store= 1150";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$usuarios = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $customers;
} catch(PDOException $e) {
echo 'Error: '.$e->getMessage();
}
}
$data=customersData();
?>
<html>
<body>
<form>
<div class="form-group">
<div class="col-xs-3">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="ficha">
</div>
<div class="mb-3">
<label for="lastname" class="form-label">Lastname</label>
<input type="text" class="form-control" id="ficha">
</div>
</div>
<button type="submit" class="btn btn-primary" id="btnData">Show Data</button>
</form>
<script>
var btnData = document.getElementById("btnData");
btnData.addEventListener("click",function(e){
e.preventDefault();
});
</script>
</body>
</html>

You probably want to use Ajax, I added JQuery to simplify it.
Try it, and manage your id_store variable.
<?php
function customersData($id) {
try {
$pdo = conect();
$sql = "Select CTE_LASTNAME,CTE_NAME
From customers
Where id_store=?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$id]);
return $stmt->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo 'Error: '.$e->getMessage();
}
}
if (!empty($_GET["get_data"])) {
$data = customersData(intval($_GET["get_data"]));
echo json_encode($data);
exit();
}
?>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous"></script>
</head>
<body>
<form>
<div class="form-group">
<div class="col-xs-3">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="name">
</div>
<div class="mb-3">
<label for="lastname" class="form-label">Lastname</label>
<input type="text" class="form-control" id="lastname">
</div>
</div>
<button type="button" class="btn btn-primary" id="btnData">Show Data</button>
</form>
<script>
$("#btnData").click(function (ev) {
$.get(window.location.href, {
"get_data": 1150
}, function (result) {
let obj = JSON.parse(result);
$("#name").val(obj.CTE_NAME);
$("#lastname").val(obj.CTE_LASTNAME);
});
});
</script>
</body>
</html>

Related

Send Email and Insert from the same form

I have a page where I have this form that sends the data in an email.
I want that when I click the submit button, other than sending the data through email, I want to send the data in a page where I have an INSERT script.
Here's the code of my page:
<!doctype html>
<html lang="en">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<?php
require_once __DIR__.'/vendor/autoload.php';
require_once __DIR__.'/config.php';
session_start();
if (!empty($_SESSION['_contact_form_error'])) {
$error = $_SESSION['_contact_form_error'];
unset($_SESSION['_contact_form_error']);
}
if (!empty($_SESSION['_contact_form_success'])) {
$success = true;
unset($_SESSION['_contact_form_success']);
}
?>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>Appointmenta</title>
<!-- reCAPTCHA Javascript -->
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-8 offset-md-2">
<div class="card mt-5">
<div class="card-body">
<h1 class="card-title">
Add an Appointment
</h1>
<?php
if (!empty($success)) {
?>
<div class="alert alert-success">Message sent successfully.</div>
<?php
}
?>
<?php
if (!empty($error)) {
?>
<div class="alert alert-danger"><?= $error ?></div>
<?php
}
?>
<?php $Field1= $_POST['Field1']; ?>
<?php $Field2= $_POST['Field2']; ?>
<?php $Field3= $_POST['Field3']; ?>
<?php $Field4= $_POST['Field4']; ?>
<?php $Field5= $_POST['Field5']; ?>
<?php $Field6= $_POST['Field6']; ?>
<?php $Field7= $_POST['Field7']; ?>
<?php $Field8= $_POST['Field8']; ?>
<?php $Field9= $_POST['Field9']; ?>
<form id="target" method="post">
<div class="form-group">
<label for="name">Field 1</label>
<input type="text" name="Field1" id="Field1" class="form-control"
value="<?php echo $Field1?>">
</div>
<div class="form-group">
<label for="subject">Field 2</label>
<input type="text" name="Field2" id="Field2" class="form-control"
value="<?php echo $Field2?>">
</div>
<div class="form-group">
<label for="email">Field 3</label>
<input type="text" name="Field3" id="Field3" class="form-control"
value="<?php echo $Field3?>">
</div>
<div class="form-group">
<label for="subject">Field 4</label>
<input type="text" name="Field4" id="Field4" class="form-control"
value="<?php echo $Field4?>">
</div>
<div class="form-group">
<label for="subject">Field 5</label>
<input type="text" name="Field5" id="Field5" class="form-control"
value="<?php echo $Field5?>">
</div>
<div class="form-group">
<label for="subject">Field 6</label>
<input type="text" name="Field6" id="Field6" class="form-control"
value="<?php echo $Field6?>">
</div>
<div class="form-group">
<label for="subject">Field 7</label>
<input type="text" name="Field7" id="Field7" class="form-control"
value="<?php echo $Field7?>">
</div>
<div class="form-group">
<label for="subject">Field 8</label>
<input type="text" name="Field8" id="Field8" class="form-control"
value="<?php echo $Field8?>">
</div>
<div class="form-group">
<label for="message">Field 9</label>
<input type="text" name="Field9" id="Field9" class="form-control"
value="<?php echo $Field9?>">
</div>
<div class="form-group text-center">
<div align="center" class="g-recaptcha" data-sitekey="<?= CONTACTFORM_RECAPTCHA_SITE_KEY ?>"></div>
</div>
<button "name="submit" class="btn btn-primary btn-block"> Send Email</button>
</form>
<form action="../list.php">
<p><br></p>
<button class="btn btn-primary btn-block">Return home.</button>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<script language="Javascript">
<!--
$('form').submit(function(event) {
event.preventDefault();
$.ajax({
method: 'POST',
url: 'submit.php',
data: $( this ).serialize()
});
});
-->
</script>
When I click on 'Send Email' nothing happens.
**I want to click 'Send Email' and see the message 'Message sent successfully'. At the same time I want that same data to be sent to appointment.php, which inserts the data into a table. I'd prefer that 'appointment.php' doesn't even open, I want to stay on index.php when I click 'Send Email'**
Code of submit.php
<?php
require_once __DIR__.'/vendor/autoload.php';
require_once __DIR__.'/functions.php';
require_once __DIR__.'/config.php';
session_start();
// Basic check to make sure the form was submitted.
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
echo "The form must be submitted with POST data.";
exit();
}
require "appointment.php";
// Do some validation, check to make sure the name, email and message are valid.
if (empty($_POST['g-recaptcha-response'])) {
echo "Please complete the CAPTCHA.";
}
$recaptcha = new \ReCaptcha\ReCaptcha(CONTACTFORM_RECAPTCHA_SECRET_KEY);
$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_REQUEST['REMOTE_ADDR']);
if (!$resp->isSuccess()) {
$errors = $resp->getErrorCodes();
$error = $errors[0];
$recaptchaErrorMapping = [
'missing-input-secret' => 'No reCAPTCHA secret key was submitted.',
'invalid-input-secret' => 'The submitted reCAPTCHA secret key was invalid.',
'missing-input-response' => 'No reCAPTCHA response was submitted.',
'invalid-input-response' => 'The submitted reCAPTCHA response was invalid.',
'bad-request' => 'An unknown error occurred while trying to validate your response.',
'timeout-or-duplicate' => 'The request is no longer valid. Please try again.',
];
$errorMessage = $recaptchaErrorMapping[$error];
echo "Please retry the CAPTCHA: ".$errorMessage;
}
// Everything seems OK, time to send the email.
$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = CONTACTFORM_PHPMAILER_DEBUG_LEVEL;
$mail->isSMTP();
$mail->Host = CONTACTFORM_SMTP_HOSTNAME;
$mail->SMTPAuth = true;
$mail->Username = CONTACTFORM_SMTP_USERNAME;
$mail->Password = CONTACTFORM_SMTP_PASSWORD;
$mail->SMTPSecure = CONTACTFORM_SMTP_ENCRYPTION;
$mail->Port = CONTACTFORM_SMTP_PORT;
// Recipients
$mail->setFrom(CONTACTFORM_FROM_ADDRESS, CONTACTFORM_FROM_NAME);
//$mail->addAddress(CONTACTFORM_TO_ADDRESS, CONTACTFORM_TO_NAME);
//$mail->addAddress(CONTACTFORM2_TO_ADDRESS, CONTACTFORM2_TO_NAME);
$mail->addAddress(CONTACTFORM3_TO_ADDRESS, CONTACTFORM3_TO_NAME);
//$mail->addAddress(CONTACTFORM4_TO_ADDRESS, CONTACTFORM4_TO_NAME);
//$mail->addReplyTo("marketing#lgp-italia.it");
// Content
$mail->Subject = "Appointment at ".$_POST['Field1'];
$mail->Body = <<<EOT
Appointment at: {$_POST['Field1']}, {$_POST['Field2']}
{$_POST['Field3']}
{$_POST['Field4']}
{$_POST['Field5']}
{$_POST['Field6']}
{$_POST['Field7']}
EOT;
$mail->send();
} catch (Exception $e) {
echo "An error occurred while trying to send your message: ". $mail->ErrorInfo;
}
Code of appointment.php
<?php
if (isset($_POST['submit'])) {
require "../../../security/config.php";
require "../../../security/common.php";
try {
$connection = new PDO($dsn, $username, $password, $options);
$new_call = array(
"Field1" => $_POST['Field1'],
[...]
);
echo var_dump("1");
$sql = sprintf(
"INSERT INTO %s (%s) values (%s)",
"db.appointments",
implode(", ", array_keys($new_call)),
":" . implode(", :", array_keys($new_call))
);
echo var_dump("2");
$statement = $connection->prepare($sql);
$statement->execute($new_call);
echo var_dump("3");
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
echo var_dump("4");
}
echo var_dump("5");
?>

Trying to submit a form to MySql with AJAX

I am trying to post from a form to SQL by using Ajax.
However, when clicking the button to submit the form, no error is shown in the chrome console and it looks like the PHP is also not being called in the network tab. Could anyone please help me out or point me in the right direction?
HTML
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="js/signup.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body background-color="#000000">
<section class="section section-full bg-secondary overflow-hidden z-2">
<div class="container z-2">
<div class="row justify-content-center pt-6 pt-md-5 pb-0 mb-2">
<div class="col-12 col-xl-7">
<div class="card card-tertiary">
<div class="card-header text-center">
<span>Register</span>
</div>
<div class="card-body">
<p class="font-weight-bold">
</p>
<p class="card-text text-center">
Please enter your Email:
</p>
<form class="d-flex justify-content-between mb-2" method="POST" name="email-form" id="email-form">
<div id="name-group" class="form-group">
<p>Name: <input type="text" id="uname" name="uname" class="form-control w-75" required/>
</div>
<div id="email-group" class="form-group">
<p>Email: <input type="text" id="uemail" name="uemail" class="form-control w-75" required/>
</div>
<div class="form-group">
<button class="btn btn-sm mr-2 btn-tertiary border-dark" type="button" action="submit" id ="submit" name="submit">
<span class="btn-text">Sign-Up</span>
</button>
</div>
<div id="message"></div>
</form>
</div>
</div>
</div>
</div>
</div>
</section>
</body>
signup.js Javascript
$(document).ready(function() {
$('#email-form').submit(function(e) {
e.preventDefault();
$.ajax({
method: "POST",
url: 'emailsend.php',
data: {
'uname': $('#uname').val(),
'uemail': $('#uemail').val()
}
}).done(function( data ) {
var result = $.parseJSON(data);
var str = '';
if(result == 1) {
str = 'User record saved successfully.';
} else if( result == 2) {
str == 'All fields are required.';
} else{
str = 'User data could not be saved. Please try again';
}
$("#message").css('color', 'red').html(str);
})
})
});
emailsend.php PHP
<?php
$dbhost = "localhost";
$dbuser = "------";
$dbpass = "------";
$db = "signup";
$data = '';
$result = 0;
$conn = new mysqli($dbhost, $dbuser, $dbpass, $db) or die("Connect failed: %s\n". $conn -> error);
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
$uname = $_POST['uname'];
$email = $_POST['uemail'];
/* validation */
if(!$uname || !$email){
$result = 2;
}elseif (!strpos($email, "#") || !strpos($email, ".")) {
$result = 3;
}else {
//SQL query to get results from database
$sql = "INSERT INTO emails (name, email) VALUES ('$uname', '$email')";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ss', $uname, $email);
if($stmt->execute()){
$result = 1;
}
}
echo $result;
$conn->close()
?>
since you have
$(document).ready(function() {
$('#email-form').submit(function(e) {
and
<button class="btn btn-sm mr-2 btn-tertiary border-dark" type="button" action="submit" id ="submit" name="submit">
i dont see how will be submited when button type is not submit
change the button type to submit like this
<button class="btn btn-sm mr-2 btn-tertiary border-dark" type="submit" action="submit" id ="submit" name="submit">
First, change your button type attribute to submit instead of button:
<button class="btn btn-sm mr-2 btn-tertiary border-dark" type="submit" action="submit" id ="submit" name="submit">
Second, change your JQuery version as
Bootstrap's JavaScript version 3.3 requires jQuery version
1.9.1 or higher, but lower than version 3

Same Value in the Dynamic jQuery Form

Hello to all users of the site, my intent was to create a dynamic form for a multiple association of multiple products to the same customer, and I had the idea to implement it with the help of jquery being able to create a dynamic form, so looking on the internet I came across an example on jsFiddle, which works perfectly. The only thing that I need would be not to have an empty input where you can write but an input that has a fixed value. For example, the word "TEST", and every time a new input is generated, the input generated always has the value = "TEST".
How can I do it?
Code (you can copy and paste in your test.html it works!):
<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
</head>
<form role="form" action="/wohoo" method="POST">
<label>impianti</label>
<div class="CLASSE_DA_SPECIFICARE-VARIABILE_DA_INZIALIZZARE">
<div class="CLASSE_DEL_DIV">
<div class="CLASSE_DA_SPECIFICARE">
<input type="text" name="impianti[]">
<input type="text" name="impianti[]">
<button type="button" class="RIMUOVI_INPUT">Remove</button>
</div>
</div>
<button type="button" class="add-field">Add field</button>
</div>
</form>
<script type="text/javascript">
$('.CLASSE_DA_SPECIFICARE-VARIABILE_DA_INZIALIZZARE').each(function () {
var $VARIABILE_DA_INZIALIZZARE = $('.CLASSE_DEL_DIV', this);
$(".add-field", $(this)).click(function (e) {
$('.CLASSE_DA_SPECIFICARE:first-child', $VARIABILE_DA_INZIALIZZARE).clone(true).appendTo($VARIABILE_DA_INZIALIZZARE).find('input').val('').focus();
});
$('.CLASSE_DA_SPECIFICARE .RIMUOVI_INPUT', $VARIABILE_DA_INZIALIZZARE).click(function () {
if ($('.CLASSE_DA_SPECIFICARE', $VARIABILE_DA_INZIALIZZARE).length > 1)
$(this).parent('.CLASSE_DA_SPECIFICARE').remove();
});
});
</script>
How to put into.val() <?php echo $row['impianto_id'] ;?>
I have this:
<?php
session_start();
include 'connessione.php';
$id = $_SESSION['id'];
$query_string = "SELECT * FROM impianti";
$impianti = mysqli_query($connessione, $query_string);
?>
<h4>IMPIANTO ID CAMPAGNA</h4>
<select name="impianto_id_campagna">
<?php
while ($row = mysqli_fetch_assoc($impianti)) { ?>
<option value="<?php echo $row['impianto_id']; ?>">
<?php echo $row['concessionaria']; ?>
</option>
<?php } ?>
</select>
I want to echo this in .val()
But it does not work...
<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
</head>
<form role="form" action="/wohoo" method="POST">
<label>impianti</label>
<div class="CLASSE_DA_SPECIFICARE-VARIABILE_DA_INZIALIZZARE">
<div class="CLASSE_DEL_DIV">
<div class="CLASSE_DA_SPECIFICARE">
<input type="text" name="impianti[]">
<input type="text" name="impianti[]">
<button type="button" class="RIMUOVI_INPUT">Remove</button>
</div>
</div>
<button type="button" class="add-field">Add field</button>
</div>
</form>
<script type="text/javascript">
var impianto_id = '<?php $row[' impianto_id ']; ?> ';
console.log (impianto_id);
</script>
<script type="text/javascript">
$('.CLASSE_DA_SPECIFICARE-VARIABILE_DA_INZIALIZZARE').each(function () {var $VARIABILE_DA_INZIALIZZARE = $('.CLASSE_DEL_DIV', this);
$(".add-field", $(this)).click(function (e) {
$('.CLASSE_DA_SPECIFICARE:first-child', $VARIABILE_DA_INZIALIZZARE).clone(true).appendTo($VARIABILE_DA_INZIALIZZARE).find('input').val(impianto_id).focus();
});
$('.CLASSE_DA_SPECIFICARE .RIMUOVI_INPUT', $VARIABILE_DA_INZIALIZZARE).click(function () {
if ($('.CLASSE_DA_SPECIFICARE', $VARIABILE_DA_INZIALIZZARE).length > 1)
$(this).parent('.CLASSE_DA_SPECIFICARE').remove();
});
});
</script>
$('.CLASSE_DA_SPECIFICARE-VARIABILE_DA_INZIALIZZARE').each(function() {
var $VARIABILE_DA_INZIALIZZARE = $('.CLASSE_DEL_DIV', this);
$(".add-field", $(this)).click(function(e) {
$('.CLASSE_DA_SPECIFICARE:first-child', $VARIABILE_DA_INZIALIZZARE).clone(true).appendTo($VARIABILE_DA_INZIALIZZARE).find('input').val('TEST').focus();});// here the test
$('.CLASSE_DA_SPECIFICARE .RIMUOVI_INPUT', $VARIABILE_DA_INZIALIZZARE).click(function() {
if ($('.CLASSE_DA_SPECIFICARE', $VARIABILE_DA_INZIALIZZARE).length > 1)
$(this).parent('.CLASSE_DA_SPECIFICARE').remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form role="form" action="/wohoo" method="POST">
<label>impianti</label>
<div class="CLASSE_DA_SPECIFICARE-VARIABILE_DA_INZIALIZZARE">
<div class="CLASSE_DEL_DIV">
<div class="CLASSE_DA_SPECIFICARE">
<input type="text" name="impianti[]">
<input type="text" name="impianti[]">
<button type="button" class="RIMUOVI_INPUT">Remove</button>
</div>
</div>
<button type="button" class="add-field">Add field</button>
</div>
</form>
All you had to do is just add 'test' into the .val() of the input that you created.

Same structure, but Ajax success response acts differently from previous version

Have been working on a form with Ajax and used to work on a version with no extras (css and so on) before. It worked all fine, data has been inserted successfully into the database and I have been able to show and hide two divs.
Now I used to apply it to the form I've been working on. It acts different from the previous version, so it's exactly the same (sure, changed some names, added some inputs), like no "success message" from the PHP-file, suddenly all data visible in the URL, the current form doesn't hide and shows the next one.
I can't understand the sudden change in behavior, took a look for mistakes, compared the codes, but have no idea. It seems to be such a small mistake that I don't spot it or something is wrong with the whole construction.
The current file is:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<?
require 'config.php';
session_start();
// Check if user is logged in using the session variable
if ( $_SESSION['logged_in'] != 1 ) {
$_SESSION['message'] = "You must log in before viewing your profile page!";
header("location: error.php");
}
else {
// Makes it easier to read
$id = $_SESSION['id'];
$name = $_SESSION['name'];
$email = $_SESSION['email'];
$active = $_SESSION['active'];
$hash = $_SESSION['hash'];
}
?>
<script type="text/javascript">
function getState(val) {
$.ajax({
type: "POST",
url: "demo_ajax.php",
data:'country_id='+val,
success: function(data){
$("#region").html(data);
}
});
}
$(document).ready(function(){
$("#submit").click(function(){
var size=$("#size").val();
var industry=$("#industry").val();
var country=$("#country").val();
var region=$("#region").val();
var url=$("#website").val();
var fb=$("#fb").val();
var lkdn=$("#lkdn").val();
$.ajax({
type:"post",
url:"process2.php",
data:"size="+size+"&industry="+industry+"&country="+country+"&region="+region+"&url="+url+"&fb="+fb+"&lkdn="+lkdn,
success:function(data){
$("#theform").hide();
$("#info").html(data);
//$("#partone").css();
$("#partone").show();
alert("Hello");
}
});
});
});
</script>
<?php include 'js/js.html'; ?>
<?php include 'css/css.html'; ?>
</head>
<body class="w3-blue r_login_corp_body">
<div id="info" style="color:white"></div>
<div class="r_login_corp_body"></div>
<div class="w3-content w3-white r_siu r_centered_div">
<header class="w3-camo-black w3-container">
<div class="w3-container ">
<span class="w3-xlarge r_caption">eRecruiter</span> <span class="large">Corporate Login</span>
</div>
<div class="w3-black">
<a href="javascript:void(0)" onclick="selectForm('register');">
<div class="w3-half tablink w3-hover-text-yellow w3-padding w3-center w3-padding-16">Register</div>
</a>
</div>
</header>
<!-- Register -->
<div id="register" role="form" class="r_form_elements">
<form name="formone" class="form" autocomplete="off">
<div id="profed" class="w3-container w3-padding-16">
<div class="alert alert-error"></div>
<label>Company Industry</label>
<input class="w3-input" name="industry" id="industry" type="text" placeholder="Your Industry" >
<label>Company Size</label>
<input class="w3-input" name="size" id="size" type="integer" placeholder="Your Company Size" >
<label >Country:</label>
<select name="country" id="country" class="demoInputBox" onChange="getState(this.value);" >
<option value="">Select Country</option>
<?php
$sql1="SELECT * FROM pentagonal_country";
$results=$mysqli->query($sql1);
while($rs=$results->fetch_assoc()) {
?>
<option value="<?php echo $rs["country_code"]; ?>"><?php echo $rs["country_name"]; ?></option>
<?php
}
?>
</select>
<label>State:</label>
<select id="region" name="region" onKeyup="checkform()">
<option value="">Select State</option>
</select>
<label>Website</label>
<input class="w3-input" name="website" id="website" type="url" placeholder="Your Website-Address" >
<label>Facebook</label>
<input class="w3-input" name="fb" id="fb" type="url" placeholder="https://facebook.com/" >
<label>Linkedin</label>
<input class="w3-input" name="lkdn" id="lkdn" type="url" placeholder="https://linkedin.com/in/">
</div>
<div class="w3-row">
<button type="submit" id="submit" class="w3-button w3-black w3-half w3-hover-yellow" >Add</button>
<button class="w3-button w3-black w3-half w3-hover-pale-yellow">Forgot Password</button>
</div>
</form>
</div>
<!-- Register -->
<div id="partone" style="display:none">
<form>
name : <input type="text" name="name" id="name">
</br>
message : <input type="text" name="message" id="message">
</br>
</br>
name : <input type="text" name="url" id="url">
</br>
message : <input type="text" name="fb" id="fb">
</br>
name : <input type="text" name="lkdn" id="lkdn">
</br>
</br> </br>
Send;
</form>
</div>
</div>
</body>
</html>
and the PHP-file to insert data is:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "remotejobs";
session_start();
// Check if user is logged in using the session variable
if ( $_SESSION['logged_in'] != 1 ) {
$_SESSION['message'] = "You must log in before viewing your profile page!";
header("location: error.php");
}
else {
// Makes it easier to read
$id = $_SESSION['id'];
$name = $_SESSION['name'];
$email = $_SESSION['email'];
$active = $_SESSION['active'];
$hash = $_SESSION['hash'];
}
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$industry=$_POST["industry"];
$size=$_POST["size"];
$country=$_POST["country"];
$region=$_POST["region"];
$website=$_POST["url"];
$fb=$_POST["fb"];
$lkdn=$_POST["lkdn"];
$usrid=$id;
$sql = "INSERT INTO corp_user_profile (id, industry, size, nation, region, url, facebook, linkedin)
VALUES ('$usrid', '$industry','$size', '$country', '$region', '$website', '$fb', '$lkdn')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
I used to work with the previous file I've worked with just to be sure that everything's right after a week of bug fixing.
Can somebody tell me where the problem is, probably why it is a mistake to avoid future problems like this?
The most obvious bug (aside from the SQL injection stuff mentioned above) is that
<button type="submit" will cause the form to submit normally via postback, unless you prevent it using script. Add event.preventDefault() to the first line of your "click" handler.
$("#submit").click(function(event){
event.preventDefault(); //prevent default postback behaviour
var size=$("#size").val();
//...etc
You're seeing the data in the URL because the form is posting normally (before the ajax has chance to run) and doing a GET because there's no other method specified in the form's markup, and GET is the default..
You may want to prevent the default behavior by passing the event to your click function and calling event.preventDefault().

I am trying to auto update mysql database using ajax and no click button

My database is not updating dynamically. Am I missing something?
It was working before removing some field names and also it was updating the user records automatically. But now it seems some issue in updating dynamically.
Form javascript used for updating
<script type="text/javascript">
// JQUERY: Plugin "autoSumbit"
(function($) {
$.fn.autoSubmit = function(options) {
return $.each(this, function() {
// VARIABLES: Input-specific
var input = $(this);
var column = input.attr('name');
// VARIABLES: Form-specific
var form = input.parents('form');
var method = form.attr('method');
var action = form.attr('action');
// VARIABLES: Where to update in database
var where_val = form.find('#where').val();
var where_col = form.find('#where').attr('name');
// ONBLUR: Dynamic value send through Ajax
input.bind('blur', function(event) {
// Get latest value
var value = input.val();
// AJAX: Send values
$.ajax({
url: action,
type: method,
data: {
val: value,
col: column,
w_col: where_col,
w_val: where_val
},
cache: false,
timeout: 10000,
success: function(data) {
// Alert if update failed
if (data) {
alert(data);
} else { // Load output into a P
$('#notice').text('Updated');
$('#notice').fadeOut().fadeIn();
}
}
});
// Prevent normal submission of form
return false;
})
});
}
})(jQuery);
// JQUERY: Run .autoSubmit() on all INPUT fields within form
$(function(){
$('#ajax-form INPUT').autoSubmit();
});
</script>
<script type="text/javascript" src="materialise/js/jquery-1.8.0.min.js"></script>
<form id="ajax-form" class="autosubmit" method="POST" action="./php_parsers/ajax-update.php">
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-mode-edit prefix"></i>
<input type="text" name="firstname" >
<label for="firstname">Firstname: * <?php echo $firstname; ?></label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-border-color prefix"></i>
<input type="text" name="lastname" value="<?php echo $lastname; ?>">
<label for="lastname">Lastname: *</label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-action-accessibility prefix"></i>
<input type="date" name="age" class="datepicker validate">
<label for="age">D.o.B *</label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-mode-edit prefix"></i>
<label for="gender"><?php echo $sex; ?></label>
</div>
</div>
<input id="where" type="hidden" name="<?php echo $uname; ?>" value="<?php echo $uname; ?>" />
</form>
update php used
<?php
// DATABASE: Connection variables
include_once("../php_includes/check_login_status.php");
// DATABASE: Clean data before use
function clean($value) {
global $db_conx;
$value = preg_replace('#[^a-z0-9. ]#i', '', $value);
$value = mysqli_real_escape_string($db_conx, $value);
return $value;
}
// FORM: Variables were posted
if (count($_POST)) {
// Prepare form variables for database
foreach($_POST as $column => $value)
${$column} = clean($value);
// Perform MySQL UPDATE
$result = "UPDATE users SET ".$col."='".$val."' WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $result);
}
?>
below is the updated code working on my local...hope it will help you
did it without creating jquery plugin
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$('input').blur(function() {
var input = $(this);
var column = input.attr('name');
// VARIABLES: Form-specific
var form = input.parents('form');
var method = form.attr('method');
var action = form.attr('action');
// VARIABLES: Where to update in database
var where_val = form.find('#where').val();
var where_col = form.find('#where').attr('name');
var value = input.val();
// AJAX: Send values
$.ajax({
url: action,
type: method,
data: {
val: value,
col: column,
w_col: where_col,
w_val: where_val
},
cache: false,
timeout: 10000,
success: function(data) {
// Alert if update failed
if (data) {
alert(data);
} else { // Load output into a P
$('#notice').text('Updated');
$('#notice').fadeOut().fadeIn();
}
}
});
});
});
</script>
</head>
<body>
<form id="ajax-form" class="autosubmit" method="POST" action="./php_parsers/ajax-update.php">
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-mode-edit prefix"></i>
<input type="text" name="firstname" value="<?php echo $firstname; ?>">
<label for="firstname">Firstname: * </label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-border-color prefix"></i>
<input type="text" name="lastname" value="<?php echo $lastname; ?>">
<label for="lastname">Lastname: *</label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-action-accessibility prefix"></i>
<input type="date" name="age" class="datepicker validate">
<label for="age">D.o.B *</label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-mode-edit prefix"></i>
<label for="gender"><?php echo $sex; ?></label>
</div>
</div>
<input id="where" type="hidden" name="<?php echo $uname; ?>" value="<?php echo $uname; ?>" />
</form>
</body>
</html>
**Here’s the code example of a POST method call and AJAX database update –**
<div id="c">
<input id="text1" type="text" name="text1" />
<input id="submit" type="submit" name="submit" value="SAVE IT" />
</div>
<div id="cn">
</div>``
**Now we declare the JQuery code to make a POST call**
<script type="text/javascript">
$(document).ready(function () {
$('#submit').click(function(){
var ths = this;
var str = $(ths).siblings("#text1").val();
$.post("saveData.php", {t:str}, function(value){
$(ths).parent("#c").fadeOut("fast");
$(ths).parent("#c").siblings("#cn").html(value);
});
});
});
</script>
**This code block receive value and update database**
$t = $_POST['t'];
$link = mysql_connect(servername, username, password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(databasename, $link);
// Insert the data
$query2="INSERT INTO p_a_j(scrap) VALUES('$t')";
$results2 = mysql_query($query2, $link)
or die(mysql_error());
if(mysql_affected_rows()>=1){
echo '<span>You entered'.$t.'</span>'.
'Database updated'.
'Try this again'; }

Categories

Resources