ajax post to php file - php

I'm not able to get this to work - this is my first attempt at this. I do realize that the information has not been serialized, I just wanted to get this to work first.
Any ideas what I'm doing wrong here? It's not saving the information to the mysql database.
index.html :
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="purchase.js"></script>
</head>
<form name="paypal_form" onsubmit="return validate_form();" method="post">
<input type="text" size="25" name="os0" value="">
<input type="text" size="25" name="os1" value="">
<input type="hidden" name="item_name" value="product">
<input type="image" src="images/paypal.gif" name="submit">
</form>
payment.js :
function validate_form()
{
// code to validate form data
// ....
valid = true;
var regcode = document.paypal_form.os0.value;
var email = document.paypal_form.os1.value;
var product = document.paypal_form.item_name.value;
var dataString = 'regcode=' + regcode + '&email=' + email + '&product=' + product;
$.ajax({
url: "/process.php",
type: "POST",
data: dataString,
success: function()
{
alert("Order Submitted");
}
});
return valid;
}
process.php :
$dbhost = "localhost";
$dbuser = "dbuser";
$dbpass = "dbpass";
$dbname = "dbname";
$date = date('Y/m/d');
$RegCode = $_POST['regcode'];
$Email = $_POST['email'];
$Product = $_POST['product'];
mysql_connect($dbhost, $dbuser, $dbpass);
// Store the transaction ID in the database
mysql_query("INSERT into payment (date, regcode, sentemail, status) values ('$date', '$RegCode', '$Email', '$Product')");

if process.php is in the same folder make it url:'process.php' and also
mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db("dbname", $con);

Add below attribute in form tag and try
action="javascript:void(0);"

Related

PHP/MYSQL Log-in update troubles

I have been working on this Login script for awhile and everything works, except this update function. I have tried changing variable name and everything else. On UpdateUser.php, the code works if I insert variables instead of the $[POST] variables. I am at a loss. Any help would be greatly appreciated. Sorry for the messy code, this is a class assignment, so I wasn't worried about password security at the moment.
This is index4.php
<form id="form" action="index4.php" method="post">
<h2>Update Your Login</h2>
UserName:<br>
<input type="text" id="useuserName" required />
<br>
Password:<br>
<input type="text" id="usepassWord" required />
<br>
First Name:<br>
<input type="text" id="usefirstName" required />
<br>
Last Name:<br>
<input type="text" id="uselastName" required />
<br>
<input id="updateuser" type ="submit" />
</form>
<script>
$('#updateuser').click(function() {
var useID = $_SESSION["id"];
var useuserName = $("#useuserName").val();
var usepassWord = $("#usepassWord").val();
var usefirstName = $("#usefirstName").val();
var uselastName = $("#uselastName").val();
var usePermissions = $_SESSION["Permissions"];
$.ajax({
type : 'POST',
url : '',
data :{action:'updateuser', useID:useID, useuserName:useuserName, uselastName:uselastName, usePermissions:usePermissions},
error: function (html) {
alert( "What the duck" );
},
});
});
</script>
This is the UpdateUser.php file
<?php
//Update
if($_POST['action'] == 'updateuser'){
//Set Variables
$servername = "localhost";
$username = "root";
$password = "";
$db = "userdb";
//Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection: Failed! " . $conn->connect_error);
}
//Actual Code
$useID = $_POST['useID'];
$useuserName = $_POST['useuserName'];
$usepassWord = $_POST['usePassword'];
$usefirstName = $_POST['usefirstName'];
$uselastName = $_POST['uselastName'];
$usePermissions = $_POST['usePermissions'];
//Create Query
$sql = "UPDATE users SET userName = '$useuserName', Pass = '$usepassWord', firstName = '$usefirstName', lastname = '$uselastName', Permissions = '$usePermissions' WHERE id =" . $useID ."";
//Did it work Check
if ($conn->query($sql) === TRUE) {
echo "Cool";
} else {
echo "What " . $conn->error;
}
//Close Out
$conn->close();
}
?>

How possibly HTML files to retrieve database from MYSQL (using php on the server)?

I want to create form in HTML files. let say it calls index.html ( client will see this page), and the HTML will be included some ajax codes where it links to php (server connect to Mysql)
So that client can do (insert delete edit) to database by inserting form in the index.html. How possibly to do that?. Please give me a simple code so that I can learn. Thank you so much. I found that PHP can link to others php to retrieve the data. But I would love to use HTML instead ,to link to php on the server.
Thank you so much.
edited code
enter code here (this is index.html)
<html>
<head>
<title>Submit Form Using AJAX PHP and javascript</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="css/style.css" />
<script>
function myFunction() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var contact = document.getElementById("contact").value;
var dataString = 'name1=' + name + '&email1=' + email + '&password1=' + password + '&contact1=' + contact;
if (name == '' || email == '' || password == '' || contact == '')
{
alert("Please Fill All Fields");
}
else
{
//AJAX code to submit form.
$.ajax({
type: "POST",
url: "https://../test2.php",
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
}
return false;
}</script>
</head>
<body>
<div id="mainform">
<div class="innerdiv">
<h2>Submit Form</h2>
//div starts here
<form id="form">
<h3>Fill Your Information!</h3>
<div>
<label>Name :</label>
<br/>
<input type="text" id="name" /><br/>
<br/>
<label>Email :</label>
<br/>
<input type="text" id="email"/><br/>
<br/>
<label>Password :</label>
<br/>
<input type="password" id="password" /><br/>
<br/>
<label>Contact No :</label>
<br/>
<input type="text" id="contact" /><br/>
<br/>
<input type="button" id="submit" onclick="myFunction()" value="Submit"/>
</div>
</form>
<div id="clear"></div>
</div>
</body>
</html>
and this is the php.
//Fetching Values from URL
$name2 = $_POST['name1'];
$email2 = $_POST['email1'];
$password2 = $_POST['password1'];
$contact2 = $_POST['contact1'];
$servername = "localhost";
$username = "user";
$password = "userpwd";
$dbname = "dbname";
// Establishing connection with server..
$dbc = mysqli_connect($servername, $username, $password , $dbname)
or die('Error connecting to MySQL server.');
// Selecting Database
if (isset($_POST['name1'])) {
//Insert query
$query = mysqli_query("insert into form_element(name, email, password, contact) values ('$name2', '$email2', '$password2','$contact2')");
echo "Form Submitted succesfully";
}
//connection closed
mysqli_close($dbc);
?>
I don't get it work.
I don't have all the div's you had in there before, but you should be able to add them!
This should work once you put in the right username, password and database name in connection.php
If this doesn't work or isn't what you wanted, please let me know!
This is also up and running at http://emmetstudios.com/form, if you want to see it in operation.
Here's the code, (put it all in the same folder, different files):
connection.php:
<?php
function Connect()
{
$dbhost = "localhost";
$dbuser = "yourusername";
$dbpass = "yourpassword";
$dbname = "yourdatabasename";
// Create connection
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname) or die($conn->connect_error);
return $conn;
}
?>
success.php:
<?php
require 'connection.php';
$conn = Connect();
$name = $conn->real_escape_string($_POST['name']);
$email = $conn->real_escape_string($_POST['email']);
$password = $conn->real_escape_string($_POST['password']);
$contact = $conn->real_escape_string($_POST['contact']);
$query = "INSERT into form_element (name,email,password,contact) VALUES('" . $name . "','" . $email . "','" . $password . "','" . $contact . "')";
$success = $conn->query($query);
if (!$success) {
die("Couldn't enter data: ".$conn->error);
}
echo "Successful!";
$conn->close();
?>
index.php:
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
<form id="form" action="success" method="post" onsubmit="return validateForm()" name="upload">
Name:<br>
<input type="text" name="name"> <br><br>
Email:<br>
<input type="text" name="email"> <br><br>
Password:<br>
<input type="password" name="password"> <br><br>
Phone Number:<br>
<input type="text" name="contact"> <br><br>
<input id="submit" type="submit" value="Submit">
</form>
<script>
function validateForm() {
var name = document.forms["form"]["name"].value;
if (name == "") {
alert("Name must be filled out");
return false;
}
var email = document.forms["form"]["email"].value;
if (email == "") {
alert("Email must be filled out");
return false;
}
var password = document.forms["form"]["password"].value;
if (password == "") {
alert("Password must be filled out");
return false;
}
var contact = document.forms["form"]["contact"].value;
if (contact == "") {
alert("contact must be filled out");
return false;
}
}
</script>
</body>
</html>

Fetch and insert data into mysql using angularjs

I am unable to connect insert the date into sql server using angularjs & php.
I want to know how to insert data in sql and fetch the data from db.
<body>
<div ng-app="myapp" ng-controller="empcontroller">
<form>
Employe No. <input type="text" ng-model="emp_no" /><br/>
First Name. <input type="text" ng-model="first_name" /><br/>
Last Name. <input type="text" ng-model="last_name" /><br/>
Department. <input type="text" ng-model="dept_name" /><br/>
<input type="button" value="submit" ng-click="insertdata()"/> <br/>
</form>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular-route.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script type="text/javascript">
var app = angular.module('myapp',[]);
app.controller('empcontroller', function($scope, $http){
$scope.insertdata=function(){
$http.post("insert.php",{'emp_no':$scope.emp_no,'first_name':$scope.first_name,'last_name':$scope.last_name,'dept_name':$scope.dept_name})
.success(function(data,status,headers,config){
console.log("data insert succesfully");
});
}
});
</script>
</body>
PHP CODE:
$data = json_decode(file_get_contents("php://input"));
$empno = mysql_real_escape_string($data->emp_no);
$fname = mysql_real_escape_string($data->first_name);
$lname = mysql_real_escape_string($data->last_name);
$dept = mysql_real_escape_string($data->dept_name);
$con = mysql_connect("localhost", "root", "root");
mysql_select_db("company", $con);
mysql_query("INSERT INTO employee('emp_no', 'first_name', 'last_name', 'dept_name')VALUES('".$empno."','".$fname."','".$lname."','".$dept."')");
Here You go Try this
HTML
<div ng-app="myapp" ng-controller="empcontroller">
<form>
Employe No. <input type="text" ng-model="emp_no" /><br/>
First Name. <input type="text" ng-model="first_name" /><br/>
Last Name. <input type="text" ng-model="last_name" /><br/>
Department. <input type="text" ng-model="dept_name" /><br/>
<button ng-click="postData()">Submit</button><br>
</form>
</div>
CONTROLLER:
app.controller('empcontroller', function ($scope, $http) {
/*
* This method will be called on click event of button.
*/
$scope.postData = function () {
var request = $http({
method: "post",
url: window.location.href + "insert.php",
data: {
emp_no: $scope.emp_no,
first_name: $scope.first_name,
last_name: $scope.last_name,
dept_name: $scope.dept_name,
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
}
});
PHP CODE:
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$emp_no = $request->emp_no;
$first_name = $request->first_name;
$last_name = $request->last_name;
$dept_name = $request->dept_name;
$servername = "localhost";
$username = "root";
$password = "root"; //Your User Password
$dbname = "myDB"; //Your Database Name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO employee (emp_no, first_name, last_name, dept_name)
VALUES ($emp_no, $first_name, $last_name , $dept_name)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Three problems with your code:
When executing $scope functions with ng-click, best practice is to pass in the variables as you use them.
Since your PHP controller is expecting JSON, you should form a JSON object and indicate it in the headers.
.success() is being deprecated. You should use the promise .then() instead.
HTML:
<!-- need to pass model in the ng-click function -->
<input type="button" value="submit" ng-click="insertdata(emp_no, first_name, last_name, dept_name)"/>
Controller:
$scope.insertata = function(empNo, firstName, lastName, deptName) {
//make json payload object
var payload = {
emp_no: empNo,
first_name: firstName,
last_name: lastName,
dept_name: deptName
};
//pass to API
$http.post('insert.php', payload, {
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}).then(function(data, status, headers, config) {
//success
}, function(data, status, headers, config) {
//an error occurred
});
}
well, using the code of KKKKKKKK now you need a php code.
To retrieve information from a json file posted using post to php you should do something like this:
$json = file_get_contents('php://input');
$obj = json_decode($json); // this will retrieve the json.
And now manipulate as you want.

Need help to compare and add value to DB with PHP, $_POST not working..?

I am trying to compare the text that is written in the input field with the "UserID" in the database to know where to add 1 pts on the button click. Adding a new user to the DB is not a problem, but then when I want to "UPDATE" the DB nothing happends, it seems like I cant get the $_POST['UserID']; to work in my addPts.php ?
Here is an example from my code:
blabla.html
<html>
<head>
<script type="text/javascript" src="blabla.js"></script>
</head>
<body>
<nav>
<li>
<form action="addToDB.php" method="post" target="hidden-form">
<input type="text" id="UserID" name="UserID" placeholder="Your ID Here" style="width:290px"/>
<input type="submit" id="submit" name="submit" value="Add to DB"/>
</form>
</li>
</nav>
<section id="mainframe">
<iframe src="blabla2.html" name="myIFRAME"></iframe>
</section>
<iframe style="display:none" name="hidden-form"></iframe>
<button><a id="theLink" href="http://www.stackoverflow.com" target="myIFRAME">Press me for 1pts</a></button>
</body>
</html>
blabla2.html
<html>
<head>
</head>
<body>
Start message in iFrame
</body>
</html>
blabla.js
$(function (){
$('#theLink').click(function(){
var request = $.ajax({
type: "POST",
url: "../bla/addPts.php"
});
request.done(function( msg ) {
alert('1 Point added');
return;
});
request.fail(function() {
alert( "Request failed.. " );
});
});
});
addToDB.php
<?php
$localhost = "localhost";
$dbuser = "blabla";
$dbpass = "blablabla";
$dbname = "bla";
$connect = mysql_connect($localhost, $dbuser, $dbpass);
mysql_select_db("$dbname", $connect);
$UserID = $_POST['UserID'];
$checkIDLenght = strlen($UserID);
$messageNewMember = "WELCOME! New User!";
$messageOldMember = "Welcome back!";
$insert = 'INSERT into membersBLA(UserID) VALUES("'.$UserID.'")';
$query = mysql_query("SELECT UserID FROM membersBLA WHERE UserID='".$UserID."'");
if (mysql_num_rows($query) != 0)
{
echo "<script type='text/javascript'>alert('$messageOldMember');</script>";
}
else {
mysql_query($insert);
echo "<script type='text/javascript'>alert('$messageNewMember');</script>";
}
?>
addPts.php
<?php
$localhost = "localhost";
$dbuser = "blabla";
$dbpass = "blablabla";
$dbname = "bla";
$connect = mysql_connect($localhost, $dbuser, $dbpass);
mysql_select_db("$dbname", $connect);
$user = $_POST['UserID'];
mysql_query("UPDATE membersBLA SET UserPts = UserPts + 1 WHERE UserID='".$user."'");
?>
It works to "UPDATE" the DB if I type in the " WHERE UserID='Name'"); " manually, then it update the "UserPts" for the name I wrote.. but Getting the typed name from the input to compare does not seems to work?
Try this
//Retrieve value of userid and use data paremeter of jQuery.ajax()
$(function (){
$('#theLink').click(function(){
var UserID=jQuery("#UserID").val();
var request = $.ajax({
type: "POST",
url: "../bla/addPts.php",
data:{'UserID': UserID},
});
request.done(function( msg ) {
alert('1 Point added');
return;
});
request.fail(function() {
alert( "Request failed.. " );
});
});
});

How do i include ajax in PHP coding to display data in the same page

I want to display data retrieved from the table in the same page. I know if i use ajax, work becomes easier. But how do i do it? I don't know anything about ajax. My current program is combined with html and php. The program is below. All i want is, when i click the button, the requested action and the data must be displayed in the same page.
<!DOCTYPE html>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'DB';
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_error())
{
die("couldn't connect" . $conn->connect_error());
}
$id = $_POST['Id'];
$name = $_POST['Name'];
$blood = $_POST['BloodGroup'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST['insert'])){
$insert = "Insert into ins(Id, name, BloodGroup) values ('$id','$name', '$blood')" ;
if($conn->query($insert) === TRUE) {
echo ("Input data entered successfully");
} else {
echo ("Input data failed to be entered" . $conn->error());
}
$conn->close();
} elseif(isset($_POST['update'])) {
$update = "update ins set Name='".$name."', BloodGroup='".$blood."' where Id='".$id."'";
mysql_query($update);
if($conn->query($update) === TRUE) {
echo ("Data updated successfully");
} else {
echo ("Data cant be updated" . $conn->error());
}
$conn->close();
} elseif(isset($_POST['delete'])) {
$id = $_POST['Id'];
$delete = "delete from ins where Id='".$id."'";
if($conn->query($delete) === TRUE) {
echo ("Data deleted successfully");
} else {
echo ("Data cant be updated" . $conn->error());
}
$conn->close();
}
else {
$id = $_POST['Id'];
$retrieve = "SELECT * FROM ins WHERE Id = ".$id;
if ($result=mysqli_query($conn,$retrieve))
{
while ($row=mysqli_fetch_row($result))
{
echo '<table>
<tr>
<td>Id</td>
<td>Name</td>
<td>Blood Group</td>
</tr>
<tr>
<td>'.$row[0].'</td>
<td>'.$row[1].'</td>
<td>'.$row[2].'</td>
</tr>
</table>';
//$row[0],$row[1],$row[2]';
}
mysqli_free_result($result);
}}}
$conn->close();
?>
<h2>SELECT THE OPERATION YOU WANT TO PERFORM<h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Id: <input type="text" name="Id" />
Name: <Input type="text" name="Name" />
BloodGroup: <input type="text" name="BloodGroup" /><br /><br />
<input type="submit" name="insert" value="Insert" />
<input type="submit" name="update" value="Update" />
<input type="submit" name="delete" value="Delete" />
<input type="submit" name="retrieve" value="retrieve" />
</form>
</body>
</html>
$.ajax({
method: "POST",
url: "{php file url}",
data: { name: "John", location: "Boston" } // data list need to sent
})
.done(function( msg ) {
$("#div1").html(result); //#div1 is container element where you want to show output of ajax
});
For more details refer
http://api.jquery.com/jquery.ajax/
Just start learning jquery and jquery ajax
http://api.jquery.com/jquery.ajax/
you will find something like this:
$.ajax({
type: "POST",
url: '', //write your php file url from where you want to get data
data:{}, //to post data like data:{customerName:'xyz'},
success: function(res){ //data returned from your php file
console.log(res); //use data as per your need
}
});

Categories