Dynamic form and send to mysql via jquery and ajax - javascript

I have already asked some questions about this, I was helped, but kind of the way they said it only works if the form is normal, with inputs with name "something here" my form only has an input "text" name "table" to put The table number the rest of the form comes via mysql ajax. My question is how can I pass this form to the database since it is dynamic? My code below.
My form
<div class="well">
<!-- left -->
<div id="theproducts" class="col-sm-5">
</div>
<!-- left -->
<form method="post" action="relatorio.php" id="formRel">
<span>Mesa</span>
<input type="text" id="numero_mesa" name="numero_mesa">
<input type="text" id="theinputsum">
<!-- right -->
<div id="thetotal" class="col-sm-7">
<h1 id="total"></h1>
<button type="submit" class="btn btn-lg btn-success btn-block"><i class="fa fa-shopping-cart" aria-hidden="true"></i> Finalizar Pedido</button>
</form>
</div>
<!-- right -->
</div>
And the javascript code.
<script>
$('#formRel').submit(function(event){
event.preventDefault();
var formDados = new FormData($(this)[0]);
$.ajax({
method: "POST",
url: "relatorio.php",
data: $("#formRel").serialize(),
dataType : "html"
})
};
</script>
The insert query is like this.
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
//Criar a conexao
$link = new mysqli ("localhost", "root", "", "restaurant");
if($link->connect_errno){
echo"Nossas falhas local experiência ..";
exit();
}
//echo "<pre>"; print_r($_POST); exit;
$mesa = $_POST['numero_mesa'];
$pedido = $_POST['products'];
$preco = $_POST['products'];
$sql = "INSERT INTO spedido ('pedido','preco','numero_mesa') VALUES ('$mesa','$pedido','$preco')";
$link->query($sql);
?>
enter image description here

<script>
$(document).on('submit', '#formRel', function(event) {
event.preventDefault();
var numero_mesa = $('#numero_mesa').val();
$.ajax({
type: "POST",
url: "relatorio.php?",
data: "numero_mesa="+ numero_mesa+
"&products="+ products,
success: function (data) {
alert(data) // this will send you a message that might help you see whats going on in your php file
});
})
};
</script>

Related

Return mysql fetch data and insert into form field value

i have a list of clients on a page, each client has an icon to click on to edit the client details.
<i class="fas fa-user-edit gray openModal" data-modal="modal2" client="'.$client['id'].'"></i>
Everything is good up to this point. click the icon the proper modal opens and it triggers the js file just fine. (I did alot of console logs to ensure). The client variable in my jquery file holds fine and i'm able to get it passed to the php file.
in the php file i'm able to pull the information into an array and i was able to just echo the $client['firstName'] and have it show in the console.
when i moved to getting that information and parse it as the Json is when i got lost. Can someone please help me take my result and load into my form fields. The code i have now may be totally off because i've been playing with different code from different searches.
form (shortened to two fields for ease of example)
<form id="form" class="editClient ajax" action="ajax/processForm.php"
method="post">
<input type="hidden" id="refreshUrl" value="?
page=clients&action=view&client=<?php echo $client['id'];?>">
<input type="hidden" name="client" value="<?php echo $client['id'];?>">
<div class="title">
Client Name
</div>
<div class="row">
<!-- first name -->
<div class="inline">
<input type="text" id="firstName" name="firstName" value="<?php echo $client['firstName']; ?>" autocomplete="nope" required>
<br>
<label for="firstName">First Name<span>*</span></label>
</div>
<!-- last name -->
<div class="inline">
<input type="text" id="lastName" name="lastName" value="<?php echo $client['lastName']; ?>" autocomplete="nope" required>
<br>
<label for="lastName">Last Name<span>*</span></label>
</div>
</form>
javascript/jquery file
$('.openModal').on('click', function() {
//$('body, html, div').scrollTop(0);
var that = $(this),
client = that.attr('client');
$.ajax({
type: "post",
url: "ajax/getClient.php",
data: {id:client},
success: function(response){
var result = JSON.parse(response);
var data = result.rows;
$("#firstName").val(data[0]);
}
})
});
php file
<?php
include('../functions.php');
$sql = 'SELECT * FROM clients WHERE id="'.$_POST['id'].'"';
$result = query($sql);
confirmQuery($result);
$data = fetchArray($result);
echo json_encode(['response' => $data, 'response' => true]);
?>
UPDATED ----------
Here is my final js file that allowed my form values to be set.
$('.openModal').on('click', function() {
var that = $(this),
client = that.attr('client');
$.ajax({
type: "post",
url: "ajax/getClient.php",
data: {id:client},
success: function(response){
var result = JSON.parse(response);
$("select#primaryContact").append( $("<option>")
.val(result[0].primaryContact)
.html(result[0].primaryContact)
);
$("select#primaryContact").append( $("<option>")
.val("")
.html("")
);
if (result[0].email !== "") {
$("select#primaryContact").append( $("<option>")
.val(result[0].email)
.html(result[0].email)
);
}
if (result[0].phoneCell !== "") {
$("select#primaryContact").append( $("<option>")
.val(result[0].phoneCell)
.html(result[0].phoneCell)
);
}
if (result[0].phoneHome !== "") {
$("select#primaryContact").append( $("<option>")
.val(result[0].phoneHome)
.html(result[0].phoneHome)
);
}
$("input#firstName").val(result[0].firstName);
$("input#lastName").val(result[0].lastName);
$("input#address").val(result[0].address);
$("input#city").val(result[0].city);
$("input#zip").val(result[0].zip);
$("input#email").val(result[0].email);
$("input#phoneCell").val(result[0].phoneCell);
$("input#phoneHome").val(result[0].phoneHome);
$("input#phoneFax").val(result[0].phoneFax);
$("input#source").val(result[0].source);
$("input#referBy").val(result[0].referBy);
$("input#client").val(result[0].id);
}
})
});

Php Ajax Form is not submitting

Hey guys I am creating a newsletter sign-up form and trying to submit it with AJAX..
Here is my form:
<div id="form-content">
<form method="POST" id="news-form" name="newsletter">
<div class="bd-input-2 form-group">
<input type="email" name="newsletter_email" placeholder="Enter your email address" required />
</div>
<div class="form-group">
<button type="submit" name="newsletter">Submit</button>
</div>
</form>
</div>
And this one is my JS file in same page as form:
$('#news-form').submit(function(e){
e.preventDefault();
$.ajax({
url: 'newsletter-submit.php',
type: 'POST',
data: $(this).serialize()
})
.done(function(data){
$('#form-content').fadeOut('slow', function(){
$('#form-content').fadeIn('slow').html(data);
console.log(data);
});
})
.fail(function(){
alert('Ajax Submit Failed ...');
});
});
On console nothing is displaying not even an error just an empty line.
And my newsletter-submit.php file :
<?php
if(isset($_POST['newsletter'])){
$newsletter_email = filter_var($_POST['newsletter_email'],FILTER_VALIDATE_EMAIL);
if(filter_var($newsletter_email, FILTER_VALIDATE_EMAIL)){
$newsletter_email = filter_var($newsletter_email, FILTER_VALIDATE_EMAIL);
$em_check = sqlsrv_query($con, "SELECT email FROM newsletter_signups WHERE email='$newsletter_email'",array(), array("Scrollable"=>"buffered"));
$num_rows = sqlsrv_num_rows($em_check);
if($num_rows > 0){
echo "<br/><p style='color: #fff;'>Email exist in our newsletter list.</p>";
}else{
$query = "INSERT INTO newsletter_signups (email) VALUES ('{$newsletter_email}')";
$insert_newsletter_query = sqlsrv_query($con,$query);
echo '<br/><p style="color: green;">Thank you for sign up in our newsletter</p>';
}
}
}
?>
But if I add any code after php tags e.g Hello world that is displayed after the submission.
My php code was working before AJAX file
Your input field is named newsletter_email and in your php you are checking for isset($_POST['newsletter']) which is always false.

Get the Echo from PHP into a Div with Ajax

I have a simple Database on a Server (for Testing).
This PHP File is on the Server and works when I open the URL. (http://**.com/search.php?id=abc) Echo gives back "30"
<?php
$pdo = new PDO('mysql:host=*com; dbname=*test1', '*', '*');
$idV = $_GET['id'];
$statement = $pdo->prepare("SELECT position FROM idtabelle WHERE idnumber = :idV");
$statement->bindParam(':idV', $idV);
$statement->execute();
while ($row = $statement->fetch(PDO::FETCH_ASSOC))
{ $posV = $row['position']; };
echo $posV;
?>
The HTML is just for Testing
<input type="text" id="txt1">
<button type="button" class="btn btn-info" id= "bt1">Info Button</button>
<div id= "div1"> </div>
I want that when i enter a Code in the Textfield and press the Button, the Echo from the PHP is Displayed in the Div.
I know i should use Ajax GET, but i tried so many things and nothing worked.
Could you help me pls?
Edit: Last try: https://jsfiddle.net/qz0yn5fx/
<input type="text" id="txt1">
<button type="button" class="btn btn-info" id="bt1">Info Button</button>
<div id="div1">Here </div>
<script>
$(document).ready(function() {
$("#bt1").click(function() {
$.ajax({
//create an ajax request to load_page.php
type: "GET",
url: "http://**.com/search.php?id=a10 ",
dataType: "html", //expect html to be returned
success: function(response){
$("#div1").html(response);
alert(response);
}
});
});
});
</script>
Better dont look at the next Fiddle i just copied all first Tries:
https://jsfiddle.net/jqv1ecpj/
You could just use a simple POST request instead of a GET request.
<form id="search" name="search" method="post">
<input type="text" id="txt1" name="search_input">
<button type="submit" class="btn btn-info" id="bt1">Info Button</button>
</form>
<div id="div1">Here </div>
$(document).ready(function(){
$("#search").on("submit", function(e){
e.preventDefault();
$.post("/search.php", $("#search").serialize(), function(d){
$("#div1").empty().append(d);
});
});
});
And then in your PHP, (don't forget to use try{}catch{}):
try {
$pdo = new PDO('mysql:host=*com; dbname=*test1', '*', '*');
$pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$idV = (isset($_POST['search_input'])) ? $idV = $_POST['search_input'] : exit('The search was empty');
$statement = $pdo->prepare("SELECT position FROM idtabelle WHERE idnumber = ?");
$statement->bindParam(1, $idV);
$statement->execute();
foreach($statement -> fetchAll() as $row){
echo $row['position'];
}
$pdo = null;
} catch (PDOException $e) {
die($e -> getMessage());
}
I think this should work (haven't tested it). Let me know if it doesn't work and I'll test and correct it.

To display data in the fields in the modal retrieved from the mysql database

Friends I am submitting the form on clicking the submit button and simultaneously i am displaying the just submitted data in the modal.So as soon as i hit the submit button ,the data gets submitted and a modal appears with the data just submitted.Everything is working fine with my code but the only problem that the data does not gets displayed in the modal.
Here is the code for submitting the form-
$("#savep").click(function(e){
e.preventDefault();
formData = $('form.pform').serialize() + '&'
+ encodeURI($(this).attr('name'))
+ '='
+ encodeURI($(this).attr('value'));
$.ajax({
type: "POST",
url: "data1_post.php",
data: formData,
success: function(msg){
$('input[type="text"], textarea').val('');
$('#entrysavedmodal').modal('show');
},
error: function(){
alert("failure");
}
});
});
Here is modal which gets displayed when i click on submit button-
<div id="entrysavedmodal" class="modal fade" role="dialog">
<div class="modal-dialog" style="width:1000px;">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><span class="glyphicon glyphicon-plus"></span> Saved Entry</h4>
</div>
<div class="modal-body">
<form class="form-horizontal savedform" id="savedform">
<div class="form-group">
<label class="control-label col-xs-2">Date:</label>
<div class="col-xs-4">
<input type="text" class="form-control" id="datepreview" name="datepreview"
value = "<?php
include('db.php');
$sql = "SELECT `date` FROM tran ORDER BY id DESC limit 1";
$result = mysqli_query($conn,$sql);
$rows = mysqli_fetch_assoc($result);
$date = $rows['date'];
echo $date;
?>" readonly /> //this field does not show anything and none of the fields show any data.
</div>
<label class="control-label col-xs-2">v_no:</label>
<div class="col-xs-4">
<input type="text" class="form-control" id="v_nopreview" name="v_no" autocomplete="off" readonly /> //same problem
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-info" id="print" name="print" >Print</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
Date field does not show the date value from database and v_nopreview field also does not show anything.
I have tried to give as much details as possible but in case if you need anything then let me know.Please let me know why the data is not being displayed inside the input fields in modal.
Thanks in advance.
Edited part
Here is the data1_post.php code-
<?php
include('db.php');
$sql = "INSERT INTO `table1` (`date`, `v_no`, `name`,`narration`,`stk_y_n`)
VALUES ( '".$_POST['date']."','".$_POST['v_no']."', '".$_POST['user']."','".$_POST['narration']."', 'No')";
if ($conn->query($sql) === TRUE){
echo "saved";
}
else
{
echo "not saved";
}
?>
As I understand, you expect execution of php code each time after js event. But PHP is a server-side language, it interprets only once, when you request the pages.
So your php code will load some content form DB after refreshing, then you clear input's value before displaying model and as it can't be executed again - you see empty modal.
I recommend you to return saved data from "data1_post.php" and than process it in success callback
UPDATE
if you want to present saved data, your php code would look like the following
include('db.php');
$response = ["success" => false];
$sql = "INSERT INTO `table1` (`date`, `v_no`, `name`,`narration`,`stk_y_n`)
VALUES ( '".$_POST['date']."','".$_POST['v_no']."', '".$_POST['user']."','".$_POST['narration']."', 'No')";
if ($conn->query($sql) === TRUE){
$sql = "SELECT `date` FROM tran ORDER BY id DESC limit 1";
$result = mysqli_query($conn,$sql);
$rows = mysqli_fetch_assoc($result);
$response = ["success" => true, "date" => $rows['date']];
}
header('Content-type: application/json');
echo json_encode($response);
and js
$("#savep").click(function(e){
e.preventDefault();
formData = $('form.pform').serialize() + '&'
+ encodeURI($(this).attr('name'))
+ '='
+ encodeURI($(this).attr('value'));
$.ajax({
type: "POST",
url: "data1_post.php",
data: formData,
success: function(response){
$('input[type="text"], textarea').val('');
if (response.success) {
$('#datepreview').val(response.date);
$('#entrysavedmodal').modal('show');
} else {
alert("failure");
}
},
error: function () {
alert("failure");
}
});
});

Image upload after submit using ajax

I am trying to upload image using ajax. But i am getting this error:
Notice: Undefined index: Image in /Applications/MAMP/htdocs/request/insert.php on line 8
Notice: Undefined index: Image in /Applications/MAMP/htdocs/request/insert.php on line 9
After clicked insert button then i am getting that error. The problem is just image section. Other details will still posting. There's something I missed.But I can not find. Anyone can help me here ?
My ajax code is here:
// Insert
$("body").on("click",".insert", function(){
var Desc = $(".Desc").val();
var Title = $(".Title").val();
var Image = $("#Image").val();
var dataString = 'Desc=' + Desc + '&Title=' + Title + '&Image=' + Image ;
$.ajax({
type: "POST",
url:"request/insert.php",
data: dataString,
cache:false,
success: function(html){
// Do something
}
});
});
HTML
<form method="post" action="" id="Form" enctype="multipart/form-data">
<div class="file-field input-field">
<div class="btn">
<span>File</span>
<input type="file" name="Image" id="Image">
</div>
</div>
<div class="row">
<div class="row">
<div class="input-field col s12">
<textarea id="textarea1" name="Desc" class="materialize-textarea Desc"></textarea>
<label for="textarea1">Textarea</label>
</div>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<input name="Title" id="first_name2" type="text" class="validate Title">
<label class="active" for="first_name2">First Name</label>
</div>
</div>
<div class="btn waves-effect waves-light insert" name="action">Submit
<i class="material-icons right">send</i>
</div>
</form>
PHP
<?php
include_once 'functions/db.php';
if(isSet($_POST['Title']) && isSet($_POST['Desc']) && isSet($_POST['Image'])) {
$Title = mysqli_real_escape_string($db, $_POST['Title']);
$Desc = mysqli_real_escape_string($db, $_POST['Desc']);
$Image = $_FILES['Image']['name'];
$image_tmp= $_FILES['Image']['tmp_name'];
move_uploaded_file($sliderPath);
$insert_query = mysqli_query($db,"INSERT INTO Post(Title,Desc,Image) VALUES ('$Title','$Desc','$Image')") or die(mysqli_error($db));
}
?>
You cannot send the image data like the way you are doing now inside jquery , you have to append it inside a FormData(); and then submit it to your url , as the image is multipart data , replace your javascript code with below:
$("body").on("click",".insert", function(){
var data = new FormData();
data.append('Desc',$(".Desc").val());
data.append('Title',$(".Title").val());
var Image = $("#Image").prop("files")[0];;
data.append('Image',Image);
$.ajax({
type: "POST",
url:"request/insert.php",
data: data,
cache:false,
processData:false,
contentType:false,
success: function(html){
// Do something
}
});
});
and inside php it is isset(); not iSset(); and also inside php change :
$_POST['Image']
to :
$_FILES['Image']
Your uploaded file information will be available in the global array $_FILES not $_POST and that is why you were not able to access it. You may access the Image information like this
$imageName = $_FILES['Image']['name']
You should also consider validating user's inputs before saving your data to the database. Rule #1: Never ever trust such data
Try your ajax call like this it will work for sure.
$("#Form").on("submit",function(e){
e.preventDefault();
var dataString = new FormData(this);
$.ajax({
type: "POST",
url:"img1.php",
data: dataString ,
processData: false,
contentType: false,
success: function(html){
console.log(html);
},
error: function(data){
console.log("error");
console.log(data);
}
});
});

Categories

Resources