I am trying to make a functionality where I am sending Name and Age using ajax. The same is gathered by PHP and then stored to DB. I think I am doing it correctly but data not saved in database. Can someone help me out?
HTML
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('button').click(function(){
$.ajax({
url: 'addData.php',
type: 'POST',
dataType: "json",
data: {
name: $('#name').val(),
age: $('#age').val(),
}
})
});
});
</script>
</head>
<body>
<input id="name" type="text" />
<input id="age" type="text" />
<button>Click</button>
</body>
</html>
PHP
<?php
//Parameters for connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test1";
//Reading json
$data_back = json_decode(file_get_contents('php://input'));
// set json string to php variables
$name = $data_back->{"name"};
$age = $data_back->{"age"};
// Create Connection
$conn = new mysqli($servername, $username, $password, $dbname);
//Creating Query
$sql = "INSERT INTO table1 (name, age) VALUES ($name, $age)";
//Running Query
$conn->query($sql);
//Closing Connection
$conn->close();
?>
ERROR
Even though you're sending data with jquery as json, php is still recieving it as a $_POST object. So, this should work:
$name = $_POST['name'];
$age = $_POST['age'];
I think your object $data_back is empty because of errors in parsing of data by function json_decode. You should try to use var_dump($data_back); exit; after json_decode or more advanced methods such as debugging.
I believe this is the proper way to access data post json_decode
$name = $data_back->name;
I also recommend looking into prepared statements for the database query execution...Ok, I HIGHLY recommend you look into it.
Edit: Maybe try this as well: Replace file_get_contents() with $_POST;
Related
I have two php files, file A and file B that get data from the same database. File A displays the data in a paragraph on the site while File B is used by AJAX to display data in a graph created with graph.js. Both files do their job, except.
In both files I have a variable called $employeeNumber which is the name of an input field in a form used by the user to input whichever employee number they would like to view the data of. File A allows me to use
$employeeNumber = $_POST["employeeNumber"]; to get the input and displays data accurately but File B won't allow me to use $_POST[], $_REQUEST[], or $_GET[]. Instead it forces me to hardcode the unique number. This is not desired.
File B is meant to get the input entered into the form, and update the graph with the data relating to the employee number entered.
I used echo $row["empnumber"]; for File A to display the data and for File B I used print json_encode($data); Could this be where I went wrong?
File B (Doesn't update graph unless I hardcode employeeNum)
<?php
header('Content-Type: application/json');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";
//BELOW IS WHERE THE ISSUE LIES.
//WHEN I HARDCODE THE UNIQUE NUMBER LIKE THIS, THE GRAPH UPDATES ACCORDINGLY. WITH ACCURATE DATA FROM THE EMPLOYEE THAT THE UNIQUE NUMBER BELONGS TO.
$employeeNum = 8020;
//THIS (BELOW) I ANTICIPATED WOULD GET THE EMPLOYEE NUMBER FROM THE USERS INPUT IN THE FORM WHICH I HAVE NOW INCLUDED BUT IT PRODUCES AN ERROR.
$employeeNum = $_POST["employeeNum"]; //this is line 9
//HERE IS THE ERROR WHEN I OPEN THE Graphdata.php FILE
<br />
<b>Notice</b>: Undefined index: employeeNum in <b>C:\wamp64\www\Graphdata.php</b> on line <b>9</b><br />
<br />
<b>Warning</b>: Invalid argument supplied for foreach() in <b>C:\wamp64\www\Graphdata.php</b> on line <b>22</b><br />
<br />
<b>Fatal error</b>: Uncaught Error: Call to a member function close() on bool in C:\wamp64\www\Graphdata.php:26
Stack trace:
#0 {main}
thrown in <b>C:\wamp64\www\Graphdata.php</b> on line <b>26</b><br />
//Connect to database
$dbconnect = new mysqli($servername, $username, $password, $dbname);
//If failed to connect
if(mysqli_connect_error()){
die("Database connection error".mysqli_connect_error());
}
//Create query
$sql = "SELECT Mathematics, English, Afrikaans, Geography, Physics, History, Life_Orientation FROM studentresults WHERE employeeNumber = $employeeNum";
//Run query
$result = $dbconnect->query($sql);
//Produce result
$data = array();
foreach ($result as $row){ //THIS IS LINE 22
$data[] = $row;
}
$result -> close();
$dbconnect -> close();
//Print the result
print json_encode($data);
?>
File A (Works fine)
<?php
//connecting to database
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";
$employeeNum = $_POST["employeeNum"];
$connect = new mysqli($servername, $username, $password, $dbname);
//checking connection
if (mysqli_connect_error()) {
die ("Database connection failed: ". mysqli_connect_error());
}
// Query the database
$sql = "SELECT Salary FROM myEmployees WHERE employeeNumber = $employeeNum";
$result = $connect->query($sql);
//print out result
while($row = mysqli_fetch_array($result)) {
echo $row["English"];
}
$result -> close();
?>
Here's the AJAX code making the request
$.ajax({
//Graphdata.php is the name of FILE B
url: "http://localhost/Graphdata.php",
type: "GET",
success : function(data){
console.log(data);
var Salary = [];
var timeWorked = [];
var Age = [];
var userid = [];
for(var i in data){
userid.push("UserID " + data[i].userid);
Salary.push(data[i].Salary);
Age.push(data[i].Age);
timeWorked.push(data[i].timeWorked);
}
//Create the graph
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
Here is the form code.
<form action="Graphdata.php" method="post">
<p class="name">Username</p>
<input class="inp1" type="text" name="name">
<p class="password">Password</p>
<input class="inp2" type="password" name="email">
<p class="employeeid">Employee ID</p>
<input id = "employeeNum" class="inp3" type="int" name="employeeNum">
The problem is that when you call via AJAX, you are not passing any data along to the back end.
Further, when you use method=GET, the $_POST array will be empty.
Change your method to POST, and include the data like this:
$.ajax({
method: "POST",
url: "http://localhost/Graphdata.php",
data: {employeeNum: someValue}
...
})
Although I found other topics reporting the same issue, none of them helped me.
I'm learning AngularJS and I tried to insert data into a MySQL database. I have a really simple HTML file where the user can provide a name and age, and then click in a Submit button which would put this data into the MySQL database.
Since it's just for learning purposes, I named the database and the table "test".
I am using PHP as the server language.
I have:
- An index.html file for the view
- A script.js file where I use AngularJS HTTP POST method to insert data into the MySQL database
- A config.php file where I deal with the connection with the server and the insertion of data into the database.
Also, my table consists of only 3 columns: an ID (unique, auto-incremented), a "name"(text) and an "age"(int).
The code for each file is here:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>AngularJS-PHP-MySQL</title>
<!-- AngularJS CDN-->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<!-- script.js with implementation of Module and Controller -->
<script src="script.js" ></script>
</head>
<body>
<div ng-app="myApp" ng-controller="formCtrl">
<form id="myForm" action="" method="post">
<input type="text" name="name" id="name" value="" placeholder="Name" ng-model="nameModel">
<input type="text" name="age" id="age" value="" placeholder="Age" ng-model="ageModel">
<input type="button" name="sub" id="sub" value="Submit" ng-click="insertData()">
</form>
</div>
</body>
</html>
script.js
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope,$http){
$scope.insertData = function(){
$http.post("config.php",{'name': $scope.nameModel, 'age': $scope.ageModel})
.success(function(data, status, headers, config){
console.log("inserted Successfully");
});
}
});
config.php
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$Table_name = "test";
mysql_connect($servername, $username, $password);
mysql_select_db($Table_name) or die(mysql_error());
$name = $_POST['name'];
$age = $_POST['age'];
mysql_query("INSERT INTO $Table_name('name', 'age') VALUES('$name', '$age')");
?>
I get an alert that the POST method was successful but it did not insert the data into the table. I have no idea why and I don't find an answer online.
I found in another topic here that AngularJS and some server side languages like PHP have different ways to serialize and transmit the data. Like the post says, the problem lies with PHP being unable to understand AngularJS’s transmission natively.
To avoid that, I explicitly built the header on my inserData() function:
script.js
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope,$http){
$scope.insertData = function(){
var request = $http({
method: "post",
url: "config.php",
data: {
name: $scope.nameModel,
age: $scope.ageModel,
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
}
});
I also changed my config.php file into:
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "test";
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$name = $request->name;
$age = $request->age;
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO test(name, age) VALUES('$name', '$age')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Now they can transmit compatible data. I also assigned the connection to a variable and then used it to query my data.
The HTML remains the same. With these changes, everything here is working properly now.
I'm not sure if your PHP/MYSQL code is OK.
Could you try the following code?
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$Table_name = "test";
$connection = mysql_connect($servername, $username, $password);
mysql_select_db($Table_name, $connection) or die(mysql_error());
$name = $_POST['name'];
$age = $_POST['age'];
$sqlQuery = "INSERT INTO $Table_name('name', 'age') VALUES('$name', '$age')";
mysql_query($sqlQuery, $connection);
?>
Pretty new to php/mysql and jquery, and I'm having trouble getting my form data to upload to my mysql db. I've tried a few different approaches and done my research, but none of the suggestions I've found online are working for me, which is why I'm posting here. So here's my most recent failed approach:
in my index file:
<head>
...
<script type="text/javascript">
$(document).ready(function() {
// Announcement form AJAX submit
$('#announcementForm').submit(function() {
$.ajax({
url: 'ajax.php',
type: 'POST',
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
if (data.error) {
$('#error').css('display', 'block');
} else {
$('#note').show();
$('#error').hide();
$('#fields').hide();
}
}
});
return false;
});
});
</script>
</head>
<body>
...
<form class="dl_form" id="announcementForm" method="post">
<dl>
<dt>Announcement</dt>
<dd><textarea id="Announcement" sytle="width: 300px; height: 150px;" name="Announcement"></textarea></dd>
</dl>
<dl>
<dt>Announcement Type:</dt>
<dd><input type="radio" name="Type" value="schedule">Scheduling</input></dd>
<dd><input type="radio" name="Type" value="general">General</input></dd>
</dl>
<dl>
<dt></dt>
<dd><input type="submit" value="submit" /></dd>
</dl>
</form>
<div id="note">
<p>Announcement posted successfully!"</p>
</div>
<div id="error">You haven't completed all of the required fields</div>
And then in my ajax.php file I have (some lines have been replaced with "######" for security reasons):
<?php
//database credentials
$server = '######';
$username = '######';
$password = '######';
$database = '######';
$connect = mysql_connect($server, $username, $password ) or die(mysql_error.'error connecting to db');
//select database
mysql_select_db($database, $connect) or die(mysql_error.'error selecting db');
//$typeValue = $('input:radio[name=Type]:checked').val());
if (!empty($_POST)){
$Announcement = $_POST['Announcement'];
$Type = $_POST['Type'];
if (!empty($Announcement) && !empty($Type) )
{
//insert data into db
mysql_query("INSERT into announcements (AnnouncementID, Type, Announcement)
VALUES ('', '".$Type."', '".$Announcement."')") or die(mysql_error());
}else {
echo json_encode(array(
'error' => true,
'msg' => "You haven't completed all required fields!"
));
exit;
}
}
?>
Any help you guys can provide would be much appreciated.
Thanks
UPDATE IN RESPONSE TO Jay Blanchard:
I just ran the console in my browser. The only error I'm getting is:
SCRIPT1004: Expected ';'
in reference to the first line of my JS:
$function() {
...
UPDATE 2:
Just updated my code to reflect my most recent changes...before I could at least trigger the submit click even and the fields would empty, indicating that at least something was happening. With my new round of changes however, not even that triggers, so I'm still pretty stuck
In your php you've made a mistake with your echo statement its not jason_encode instead its json_encode.
Additionally
Also you Should remove AnnouncementID from your query if in database it is auto increment, because db will warn you for incorrect integer value for column AnnouncementID.
EDIT: In your php part in statement
mysql_query("INSERT into announcements (AnnouncementID, Type, Announcement)
VALUES ('', '".$Type."', '".$Announcement"')") or die(mysql_error());
You are forgetting a concatenation operator . after '".$Announcement which should be
mysql_query("INSERT into announcements (AnnouncementID, Type, Announcement)
VALUES ('', '".$Type."', '".$Announcement."')") or die(mysql_error());
and in your jquery instead of
$function() {
use
$(document).ready(function(){
I have the following scripts. The user will pass a numerical value e.g. 123 as a parameter in the URL, and the app will load/fetch that value from MySQL and show it in the textarea.
E.g., entering, "example.com/index.php?id=123" in the URL will pull the 123rd record from the database and show it in the textarea. Everything seems to be working, but I want to show the last row/id of the "source" table when the form is submitted. So, instead of showing "Saved!" in the pop-up, it should show something like "124" (or, the last updated row/number).
index.php:
<?php
include('connect-db.php');
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
$id = $_GET['id'];
$result = mysql_query("SELECT content FROM source WHERE id=$id") or die(mysqli_error());
$row = mysql_fetch_array($result);
if($row)
{
$submit_date = date("Ymd");
$content = $row['content'];
}
}
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#myform").submit( function () {
$.post(
'submit.php',
$(this).serialize(),
//
// show the last id here!
//
function(data){ alert("Saved!"); }
);
return false;
});
});
</script>
</head>
<body>
<div id="header" >
<form action="submit.php" method="post" id="myform">
<textarea id="editor" name="editor" id="editor"><?php echo $content; ?></textarea>
<br/>
<input type="submit" name="submit" value="Submit" id="submit"/>
</form>
</div>
</body>
</html>
submit.php:
<?php
include('connect-db.php');
$submit_date = date("Ymd");
$content = mysql_real_escape_string(htmlspecialchars($_POST['editor']));
$ip_address = $_SERVER['REMOTE_ADDR'];
if ($content != '') {
//
// Show the variable (last_id) value in the JavaScript above!
//
$last_id = mysql_insert_id();
mysql_query("INSERT INTO source (submit_date, ip, content) values('$submit_date','$ip_address','$content')") or die(mysql_error());
mysql_close($connection);
}
?>
connect-db:
<?php
$server = 'localhost';
$user = 'domdom';
$pass = 'password#123';
$db = 'domdom';
$connection = mysql_connect($server, $user, $pass) or die ("Could not connect to server ... \n" . mysql_error ());
mysql_select_db($db) or die ("Could not connect to database ... \n" . mysql_error ());
?>
Please note that I do not need any advice on PDO or MySQLi, that is not important at this time. However, any suggestions on improving the security/SQL query etc. are welcome. Thanks.
I will try to answer in 2 parts:
[1] PHP side: in the "isset($_GET['id'])" section, just return the content of the text area you want to fill out. Say, in your DB, 123 -> 'Friday'. Just return the String 'Friday'.
[2] Client side: Do not "submit" the form. Call a JS function, and in there, create an XmlHttpRequest, and send the request to the server as an AJAX request. When you get the return value, examine it and populate your HTML textarea.
If you think this method is suitable for you and you need more details, let me know. I do this in many of my sites.
I'm trying to use AJAX to send values to PHP file, which then updates mysql database on the server. But for some reason the values are not transferred to PHP file.
This is the JS I use:
function send_message()
{
var number = localStorage.getItem("number");
var message = prompt("Message:", "");
jQuery.ajax({ type: "POST",
url: serviceURL + "message.php",
data: 'number='+number+'&message='+message,
cache: false,
success: function(response)
{
alert("message sent");
}
});
}
And this is the message.php
<?php
include 'config.php';
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$number = $_GET['number'];
$message = $_GET['message'];
// query
$sql = "INSERT into table
SET condition=0, change=1, change_time=NOW(), recieve=999,
number=?, message=?";
$q = $conn->prepare($sql);
$q->execute(array($number, $message));
?>
Everything else is inserted to mysql except the number and message are NULL. What could be the reason for this?
You're posting data with AJAX using POST. In order to listen for those values in PHP you need to...
Replace:
$number = $_GET['number'];
$message = $_GET['message'];
With:
$number = $_POST['number'];
$message = $_POST['message'];
To make things simpler just use a convenience method like $.post or $.get for ajax calls in jQuery:
function send_message()
{
var number = localStorage.getItem("number");
var message = prompt("Message:", "");
$.post(serviceURL + "message.php", {'number' : number, 'message' : message},
function(response){
alert("message sent");
}
);
}
Then in your php:
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
//if you used $.get you will also have to use $_GET here
$number = $_POST['number'];
$message = $_POST['message'];
// query
$sql = "INSERT into table
SET condition=0, change=1, change_time=NOW(), recieve=999,
number=?, message=?";
$q = $conn->prepare($sql);
$q->execute(array($number, $message));
?>
I can see that you're using prepared statements in PDO. But you may also want to add:
Filter Vars and Filter Input for additional security.
Use $_POST instead of $_GET.
Also, you can try to use $_REQUEST global array to forget about it. It has all the data you have sent to script.
You may change your php file to;
<?php
include 'config.php';
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$number = $_POST['number'];
$message = $_POST['message'];
// query
$sql = "INSERT into table
SET condition=0, change=1, change_time=NOW(), recieve=999,
number=?, message=?";
$q = $conn->prepare($sql);
$q->execute(array($number, $message));
?>