My script does not seem to be working. Every time i try to use the form i've get the error with readystate=0, and status=0. Any help will be appreciated.
I've got the following form:
<form action="" method="post" >
<input type="text" name="name" id="tekst"/><br/>
<input type="text" name="name" id="autor"/><br/>
<input type="submit" name="<?php echo $id; ?>" value="Send" id="submit"/>
</form>
<div class="response"></div>
the values from input fields are then processed by the following code:
$("input#submit").click(function(){
var id = $("input#submit").attr("name");
var autor = $('input#autor').val();
var tresc = $('input#tekst').val();
$.ajax({
type: "POST",
url: "add_comment.php",
data:
{id: id,
autor: autor,
tresc: tresc},
success: function(data){
$(".response").text(data);
},
error:function(xhr,err){
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
});
});
Here is my add_comment.php:
<?php
$id = $_POST['id'];
$autor= $_POST['autor'];
$tresc = $_POST['tresc'];
if(isset($id) && isset($autor) && isset($tresc)){
include("db/connection.php");
$zapytanie= "INSERT INTO komentarze(id_ref, autor, tresc) values ('$id', '$autor', '$tresc')";
$wynik = $db->query($zapytanie);
echo "Added";
}else{
echo "Problem";
}
?>
EDIT:
id_ref is not auto_increment field. The script is running on the localhost
First of all, your form isn't correct...name="name", class=".response"??
<form action="" method="post" >
<input type="text" name="tekst" id="tekst"/><br/>
<input type="text" name="autor" id="autor"/><br/>
<input type="submit" name="id" value="Send" id="submit"/>
</form>
<div class="response"></div>
Your PHP File should be"
<?php
$id = $_POST['id'];
$autor= $_POST['autor'];
$tresc = $_POST['tekst'];
if(isset($id) && isset($autor) && isset($tresc)){
include("db/connection.php");
$zapytanie= "INSERT INTO komentarze(id_ref, autor, tresc) values ('$id', '$autor', '$tresc')";
$wynik = $db->query($zapytanie);
echo "Added";
}else{
echo "Problem";
}
?>
<form action="add_comment.php" method="post" >
<input type="text" name="tekst" id="tekst"/><br/>
<input type="text" name="autor" id="autor"/><br/>
<input type="submit" name="button" value="Send" id="submit"/>
</form>
And in php it should be like this
$id = $_POST['button'];
$autor= $_POST['autor'];
$tresc = $_POST['tekst'];
It should work properly now. Previously you were making a mistake that in the submit button field you were passing a php variable which could contain anything and you dont know if it is dynamic. So you weren't be able to get it by using $_REQUEST['id'] because it could have been some thing like this
$id = 1; or $id = 'dynamic string' ;
Related
I am able to get data from my form to backend php but how to insert it to MySQL?
Here is my form
<div class="container">
<form class="form-control" method="post" action="save.php">
<div id="input_fields">
<div class="container">
<input type="text" name="name[]" placeholder="name"> <input type="text" name="project[]" placeholder="project"> <button class="btn btn-primary" id="add_field">+</button>
</div>
</div>
<input class="btn btn-primary" type="submit" value="submit">
</form>
</div>
<script>
$(document).ready(function() {
$("#add_field").click(function(e){
e.preventDefault();
$("#input_fields").append('<div class="container"><input type="text" name="name[]" placeholder="name"/> <input type="text" name="project[]" placeholder="project"> <button id="remove" class="btn btn-danger">-</button></div>');
});
$("#input_fields").on("click","#remove", function(e){
e.preventDefault(); $(this).parent('div').remove();
x--;
})
});
</script>
Backend php code Here on foreach I used echo to check data and it show me correct data but it is not inserting to MySQL.
if(isset($_POST["name"]) && isset($_POST["project"])) {
foreach($_POST['name'] as $key => $val) {
$proj = $_POST['project'][$key];
echo "Name ".$val." Project ".$proj;
$insert = "INSERT INTO table_name (column1,colunm2) values ('$val','$proj')";
$result = $conn->query($insert);
}
if($result) {
echo "Data inserted Successfully";
}
}
You can check that there is any error in query. If have then try to fix the following error.
if(!$result) die($conn->error);
Remove this line for now
if($result) {
echo "Data inserted Successfully";
}
and define this code inside loop, just below where foreach loop starts -
$insert = '';
$result = '';
I hope this will help you!
I am trying to make a simple incentive calculator.
PROBLEMS:
When I am submitting the form the values of the fields and field names are showing are showing up in the address bar.
eg: "http://localhost/incentive%20tracker/?jQueryDatePicker1=09%2F05%2F2015&pid=n&qty=1&memo=&remarks=&add=Add"
When I try to submit the values in the first attempt just after the first load of the page, the values are not getting inserted in the database. After the first attempt, the values do get inserted.
On success in insertion of data in the database, jQuery doesn't show me any message in spite of having the success function.
I am not being able to display an error message if the qty field is negative.
I am not sure what I am doing wrong.
HTML
<form id="saleDetail">
<input type="text" id="jQueryDatePicker1" name="jQueryDatePicker1" value="06/05/2015">
<input type="text" name="pid" id="pid" required placeholder="Enter a product code">
<datalist id="products">
<?php
$sql="SELECT * FROM products";
$result = mysqli_query($db, $sql);
while($fetch_options=mysqli_fetch_array($result)){
?>
<option value="<?php echo $fetch_options['pid']; ?>"><?php echo $fetch_options['pid']; ?></option>
<?php
}
?>
</datalist>
<input type="number" id="qty" name="qty" value="" autocomplete="off" required placeholder="Enter the Quantity">
<input type="text" id="memo" name="memo" value="" autocomplete="off" placeholder="Enter the Cash memo number">
<textarea name="remarks" id="remarks" rows="2" cols="27" placeholder="Any remarks"></textarea>
<input type="submit" id="add" name="add" value="Add">
<div id="message"></div>
</form>
JQuery
<script>
$(document).ready(function()
{
var jQueryDatePicker1Opts =
{
dateFormat: 'dd/mm/yy',
changeMonth: false,
changeYear: false,
showButtonPanel: false,
showAnim: 'slideDown'
};
$("#jQueryDatePicker1").datepicker(jQueryDatePicker1Opts);
$("#jQueryDatePicker1").datepicker("setDate", "new Date()");
$("#PanelMenu1").panel({animate: true, animationDuration: 200, animationEasing: 'swing', dismissible: true, display: 'push', position: 'right'});
$('#add').click(function()
{
var date=$('#jQueryDatePicker1').val();
var pid=$('#pid').val();
var qty=$('#qty').val();
var remarks=$('#remarks').val();
var memo=$('#memo').val();
if(pid==="" || qty==="" || qty<0){
$("#message").html("<span style='color:#cc0000'>Please fill in the required fields!");
}
else{
var dataString='date='+date+'&pid='+pid+'&qty='+qty+'&remarks='+remarks+'&memo='+memo;
$.ajax({
type:"POST",
data: dataString,
url: "add.php",
cache:false,
success: function(html){
$("#message").html("Data Added successfully! ");
}
});
}
});
return false;
});
</script>
PHP
<?php
include 'connect.php';
$error_message = "";
$mysql_table = "sales";
//if ($_SERVER['REQUEST_METHOD'] == 'POST')
if (isset($_POST['pid']) && isset($_POST['qty']))
{
$newdate =$_POST['date'];
$newpid = $_POST['pid'];
$newqty = $_POST['qty'];
$newremarks = $_POST['remarks'];
$newmemo = $_POST['memo'];
$newpid = mysqli_real_escape_string($db, $newpid);
$newqty = mysqli_real_escape_string($db, $newqty);
$newremarks = mysqli_real_escape_string($db, $newremarks);
$newmemo = mysqli_real_escape_string($db, $newmemo);
$sql = "SELECT incentive FROM products WHERE pid = '$newpid'";
$result = mysqli_query($db, $sql);
$rate=mysqli_fetch_array($result);
$amt = $rate['incentive'] * $newqty;
$sql = "INSERT `".$mysql_table."` (`date`, `pid`, `qty`, `amt`, `memo`, `remarks`) VALUES ('$newdate', '$newpid', '$newqty', '$amt', '$newmemo', '$newremarks')";
$results = mysqli_query($db, $sql);
echo "Success";
mysqli_close($db);
}
?>
Sorry to ask it again, but I checked almost all the q&a's on the topic and still couldn't solve it. Here is my form.php and creditform.php
Edit1.Changed the .get to .post
Edit2.I'm getting errors of undefined variable "name" "email" "address" "income" etc (in short for all of them) in creditform.php
What I want to do is just insert all the inputs into the table in db.
HTML
<!-- End crumbs-->
<div class="container wrap wow fadeInUp">
<div class="row">
<div class="col-sm-5 col-md-6 left-app">
<form id="form" action="php/creditform.php" method="post">
<input type="text" placeholder="Name" name="name" required>
<input type="email" placeholder="Email" name="email" required>
<input type="text" placeholder="Address" name="address" required>
<input type="number" placeholder="Monthly income before taxes" name="income" required>
<input type="number" placeholder="Amount Needed" name="amount_needed" required>
<input type="number" placeholder="Phone" name="phone" required>
<div class="row">
<div class="container">
<input type="submit" name="submit" value="Submit" class="button"></div></div>
<div id="result"></div>
</form>
</div>
<script>
$(document).ready(function($) {
'use strict';
$('#form').submit(function(event) {
event.preventDefault();
var url = $(this).attr('action');
var datos = $(this).serialize();
$.post(url, datos, function(resultado) {
$('#result').html(resultado);
});
});
</script>
FORM.PHP
<?php
include('db.config.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $email = $address = $income = $amount_needed = $phone = '';
if(isset($_POST['submit'])){
$name = addslashes($_POST['name']);
$email = addslashes($_POST['email']);
$address = addslashes($_POST['address']);
$income = addslashes($_POST['income']);
$amount_needed = addslashes($_POST['amount_needed']);
$phone = addslashes($_POST['phone']);
// check form fields
if(empty($name)){
$error .= 'Enter name <br />';
}
if(empty($email)){
$error .= 'Enter email <br />';
}
// check if errors exist
if(!empty($error)){
echo $error;
} else {
// process form as normal
$sql = "INSERT INTO `" . DBN . "`.`creditapp` (`name`, `email`, `address`, `income`, `amount_needed`, `phone`) VALUES ('$name', '$email', '$address', '$income', '$amount_needed', '$phone')";
$db->Query($sql);
}
}
}
print_r($_POST);
?>
CREDITFORM.PHP
<?php
if(isset($_POST['submit'])){
$name = $_POST['name'];
$email = $_POST['email'];
$address = $_POST['address'];
$income = $_POST['income'];
$amount_needed = $_POST['amount_needed'];
$phone = $_POST['phone'];
}
print_r($_POST);
?>
It's obvious that I'm missing something, please correct me...
Thanks for your time
You need to send a POST request for the $_POST array to have anything in it.
$.get(url, datos, function(resultado) {
$('#result').html(resultado);
});
This sends a GET request (check $_GET). You want to use $.post here instead.
$.post(url, datos, function(resultado) {
$('#result').html(resultado);
});
Here is a simple Ajax call to a Php File by an event : Click on a button.
In your example you must use POST method because you use :
$_POST['something'];
Javascript client side :
$("body").on("click", "#mybutton", function() {
var mydata = $("#form").serialize();
$.ajax({
type: "POST",
url: "/api/api.php",
data: {data : mydata},
timeout: 6e3,
error: function(a, b) {
if ("timeout" == b) $("#err-timedout").slideDown("slow"); else {
$("#err-state").slideDown("slow");
$("#err-state").html("An error occurred: " + b);
}
},
success: function(a) {
var e = $.parseJSON(a);
if (true == e["success"]) {
$("#result").html(e['message']);
// here is what you want, callback Php response content in Html DOM
}
}
});
return false;
});
Next in your Php code simply do after any success function :
if ($result) {
echo json_encode(array(
'success' => true,
'msg' => "Nice CallBack by Php sent to client Side by Ajax Call"
));
}
Okay, I practiced more on ajax - json - php and in the end this was my solution and my latest code.
Thanks for all answers and suggestions. Hope this also helps to someone.
Still open to any kind of advice to improve.
<?php
include('db.config.php');
if(isset($_POST['submit'])){
$name = addslashes($_POST['name']);
$email = addslashes($_POST['email']);
$address = addslashes($_POST['address']);
$income = addslashes($_POST['income']);
$amount_needed = addslashes($_POST['amount_needed']);
$phone = addslashes($_POST['phone']);
// process form as normal
$sql = "INSERT INTO `" . DBN . "`.`creditapp` (`name`, `email`, `address`, `income`, `amount_needed`, `phone`) VALUES ('$name', '$email', '$address', '$income', '$amount_needed', '$phone')";
$db->Query($sql);
die();
<div class="container wrap wow fadeInUp">
<div class="row">
<div class="col-sm-5 col-md-6 left-app">
<form id="form" action="creditapp.php" method="post">
<input type="text" placeholder="Name" name="name" id="name" required>
<input type="email" placeholder="Email" name="email" id="email" required>
<input type="text" placeholder="Address" name="address" id="address" required>
<input type="text" placeholder="Monthly income before taxes" id="income" name="income" required>
<input type="text" placeholder="Amount Needed" name="amount_needed" id="amount_needed" required>
<input type="text" placeholder="Phone" name="phone" id="phone" required>
<div class="row">
<div class="container">
<input type="submit" name="submit" value="Submit" class="button sub"></div>
</div>
</form>
</div>
<script>
$(document).ready(function() {
$('.sub').click(function(e){
e.preventDefault();
var name = $('#name').val(),
email = $('#email').val(),
address = $('#address').val(),
income = $('#income').val(),
amount_needed = $('#amount_needed').val(),
phone = $('#phone').val();
$.ajax({
url: "creditapp.php",
type: "POST",
data: {
name: name,
email: email,
address: address,
income: income,
amount_needed: amount_needed,
phone: phone,
submit: "submit"
}
}).done(function(msg){
$('.right-info').html('<pre>' + msg + '</pre>');
})
})
});
</script>
The problem you are having is with your javascript. You wait for the submit and than you do an ajax GET request, you need a POST.
<script>
$(document).ready(function($) {
'use strict';
$('#form').submit(function(event) {
event.preventDefault();
var url = $(this).attr('action');
var datos = $(this).serialize();
$.post(url, datos, function(resultado) {
$('#result').html(resultado);
});
});
</script>
I'm going to keep it short and simple. I'm writing a really basic code in php which adds content to mysql db and I've run into an issue with editing. This is my form:
if($idExists)
{
Print '
<form action="editIt.php" method="POST">
<div name="id"> '. $id . '</div>
Enter new detail: <input type="text" name="details"/><br/>
public post? <input type="checkbox" name="public[]" value="yes"/><br/>
<input type="submit" value="Update List"/>
</form>
';
}
And this is my editIt.php
//session start and stuff
if(filter_input(INPUT_SERVER, 'REQUEST_METHOD', FILTER_SANITIZE_STRING) == "POST")
{
echo "<script type='text/javascript'>alert('EDITIT!');</script>";
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("WebSiteDB") or die ("Cannot connect to database");
$id = $_POST['id'];
$details = mysql_real_escape_string($_POST['details']);
$time = strftime("%X");
$date = strftime("%B %d, %Y");
$isPublic = 'no';
foreach($_POST['public'] as $eachCheck)
{
if($eachCheck != NULL)
$isPublic = "yes";
}
mysql_query("UPDATE list SET details='$details', dateEdited='$date', timeEdited= '$time', public='$isPublic' WHERE id='$id'");
header("location: home.php");
}
I can't really find an issue with this code (which is not really strange, I'm a newbie at web stuff) and yet it just goes to home.php and does not change data in DB. Please, help me jump this ledge, so I can go on with my life.
I think, the problem is in this line $id = $_POST['id'];. On form submit, the input field value will only be submitted, not the DIV value.
So, please change from :
if($idExists)
{
Print '
<form action="editIt.php" method="POST">
<div name="id"> '. $id . '</div>
Enter new detail: <input type="text" name="details"/><br/>
public post? <input type="checkbox" name="public[]" value="yes"/><br/>
<input type="submit" value="Update List"/>
</form>
';
}
To :
if($idExists)
{
Print '
<form action="editIt.php" method="POST">
<input type="hidden" name="id" value="' . $id . '">
Enter new detail: <input type="text" name="details"/><br/>
public post? <input type="checkbox" name="public[]" value="yes"/><br/>
<input type="submit" value="Update List"/>
</form>
';
}
My code given below. Please help me correct the code. Iam confused with syntax. Also I do not know where exactly to put error message alert if there is any database issue and how to close the database. Please help
<form id="ContactForm" name="form1" method="post" onsubmit="submitdata()">
<div>
<div class="formwrap"><span>Your Name:</span><input name="fname" type="text" class="input" ></div>
<div class="formwrap"><span>Your E-mail:</span><input type="text" name="femail" class="input" ></div>
<div class="formwrap"><span>Your Mobile:</span><input type="text" name="fmobile" class="input" ></div>
<div class="formwrap"><span>Your City:</span><input type="text" name="fcity" class="input" ></div>
<div class="textarea_box"><span>Your Message:</span><textarea name="fmessage" cols="1" rows="1"></textarea></div>
<a class="button" onClick="document.getElementById('ContactForm').submit()"><span class="shadow"></span>Send</a>
<a class="button" onClick="document.getElementById('ContactForm').reset()"><span class="shadow"></span>Clear</a>
</div>
</form>
<?php
function submitdata(){
include "config/connection.php";
$fdname = $_POST['fname']);
$fdemail = $_POST['femail']);
$fdmobile = $_POST['fmobile']);
$fdcity = $_POST['fcity']);
$fdmessage = $_POST['fmessage']);
$sql="INSERT INTO users (name, email, mobile, city, message)
VALUES ('$fdname', '$fdemail', '$fdmobile', '$fdcity', '$fdmessage')";
}
?>
Thank you
I changed the action on your html form and created the php script that will handle and store your data into the database,take a look and do some further reading on prepared statements.
<form id="ContactForm" name="form1" action="insert.php" method="post">
<div>
<div class="formwrap"><span>Your Name:</span><input name="fname" type="text" class="input" ></div>
<div class="formwrap"><span>Your E-mail:</span><input type="text" name="femail" class="input" ></div>
<div class="formwrap"><span>Your Mobile:</span><input type="text" name="fmobile" class="input" ></div>
<div class="formwrap"><span>Your City:</span><input type="text" name="fcity" class="input" ></div>
<div class="textarea_box"><span>Your Message:</span><textarea name="fmessage" cols="1" rows="1"></textarea></div>
<a class="button" onClick="document.getElementById('ContactForm').submit()"><span class="shadow"></span>Send</a>
<a class="button" onClick="document.getElementById('ContactForm').reset()"><span class="shadow"></span>Clear</a>
</div>
</form>
insert.php
<?php
if($_POST){
$db = new mysqli("address","id","password","DBname");
if (mysqli_connect_errno())
{
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
$stmt = $db->prepare("INSERT INTO users (name, email, mobile, city, message) VALUES (?, ?, ?, ?, ?)");
$stmt -> bind_param('sssss', $fname, $femail, $fmobile, $fcity, $fmessage);
$fname = $_POST['fname'];
$femail = $_POST['femail'];
$fmobile = $_POST['fmobile'];
$fcity = $_POST['fcity'];
$fmessage = $_POST['fmessage'];
$stmt -> execute();
$stmt -> close();
$db -> close();
}
?>
You can use something like this (if you have jQuery included):
<script>
$(document).ready(function () {
$('form[name=form1]').submit(function () {
var fname = $('input[name=fname]').val();
var femail = $('input[name=femail]').val();
var fmobile = $('input[name=fmobile]').val();
var fcity = $('input[name=fcity]').val();
var fmessage = $('textarea[name=fmessage]').val();
$.post("/ajax/insert.php", {
'fname': fname,
'femail': femail,
'fmobile': fmobile,
'fcity': fcity,
'fmessage': fmessage
}, function (data) {
if (data == 1) {
alert("Success");
} else {
alert("Error");
}
});
});
});
</script>
Then make folder "ajax" in the root of website and make there a script called insert.php (if you want different name, edit line 9 in the js code). Content of the insert.php will be something like this:
<?php
include "config/connection.php";
$fdname = $_POST['fname'];
$fdemail = $_POST['femail'];
$fdmobile = $_POST['fmobile'];
$fdcity = $_POST['fcity'];
$fdmessage = $_POST['fmessage'];
$sql="INSERT INTO users (name, email, mobile, city, message)
VALUES ('$fdname', '$fdemail', '$fdmobile', '$fdcity', '$fdmessage')";
mysql_query($sql);
if(mysql_error()) {
echo 0;
} else {
echo 1;
}
?>
For onsubmit attribute JS function or codes is required not PHP function. But you provided a PHP function in onsubmit. I suggest you to use AJAX or action in form.
An Example for you
<form id="ContactForm" name="form1" >
<div>
<div class="formwrap"><span>Your Name:</span><input name="fname" type="text" class="input" ></div>
<div class="formwrap"><span>Your E-mail:</span><input type="text" name="femail" class="input" ></div>
<div class="formwrap"><span>Your Mobile:</span><input type="text" name="fmobile" class="input" ></div>
<div class="formwrap"><span>Your City:</span><input type="text" name="fcity" class="input" ></div>
<div class="textarea_box"><span>Your Message:</span><textarea name="fmessage" cols="1" rows="1"></textarea></div>
<a class="button" id="submit"><span class="shadow"></span>Send</a>
<a class="button" onClick="document.getElementById('ContactForm').reset()"><span class="shadow"></span>Clear</a>
</div>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
$('#submit').click(function(){
$.ajax({
url: 'test.php',
data: $('#ContactForm').serialize(),
type: 'post',
success: function(data){
if(data == 'inserted'){
alert('Inserted');
}else{
console.log(data);
}
}
});
});
</script>
In test.php
include "config/connection.php";
$fdname = $_POST['fname'];
$fdemail = $_POST['femail'];
$fdmobile = $_POST['fmobile'];
$fdcity = $_POST['fcity'];
$fdmessage = $_POST['fmessage'];
$sql="INSERT INTO users (name, email, mobile, city, message)
VALUES ('$fdname', '$fdemail', '$fdmobile', '$fdcity', '$fdmessage')";
// if you use mysql connection
$result = mysql_query($sql);
if($result) {
echo 'inserted';
} else {
die(mysql_error());
}
You also fix some syntax error. Remove ) after each $_POST.