post json to new window php - php

I want to post json output to a new window. How could I achieve this? Thank You!
Here is my code:
function onSuccess(data, status)
{
data = $.trim(data);
$("#notification").text(data);
}
$(document).ready(function() {
$("#submit").click(function(){
var formData = $("#callAjaxForm").serialize();
$.ajax({
type: "POST",
url: "callajax.php",
cache: false,
data: formData,
success: onSuccess,
error: onError
});
return false;
});
});
</script>
<form id="callAjaxForm">
<div data-role="fieldcontain">
<label for="firstName">First Name</label>
<input type="text" name="firstName" id="firstName" value="" />
<label for="lastName">Last Name</label>
<input type="text" name="lastName" id="lastName" value="" />
<button data-theme="b" id="submit" type="submit">Submit</button>
</div>
</form>
and below is callajax.php (I want to show the json information on this page)
<?php
$fName = $_POST['firstName'];
$lName = $_POST['lastName'];
echo("First Name: " . $firstName . " Last Name: " . $lastName);
?>

if you want to make a JSON representation of the data you are sending from the form use:
<?php
$fName = $_POST['firstName'];
$lName = $_POST['lastName'];
$resp = array('first_name'=>$fName,'last_name'=>$lName);
echo json_encode($resp);
?>

Related

jQuery(AJAX) post to php issue when I try to insert data into DB

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 ;
?>

Error in adding details by Ajax

Hello frndz i need a help i am trying to add detail by my form but no getting any value..and error is reflecting as "add request fails"..can anyone solve my error i am not getting what to do for this.. ther is my code
webapp.js
// Add company button
$(document).on('click', '#add_employee', function(e){
e.preventDefault();
$('.lightbox_content h2').text('Add Employee');
$('#form_employee button').text('Add');
$('#form_employee').attr('class', 'form add');
$('#form_employee').attr('data-id', '');
$('#form_employee .field_container label.error').hide();
$('#form_employee .field_container').removeClass('valid').removeClass('error');
$('#form_employee #ID').val('');
$('#form_employee #Name').val('');
$('#form_employee #Lastname').val('');
$('#form_employee #Email').val('');
$('#form_employee #Username').val('');
$('#form_employee #Password').val('');
$('#form_employee #Mobile').val('');
$('#form_employee #Website').val('');
show_lightbox();
});
// Add company submit form
$(document).on('submit', '#form_employee.add', function(e){
e.preventDefault();
// Validate form
if (form_employee.valid() == true){
// Send company information to database
hide_ipad_keyboard();
hide_lightbox();
show_loading_message();
var form_data = $('#form_employee').serialize();
var request =
$.ajax({
url: 'data.php',
cache: false,
data: {job:"add_employee",form_data},
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request.done(function(output){
if (output.result == 'success'){
// Reload datable
table_employee.api().ajax.reload(function(){
hide_loading_message();
var Name = $('#Name').val();
show_message("Employee Name '" + Name + "' added successfully.", 'success');
}, true);
} else {
hide_loading_message();
show_message('Add request failed', 'error');
}
});
request.fail(function(jqXHR, textStatus){
hide_loading_message();
show_message('Add request failed: ' + textStatus, 'error');
});
}
});
data.php
<?php
// Database details
$db_server = 'localhost';
$db_username = 'root';
$db_password = '';
$db_name = 'example1';
// Get job (and id)
$job = '';
$id = '';
if (isset($_GET['job'])){
$job = $_GET['job'];
if ($job == 'get_employee' ||
$job == 'get_employee_detail' ||
$job == 'add_employee' ||
$job == 'edit_employee' ||
$job == 'delete_employee'){
if (isset($_GET['id'])){
$id = $_GET['id'];
if (!is_numeric($id)){
$id = '';
}
}
} else {
$job = '';
}
}
// Prepare array
$mysql_data = array();
// Valid job found
if ($job != ''){
// Connect to database
$db_connection = mysqli_connect($db_server, $db_username, $db_password, $db_name);
if (mysqli_connect_errno()){
$result = 'error';
$message = 'Failed to connect to database: ' . mysqli_connect_error();
$job = '';
}
if ($job == 'add_employee'){
// Add company
$query = "INSERT INTO employees SET ";
if (isset($_GET['ID'])) { $query .= "ID = '" . mysqli_real_escape_string($db_connection, $_GET['ID']) . "', "; }
if (isset($_GET['Name'])) { $query .= "Name = '" . mysqli_real_escape_string($db_connection, $_GET['Name']) . "', "; }
if (isset($_GET['Lastname'])) { $query .= "Lastname = '" . mysqli_real_escape_string($db_connection, $_GET['Lastname']). "', "; }
if (isset($_GET['Email'])) { $query .= "Email = '" . mysqli_real_escape_string($db_connection, $_GET['Email']) . "', "; }
if (isset($_GET['Username'])) { $query .= "Username = '" . mysqli_real_escape_string($db_connection, $_GET['Username']). "', "; }
if (isset($_GET['Password'])) { $query .= "Password = '" . mysqli_real_escape_string($db_connection, $_GET['Password']). "', "; }
if (isset($_GET['Mobile'])) { $query .= "Mobile = '" . mysqli_real_escape_string($db_connection, $_GET['Mobile']) . "', "; }
if (isset($_GET['Website'])) { $query .= "Website = '" . mysqli_real_escape_string($db_connection, $_GET['Website']) . "'"; }
$query = mysqli_query($db_connection, $query);
if (!$query){
$result = 'error';
$message = 'add Employee error';
} else {
$result = 'success';
$message = 'Employees added success';
}
// Close database connection
mysqli_close($db_connection);
}
// Prepare data
$data = array(
"result" => $result,
"message" => $message,
"data" => $mysql_data
);
// Convert PHP array to JSON array
$json_data = json_encode($data);
print $json_data;
?>
**index.html**
<!doctype html>
<html lang="en" dir="ltr">
<head>
<title>Table</title>
<meta charset="utf-8">
<meta name="viewport" content="width=1000, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Oxygen:400,700">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel="stylesheet" href="design.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script charset="utf-8" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script charset="utf-8" src="//cdn.datatables.net/1.10.0/js/jquery.dataTables.js"></script>
<script charset="utf-8" src="http://cdn.jsdelivr.net/jquery.validation/1.13.1/jquery.validate.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"> </script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>
<script charset="utf-8" src="webapp.js"></script>
</head>
<body>
<div id="page_container">
<h1>Details of Employees</h1>
<button type="button" class="button" id="add_employee">Add Employees</button>
<table class="datatable" id="table_employee">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Lastname</th>
<th>Email</th>
<th>Username</th>
<th>Password</th>
<th>Mobile No</th>
<th>Website</th>
<th>Functions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div class="lightbox_bg"></div>
<div class="lightbox_container">
<div class="lightbox_close"></div>
<div class="lightbox_content">
<h2>Add Employees</h2>
<form class="form add" id="form_employee" data-id="" novalidate>
<div class="input_container">
<label for="Name">Name: <span class="required">*</span></label>
<div class="field_container">
<input type="text" class="text" name="Name" id="Name" value="" required>
</div>
</div>
<div class="input_container">
<label for="Lastname">Lastname: <span class="required">*</span></label>
<div class="field_container">
<input type="text" class="text" name="Lastname" id="Lastname" value="" required>
</div>
</div>
<div class="input_container">
<label for="Email">Email: <span class="required">*</span></label>
<div class="field_container">
<input type="text" class="text" name="Email" id="Email" value="" required>
</div>
</div>
<div class="input_container">
<label for="Username">Username: <span class="required">*</span></label>
<div class="field_container">
<input type="text" class="text" name="Username" id="Username" value="" required>
</div>
</div>
<div class="input_container">
<label for="Password">Password: <span class="required">*</span></label>
<div class="field_container">
<input type="password" class="text" name="Password" id="Password" value="" placeholder="eg. X8df90EO" required>
</div>
</div>
<div class="input_container">
<label for="Mobile">Mobile: <span class="required">*</span></label>
<div class="field_container">
<input type="text" class="text" name="Mobile" id="Mobile" maxlength="10" pattern="[7-9]{1}[0-9]{9}" placeholder="Only 10 digit Mobile no"required>
</div>
</div>
<div class="input_container">
<label for="Website">Website: <span class="required">*</span> </label>
<div class="field_container">
<input type="text" class="text" name="Website" id="Website" value="" placeholder="https://www.domain.com" required>
</div>
</div>
<div class="button_container">
<button type="submit">Add Employees</button>
</div>
</form>
</div>
</div>
<div id="message_container">
<div id="message" class="success">
<p>This is a success message.</p>
</div>
</div>
<div id="loading_container">
<div id="loading_container2">
<div id="loading_container3">
<div id="loading_container4">
Loading, please wait...
</div>
</div>
</div>
</div>
</body>
</html>
Change your submit HTML code to <input type="submit" value="Add Employees"></input>
And use my javascript source
<script type="text/javascript">
$( "#form_employee" ).submit(function( event ) {
var data = $(this).serializeArray();
data.push(
{name: "job", value: "add_employee"}
);
data = JSON.stringify(data);
$.ajax({
type: "POST",
url: "jsOnChange.php", //Set-Your-URL-Here
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
error: function(e)
{
alert(JSON.stringify(e, null, 4));
},
success: function(strDrivers){
alert(JSON.stringify(strDrivers, null, 4));
}
});
});
</script>
In .php listener
<?php
ini_set("allow_url_fopen", true);
$jsonStr = file_get_contents("php://input"); //read the HTTP body.
echo $jsonStr;
?>
You will get
Hope this help!!!
I think you code have some mistake at this place
var form_data = $('#form_employee').serialize();
var request =
$.ajax({
url: 'data.php',
cache: false,
data: {job:"add_employee",form_data},
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
Replace it with
var form_data = $('#form_employee').serialize();
form_data.job='add_employee';
var request =
$.ajax({
url: 'data.php',
cache: false,
data: form_data,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
Also in PHP side before print json_encode string add ob_clean() because you have mentioned dataType: json in ajax request.
ob_clean();
// Convert PHP array to JSON array
$json_data = json_encode($data);
print $json_data;

$_POST array is empty and I got undefined variable errors

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>

When I try to insert data into database through angularjs, neither it gives error nor gives any result. How to solve it?

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

How to save data using Ajax and PDO

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.

Categories