What I want to do is save all the data - after the user has filled all the forms - using Ajax and PDO.
My problem is that my Ajax won't send to user.php. I got an error in the console after I click the button says "data is not defined". Can anyone help me fix my code?
HTML
<form method="post" enctype="multipart/form-data">
<img id="picture" data-src="#" /> <br />
<input type='file' name="image" id="imgInp" accept="image/*" /><br />
Name: <input type="text" id="name" name="name" /><br />
Age: <input type="text" id="age" name="age" /><br />
Address: <input type="text" id="address" name="address" /><br />
<input type="radio" name="gender" id="gender" value="male" />Male
<input type="radio" name="gender" id="gender" value="Female" />Female<br />
<input type="submit" name="submit" id="submit" value="submit" />
</form>
Ajax
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function (e) {
e.preventDefault();
data.name = $('#name').val();
data.age = $('#age').val();
data.gender = $('#gender').val();
data.address = $('#address').val();
data.image = $('#imgInp').val();
$.ajax({
type: "POST",
url: "user.php",
data: data,
cache: false,
success: function (response) {
}
});
return false;
});
});
</script>
user.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$name = #$_POST['name'];
$age = #$_POST['age'];
$address = #$_POST['address'];
$gender = #$_POST['gender'];
$imageName = #$_FILES['image']['name'];
$q = "INSERT INTO students(name, age, address, gender, imageName ) VALUES(:name, :age, :address, :gender, :image)";
$query = $dbc->prepare($q);
$query->bindParam(':name', $name);
$query->bindParam(':age', $age);
$query->bindParam(':address', $address);
$query->bindParam(':gender', $gender);
$query->bindParam(':image', $imageName);
$results = $query->execute();
?>
Looks like you forgot to define your data variable.
var data = {};
data.name = $('#name').val();
You should initialize your data object as followed var data = {};.
Also consider to rename data to something like param. Just to not interfere with reserved names within the $.ajax({});-function. It's just a tip from a developer perspective.
Related
when I echo the php variable it work properly , but when I try to insert the data into database it doesn't work , what is the solution please I get stuck
I got this error on console
POST http://localhost/validate.php 500 (Internal Server Error)
send # jquery-3.1.1.min.js:4
ajax # jquery-3.1.1.min.js:4
(anonymous) # jquery.PHP:26
dispatch # jquery-3.1.1.min.js:3
q.handle # jquery-3.1.1.min.js:3
HTML/JQUERY
<form action="" id="myForm">
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="submit" value="Submit">
</form>
<div id="result"></div>
<script>
$(function() {
$("#myForm").submit(function(e) {
e.preventDefault();
var name = $('#name').val();
var age = $('#age').val();
$.ajax({
url: 'validate.php',
method: 'POST',
data: {postname:name, postage:age},
success: function(res) {
$("#result").append(res);
}
});
});
});
</script>
PHP
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
$sql = "insert into uss (first, last) values('".$name."','".$age."')";
$result = $conn->query($sql);
echo $result ;
?>
mysqldb.php
<?php
$conn = mysql_connect('localhost', 'root', 'password' , 'datab');
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
?>
Please add the details of the error message you get.
Make little changes to your code so that it can show the query error if any
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
$sql = "INSERT INTO `uss` (`first`, `last`) VALUES('{$name}','{$age}')";
if($conn->query($sql))
{
echo "Record inserted";
}
else
{
echo $conn->error;
}
?>
Sugesstions: Your query have the chances of the SQL Injection. Make it secure.
if you are using ajax , try the following,
<form >
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="submit" value="Submit" id="submit">
</form>
<div id="result"></div>
$("#submit").click(function(){
var name = $('#name').val(); // getting name
var age = $('#age').val();
$.ajax({
url : "validate.php",
type: "POST",
data: {name:name, age:age},
success: function(data)
{
$("#result").html(data);
}
});
});
in your controller function,echo the result
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
$sql = "insert into uss (first, last) values('$name','$age')";
$result = $conn->query($sql);
echo $result;
?>
jQuery Ajax
Form with id myFrom
<form action="" id="myForm">
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="submit" value="Submit">
</form>
<div id="result"></div>
jQuery Ajax section
$(function() {
$("#myForm").submit(function(e) {
e.preventDefault();
var name = $('#name').val(); // getting name
var age = $('#age').val(); // getting age
/* Ajax section */
$.ajax({
url: 'validate.php',
method: 'POST',
data: {postname:name, postage:age},
success: function(res) {
$("#result").append(res);
}
});
});
});
validate.php
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
//check ajax response by `echo $name` and `$age`
$sql = "insert into uss (first, last) values('".$name."','".$age."')";
$result = $conn->query($sql);
echo $result ;
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<form >
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="button" value="Submit" onclick="postdata();">
</form>
<div id="result"></div>
<script type="text/javascript">
function postdata() {
alert("ashad");
var name = $('#name').val();
var age = $('#age').val();
$.post('validate.php',{postname:name,postage:age},
function(data){
$('#result').html(data);
});
}
</script>
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
//check ajax response by `echo $name` and `$age`
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else
{
$sql = "insert into uss(first, last) values('$name','$age')";
$result = $conn->query($sql);
}
echo $result ;
?>
I've got a PHP class which has 1 method for inserting data. Once I create my instance of the class, I'm not sure how to call the method. I've seen other questions about how to accomplish calling a method, but none deal with calling the method of a class instance.
My PHP is:
<?php
$servername = "localhost";
$username = "kevin";
$password = "ally";
$database = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['btnInsert']) && ($_POST['btnInsert'] == "Insert"))
{
$Dog = new Dog($_POST['txtName'], $_POST['txtSize'], $_POST['txtColor'], $_POST['txttype'], $_POST['txtDescription']);
}
class Dog
{
public $name = "Dog Name";
public $size = 0;
public $color = "255:255:255";
public $typeName = "type Name";
public $typeDescription = "type Description";
public function Dog($name, $size, $color, $type, $description){
$this->name = $name;
$this->size = $size;
$this->color = $color;
$this->typeName = $type;
$this->typeDescription = $description;
}
public function InsertDog(){
$query = "SELECT Id from tbl_type WHERE Name = $typeName";
$result = mysqli_query($conn, "INSERT INTO tbl_type($this->typeName, $this->$typeDescription)") or die("Query fail: " . mysqli_error());
$result2 = mysqli_query($conn, "INSERT INTO tbl_Dog($this->$name, $this->$size, $this->$color, $query)") or die("Query fail: " . mysqli_error());
}
public function UpdateDog(){
}
}
?>
And my form:
<form action="index.php" method="post">
Dog Name:<br />
<input name="txtName" type="text" /><br />
<br />
Size:<br />
<input name="txtSize" type="text" /><br />
<br />
Color:<br />
<input name="txtColor" type="text" /><br />
<br />
type Name:<br />
<input name="txttype" type="text" /><br />
<br />
type Description:<br />
<input name="txtDescription" style="width: 419px; height: 125px" type="text" /><br />
<br />
<input name="btnInsert" type="submit" value="Insert" />
</form>
How can I call the InsertDog() method for the $Dog instance?
Simply use:
...
$Dog = new Dog($_POST['txtName'], $_POST['txtSize'], $_POST['txtColor'], $_POST['txttype'], $_POST['txtDescription']);
$Dog->InsertDog();
:)
You can simply have all your codes in one file (index.php) and then you can use:
$Dog = new Dog($_POST['txtName'], $_POST['txtSize'], $_POST['txtColor'], $_POST['txttype'], $_POST['txtDescription']);
$Dog->InsertDog();
Or second solution is add ajax to your code. So link jquery:
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
edit
<input name="btnInsert" type="submit" value="Insert" />
to
<input name="btnInsert" type="submit" value="Insert" id="buttonId" />
and add:
<script>
$( document ).ready(function() {
$( "#buttonId" ).click(function() {
$.ajax({
type: "POST",
url: "index.php",
data: { txtName: "DogsName", txtSize: "DogSize", txtColor: "color", txttype: "type", txtDescription: "dscr"v}
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
</script>
url to your index.php must really server/index.php - so if you use localhost, it must be http://localhost/index.php
I didn't test it, but it should works
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 am new to angularjs. When I try to insert data into database through angularjs, neither it reports error nor gives any result.
I have included 3 files here. I am trying to insert data with this code.
index.html
<form name="add_product" method="post">
<div class="lable_left">
<p>First Name :</p>
<p>Last Name :</p>
<p>Address :</p>
<p>Age :</p>
<p>Department :</p>
</div>
<div class="input_left">
<p><input type="text" name="fname" ng-model="fname"></p>
<p><input type="text" name="lname" ng-model="lname"></p>
<p><input type="text" name="address" ng-model="address"></p>
<p><input type="text" name="age" ng-model="age"></p>
<p><input type="text" name="dept" ng-model="dept"></p>
<input type="hidden" name="eid" ng-model="eid" />
<input type="button" name="submit_product" ng-show='add_prod' value="Submit" ng-click="product_submit()" class="submitbutton">
<input type="button" name="update_product" ng-show='update_prod' value="Update" ng-click="update_product()" class="submitbutton">
</div>
</form>
db.php
<?php
include('config.php');
switch($_GET['action']) {
case 'add_product' :
add_product();
break;
}
function add_product() {
$data = json_decode(file_get_contents("php://input"));
$fname = $data->fname;
$lname = $data->lname;
$address = $data->address;
$age = $data->age;
$dept = $data->dept;
print_r($data);
$qry = 'INSERT INTO employee (efname,elname,eaddress,eage,edept) values ("' . $fname . '","' . $lname . '",' .$address . ','.$age.','.$dept.')';
$qry_res = mysql_query($qry);
if ($qry_res) {
$arr = array('msg' => "Product Added Successfully!!!", 'error' => '');
$jsn = json_encode($arr);
// print_r($jsn);
}
else {
$arr = array('msg' => "", 'error' => 'Error In inserting record');
$jsn = json_encode($arr);
// print_r($jsn);
}
}
?>
controller.js
var listApp = angular.module('listpp', []);
listApp.controller('PhoneListCtrl', function ($scope,$http) {
/** function to get detail of product added in mysql referencing php **/
$scope.get_product = function() {
$http.get("db.php?action=get_product").success(function(data)
{
//$scope.product_detail = data;
$scope.pagedItems = data;
});
}
/** function to add details for products in mysql referecing php **/
$scope.product_submit = function() {
$http.post("db.php?action=add_product",
{
'efname' : $scope.fname,
'elname' : $scope.lname,
'eaddress' : $scope.address,
'eage' : $scope.age,
'edept' : $scope.dept
}
)
.success(function (data, status, headers, config) {
$scope.get_product();
})
.error(function(data, status, headers, config){
});
}
Any help will be highly appreciated,
Thanks
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' ;