So I'm thinking there is an issue with the serialization part of the jquery ajax. It's not putting any information into the database and I have no idea why! Obviously the variables from the input controls on the webpage are not being passed into the php processing page. What am I doing wrong here?? Need some help here with this folks! This is all very new to me.
Webpage:
<form name="main_form" id="main_form" method="post">
<div id="ChangeAddressDialog" title="Change of Address">
<p>Mailing Address: <input type="text" id="Address1" name="Address1" /></p>
<p>Mailing Address 2: <input type="text" id="Address2" name="Address2" /></p>
<p>City: <input type="text" id="City" name="City" /></p>
<p>State: <input type="text" id="State" name="State" maxlength="2" /></p>
<p>Zip Code: <input type="text" id="Zip" id="Zip" maxlength="10" /></p>
<p>Country: <input type="text" id="County" name="Country" /></p>
<input type="hidden" id="change_of_address_form" name="change_of_address_form" />
</div>
</form>
$('#ChangeOfAddress').click(function() {
//change of address dialog
$( "#ChangeAddressDialog" ).dialog({
width:500,
modal:true,
closeOnEscape:true,
buttons: [
{ text: "Ok", type: "submit", click: function() {
$.ajax({
url: "classes/add-address.php",
type: "POST",
data: $("#main_form").serialize(),
dataType: 'json',
error: function(SMLHttpRequest, textStatus, errorThrown){
alert("An error has occurred making the request: " + errorThrown)
},
success: function(result){
//do stuff here on success such as modal info
//$("#main_form").submit();
$(this).dialog("close");
}
})
}
},
{ text: "Close", click: function() { $(this).dialog( "close" ); } } ]
});//end dialog
});
PHP processing page:
<?php
require_once('../config.php');
//$sqlCheck = '';
$parcel_id = isset($_POST['ParcelId']) ? $_POST['ParcelId'] : null;
$address1 = isset($_POST['Address1']) ? $_POST['Address1'] : null;
$address2 = isset($_POST['Address2']) ? $_POST['Address2'] : null;
$city = isset($_POST['City']) ? $_POST['City'] : null;
$state = isset($_POST['State']) ? $_POST['State'] : null;
$zip = isset($_POST['Zip']) ? $_POST['Zip'] : null;
$country = isset($_POST['Country']) ? $_POST['Country'] : null;
$db = new ezSQL_mysql(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
$result = $db->query("INSERT INTO change_of_address (parcel_id, address_1, address_2, City, State, Zip, Country) VALUES ('" . $parcel_id . "','" . $address1 . "','" . $address2 . "','" . $city . "','" . $state . "','" . $zip . "','" . $country . "')");
if ($result == 1) {
echo '{"success":true}';
} else {
echo '{"success":false}';
}
//$sqlCheck = "INSERT INTO change_of_address (parcel_id, address_1, address_2, City, State, Zip, Country) VALUES ('" . $parcel_id . "','" . $address1 . "','" . $address2 . "','" . $city . "','" . $state . "','" . $zip . "','" . $country . "')";
//echo json_encode($sqlCheck);
?>
data: $("#main_form").serialize(),
The form element is named main_form. Your jquery selector is looking for an id. You can just change name="main_form" to id="main_form" on your form tag and it should fix it.
Related
well I am trying to insert user data and I made these codes , the record is being created but there is no data in it , just to clarify I have include the files and I am connected to the database and I think I declared all the necessary objects , if you know what is wrong I would appreciate a bit more explaining I am a beginner
addUser.php
<div id="message" class="flex-row align-center flex-nowrap">
<h4 class="heading flex-1"></h4>
</div>
<div class="flex-row form-row">
<div class="flex-column create-session-sidebar__column">
<form class="form" method="post">
<div class="Faseeh-form-input outlined"><label class="label">الاسم الاول</label>
<input id="fname" placeholder="" type="text" value=""></div>
<div class="Faseeh-form-input outlined"><label class="label">الاسم الثاني</label>
<input id="lname" placeholder="" type="text" value=""></div>
<div class="Faseeh-form-input outlined"><label class="label">اسم المستخدم</label>
<input id="username" placeholder="" type="text" value=""></div>
<div class="Faseeh-form-input outlined"><label class="label">البريد الالكتروني</label>
<input id="email" placeholder="" type="email" value=""></div>
<div class="Faseeh-form-input outlined"><label class="label"> الالكتروني</label>
<input id="password" placeholder="" type="password" value=""></div>
<div class="flex-row form-row">
<button id="addUser" class="Faseeh-btn Faseeh-btn Faseeh-btn-primary" type="submit">تسجيل</button>
</div>
</form>
</div>
</div>
</div>
<script>
$(document).ready(function() {
NewUser();
});
function NewUser() {
$(document).on('click', '#addUser', function() {
var fname = $('#fname').val();
var lname = $('#lname').val();
var username = $('#username').val();
var email = $('#email').val();
var password = $('#password').val();
var data = "fname=" + fname + "&lname=" + lname + "&username=" + username + "&email=" + email + "&password=" + password;
if(fname == "" || lname == "" || username == "" || email == "" || password == ""){
$('#message').html('Please fill in the blanks');
}else{
$.ajax ({
url: 'core/register.php?',
type:'post',
data: data,
success: function(data) {
$("#message").html(data);
}
});
}
});
}
</script>
and this is register.php
<?php
include_once "util.php";
session_start();
$util = new util();
$post = $_POST['data'];
$data = json_decode($post);
$result = $util->newUser($data);
if($result) {
echo 1;
}else {
echo 0;
}
and finally util.php
public function newUser($data){
// Our database object
$db = new dbhandler();
// Quote and escape form submitted values
$fname = $db -> quote($fname->fname);
$lname = $db -> quote($lname->lname);
$username = $db -> quote($username->username);
$email = $db -> quote($email->email);
$password = $db -> quote($password->password);
// Insert the values into the database
$result = $db -> query("INSERT INTO `users` (`fname`,`lname`,`username`,`email`,`password`) VALUES (" . $fname . "," . $lname . "," . $username . "," . $email . "," . $password . ");");
}
Almost! 2 problems though.
You are sending in the data as a url format, but you are reading it as a JSON format. Instead of
var data = "fname=" + fname + "&lname=" + lname + "&username=" + username + "&email=" + email + "&password=" + password;
You need to create an object with:
var data = array(
"fname": fname,
"lname": lname,
"username": username,
"email": email,
"password": password
}
You need to get the variables from inside the $data object you passed in.
public function newUser($data){
// Our database object
$db = new dbhandler();
// Quote and escape form submitted values
$fname = $db -> quote($data->fname);
$lname = $db -> quote($data->lname);
$username = $db -> quote($data->username);
$email = $db -> quote($data->email);
$password = $db -> quote($data->password);
// Insert the values into the database
$result = $db -> query("INSERT INTO `users` (`fname`,`lname`,`username`,`email`,`password`) VALUES (" . $fname . "," . $lname . "," . $username . "," . $email . "," . $password . ");");
}
I am trying to store the form data into database using ajax but it doesn't shows any success neither any error.
Here is my code.
<form method="POST" id="add_user" name='reg' >
<fieldset>
<legend>Student information:-</legend>
<ul>
<li>
<label> FirstName: </label><input type="text" id="name" name="name" required>
<span id='error' style="display:none;color:red;"> Only alphabets </span>
</li>
<li>
<label> LastName: </label><input type="text" id="lname" name="lname" required>
<span id='error1' style="display:none;color:red;"> Only alphabets </span>
</li>
<li>
<label>Username:</label>
<input type="text" id="username" name="username"/>
< /li>
<li>
<label>Password:</label>
<input type="password" id="password" name="password"/>
</li>
<label>
Gender: </label>
<input type="radio" id='gender' name="gender" value="male" required> Male
<input type="radio" name="gender" id='gender' value="female" required> Female
<input type="radio" name="gender" id='gender' value="other" required> Other
<li>
<label>
Email: </label>
<input id="email" type="text" name="email" required>
<span id='error2' style="display:none;color:red;"> Invalid email </span>
</li>
<li>
<label> Mobile:</label>
<input id="mobile" type="text" maxlength="10" name="mobile" required >
<span id='error3' style="display:none;color:red;"> only digits </span>
</li>
<li>
address: <textarea name="address" type="text" rows="3" cols="40"> </textarea>
</li>
</ul>
<p><button class = 'button' type="submit" id='submit'>Add User</button></p>
</fieldset>
</form>
This form in which i enter any values it got stored into database.
Here is my js file which uses ajax function to send data inext file which stores the result into database
serve.js
$(document).ready(function(){
$(document).on('submit','#add_user',function(e){
var form_data = $('#add_user').serialize();
var request = $.ajax({
url: 'fun.php?job=add',
cache : false,
data : form_data,
dataType : 'json',
contentType : 'application/json; charset=utf-8',
type : 'get'
});
request.done(function(output){
if (output.result == 'success'){
var name = $('#fname').val();
show_message("User '" + name + "' added successfully.", 'success' );
}, true);
} else{
show_message('Add request failed','error');
};
});
});
fun.php
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'){
/ / Add user
$query = "INSERT INTO oops ";
if (isset($_GET['name'])) { $query .= "name = '" . mysqli_real_escape_string($db_connection, $_GET['name']) . "', "; }
if (isset($_GET['lname'])) { $query .= "lname = '" . mysqli_real_escape_string($db_connection, $_GET['lname']) . "', "; }
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['gender'])) { $query .= "gender = '" . mysqli_real_escape_string($db_connection, $_GET['gender']) . "', "; }
if (isset($_GET['email'])) { $query .= "email = '" . mysqli_real_escape_string($db_connection, $_GET['email']) . "', "; }
if (isset($_GET['mobile'])) { $query .= "mobile = '" . mysqli_real_escape_string($db_connection, $_GET['mobile']) . "', "; }
if (isset($_GET['address'])) { $query .= "address = '" . mysqli_real_escape_string($db_connection, $_GET['address']) . "'"; }
$query = mysqli_query($db_connection, $query);
if (!$query){
$result = 'error';
$message = 'query error';
} else {
$result = 'success';
$message = 'query 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;
?>
Am I missing something please help if you found any fault in my code.
because you are using post method in your form:
<form method="POST" id="add_user" name='reg' >
and trying to receive params via get:
isset($_GET['name'])
just use post method everywhere
and also in jQuery you need to set:
type: "POST"
I am not able to post data to MySql database. I am running the project on chrome browser(windows7). Here I can see the params but they are not sent to the database table. What actually is the problem with my code?
My php code is:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
$postdata = file_get_contents("php://input");
$email = $postdata->email;
$password = $postdata->password;
$username = $postdata->username;
$con = mysqli_connect("localhost","root",'') or die ("Could not connect: " . mysql_error());;
mysqli_select_db($con, 'db_lastLog');
$qry_em = 'select count(*) as cnt from users where email ="' . $email . '"';
$qry_res = mysqli_query($con, $qry_em);
$res = mysqli_fetch_assoc($qry_res);
if($res['cnt']==0){
$qry = 'INSERT INTO users (name,pass,email) values ("' . $username . '","' . $password . '","' . $email . '")';
$qry_res = mysqli_query($con, $qry);
if ($qry_res) {
echo "1";
} else {
echo "2";;
}
}
else
{
echo "0";
}
?>
My controller code is:
.controller('SignupCtrl', function($scope, $http) {
$scope.signup = function (userdata) {
var request = $http({
method: "POST",
url: "http://localhost/lastLog.php",
crossDomain : true,
data: {
username : userdata.username,
password : userdata.password,
email : userdata.email
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
/* Successful HTTP post request or not */
request.success(function(data) {
if(data == "1"){
$scope.responseMessage = "Successfully Created Account";
}
if(data == "2"){
$scope.responseMessage = "Cannot Create Account";
}
else if(data == "0") {
$scope.responseMessage = "Email Already Exist"
}
});
}
})
My html code is:
<ion-pane>
<ion-header-bar class="bar-positive">
<h2 class="title">SignUp</h2>
</ion-header-bar>
<ion-view view-title="SignUp" name="signup-view">
<ion-content class="has-header" ng-controller="SignupCtrl">
<div class="list list-inset">
<label class="item item-input">
<input class="form-control" type="text" ng-model="userdata.username" placeholder="Enter Username">
</label>
<label class="item item-input">
<input type="text" ng-model="userdata.email" placeholder="Enter Your Email">
</label>
<label class="item item-input">
<input class="form-control" type="password" ng-model="userdata.password" placeholder="Enter Your Password">
</label>
<button class="button button-block button-positive" ng-click="signup(userdata)">SignUp</button><br>
<span>{{responseMessage}}</span>
</div>
</ion-content>
</ion-view>
</ion-pane>
I'm trying to figure out why my data is not being collected by my PHP files.
This is my index.html
<!DOCTYPE html>
<html lang="en" ng-app="gemStore">
<head>
<meta http-equiv='Content-Type':'application/x-www-form-urlencoded; charset=UTF-8' />
<title>Angular</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div ng-controller="custController">
<form>
First Name: <input type="text" ng-model="firstname"><br>
Last Name: <input type="text" ng-model="lastname"><br>
Choose Username: <input type="text" ng-model="username"><br>
Choose Password: <input type="text" ng-model="password"><br>
Address 1: <input type="text" ng-model="address1"><br>
Address 2: <input type="text" ng-model="address2"><br>
City: <input type="text" ng-model="city"><br>
State: <input type="text" ng-model="state"><br>
Zip: <input type="number" ng-model="zip"><br>
<input type="button" value="Submit" ng-click="insertdata()"><br>
</form>
</div>
<script src="js/angular.min.js"></script>
<script src="js/script.js"></script>
<script src="js/products.js"></script>
</body>
</html>
This is my script.js
(function(){
var app = angular.module('gemStore', ['store-products']);
app.controller('StoreController', ['$http', function($http){
var store = this;
store.products = [];
$http.get('/store-products.json').success(function(data){
store.products = data;
});
}]);
app.controller('custController', function($scope,$http){
$scope.insertdata = function(){
$http.post('insert.php',{'firstname':$scope.firstname,'lastname':$scope.lastname,'address1':$scope.address1,'address2':$scope.address2, 'city':$scope.city,'state':$scope.state,'zip':$scope.zip,'username':$scope.username,'password':$scope.password})
.success(function(data,status,headers,config){
console.log('data inserted successfully. First Name: ' + $scope.firstname);
});
}
});
})();
And finally my PHP file
<?php
$data = json_decode(file_get_contents("php://input"));
$firstname = mysql_real_escape_string($data->firstname);
$lastname = mysql_real_escape_string($data->lastname);
$username = mysql_real_escape_string($data->username);
$address1 = mysql_real_escape_string($data->address1);
$address2 = mysql_real_escape_string($data->address2);
$city = mysql_real_escape_string($data->city);
$state = mysql_real_escape_string($data->state);
$zip = mysql_real_escape_string($data->zip);
$password = mysql_real_escape_string($data->password);
mysql_connect("localhost","root","");
mysql_select_db("mydatabase");
mysql_query("INSERT INTO users (`firstname`, `lastname`, `username`, `password`, `address1`, `address2`, `city`, `state`, `zip`)VALUES('" . $firstname . "','" . $lastname . "','" . $username . "','" . $password . "','" . $address1 . "','" . $address2 . "','" . $city . "','" . $state . "','" . $zip . "')");
?>
I am thinking it has something to do with headers, but I'm not sure where I should add it or what needs to be changed. Any help would be appreciated. Thanks.
Also, I am using angular 1.3.16, but I doubt that makes a difference.
try this in your insertdata function.
$scope.insertdata = function(){
var data = {'firstname':$scope.firstname,'lastname':$scope.lastname,'address1':$scope.address1,'address2':$scope.address2, 'city':$scope.city,'state':$scope.state,'zip':$scope.zip,'username':$scope.username,'password':$scope.password};
$http({
url:'insert.php',
method: 'post',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data :data
}).success(function(data,status,headers,config){
console.log('data inserted successfully. First Name: ' + $scope.firstname);
});
}
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