I'm trying to save some data to a database without the use of an html form and was wondering if anyone could help me as I'm no expert in PHP. So far I have got:
JQuery
$('.summary').on('click', '#btn_save', function () {
var summary_weight = $('#summary_weight').text();
var summary_bmi = $('#summary_bmi').text();
var summary_consumed = $('#summary_consumed').text();
var summary_burned = $('#summary_burned').text();
var summary_total = $('#summary_total').text();
var user_id = $('#user_id').text();
//All values stored correctly
$.ajax({
type: "POST",
url: "save.php",
data: //Data to send,
success: function () {
$('.success_message').html("success");
}
});
});
There is no issue at the first stage as all my values are stored in the variables correctly. I just don't know in what format to send them across to save.php.
save.php
<?php
require_once 'dbconfig.php';
//Connects to database
if($_POST)
{
//Not sure what to post here
$current_date = date('Y-m-d');
try{
$stmt = $db_con->prepare("INSERT INTO entry(user_id, date, weight, bmi, calories_consumed, calories_burned, calorific_deficit) VALUES(:user, :date, :weight, :bmi, :consumed, :burned, :deficit)");
$stmt->bindParam(":user", $user_id);
$stmt->bindParam(":date", $current_date);
$stmt->bindParam(":weight", $summary_weight);
$stmt->bindParam(":bmi", $summary_bmi);
$stmt->bindParam(":consumed", $summary_consumed);
$stmt->bindParam(":burned", $summary_burned);
$stmt->bindParam(":deficit", $summary_total);
if($stmt->execute())
{
echo "Successfully Added";
}
else{
echo "Query Problem";
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
I'm not sure how to post this data to save.php and then how to process it to be sent to the database. I've also added a variable of current_date to send the current date to a field in the database.
Can anyone help me and fill in the blanks? Or maybe I'm going about this the wrong way?
Send your data in an object, like so:
// Declare data as an empty object
var data = {};
// Assemble the properties of the data object
data.summary_weight = $('#summary_weight').text();
data.summary_bmi = $('#summary_bmi').text();
data.summary_consumed = $('#summary_consumed').text();
data.summary_burned = $('#summary_burned').text();
data.summary_total = $('#summary_total').text();
data.user_id = $('#user_id').text();
$.ajax({
type: "POST",
url: "save.php",
// pass the data object in to the data property here
data: data,
success: function () {
$('.success_message').html("success");
}
});
Then, on the server side, you can access directly via $_POST superglobal:
$summary_weight = $_POST['summary_weight'];
$summary_bmi = $_POST['summary_bmi'];
// etc...
You can send all this data in the data parameter as given below:
$('.summary').on('click', '#btn_save', function () {
var summary_weight = $('#summary_weight').text();
var summary_bmi = $('#summary_bmi').text();
var summary_consumed = $('#summary_consumed').text();
var summary_burned = $('#summary_burned').text();
var summary_total = $('#summary_total').text();
var user_id = $('#user_id').text();
//All values stored correctly
$.ajax({
type: "POST",
url: "save.php",
data: {summary_weight: summary_weight, summary_bmi:summary_bmi, summary_consumed:summary_consumed, summary_burned: summary_burned, summary_total:summary_total, user_id:user_id },
success: function () {
$('.success_message').html("success");
}
});
});
And the, process it in save.php like this
$summary_weight = $_POST['summary_weight'];
and use it in the query to save it in database.
Related
I've been googling for a way to do this but everything I have found doesn't help me.
I'm not sure how to post all the below variables, If I select only one of them it'll post just fine as well as putting it into the correct database column.
any help would be much appreciated.
function submit() {
var mm10 = $('#10MM'),
mm16 = $('#16MM'),
mm7 = $('#7MM'),
mm2 = $('#2MM'),
fines = $('#Fines'),
bark = $('#Bark'),
cqi = $('#CQI');
$.ajax({
type: "POST",
url: "classes/Post/ChipSubmit.php",
data: ,
success: function(){
$("#successMessage").show();
}
});
};
You can do it in two ways. One using arrays, or two using objects:
function submit() {
var mm10 = $('#10MM').val(),
mm16 = $('#16MM').val(),
mm7 = $('#7MM').val(),
mm2 = $('#2MM').val(),
fines = $('#Fines').val(),
bark = $('#Bark').val(),
cqi = $('#CQI').val();
$.ajax({
type: "POST",
url: "classes/Post/ChipSubmit.php",
data: [mm10, mm16, mm7, mm2, fines, bark, cqi],
success: function() {
$("#successMessage").show();
}
});
} // Also you don't need a semicolon here.
Also you don't need a semicolon at the end of the function.
Using arrays is easier, if you want more precision, use objects:
function submit() {
var mm10 = $('#10MM').val(),
mm16 = $('#16MM').val(),
mm7 = $('#7MM').val(),
mm2 = $('#2MM').val(),
fines = $('#Fines').val(),
bark = $('#Bark').val(),
cqi = $('#CQI').val();
$.ajax({
type: "POST",
url: "classes/Post/ChipSubmit.php",
data: {
"mm10": mm10,
"mm16": mm16,
"mm7": mm7,
"mm2": mm2,
"fines": fines,
"bark": bark,
"cqi": cqi
},
success: function() {
$("#successMessage").show();
}
});
} // Also you don't need a semicolon here.
And in the server side, you can get them through the $_POST super-global. Use var_dump($_POST) to find out what has it got.
Kind of like Praveen Kumar suggested, you can create an object. One thing I was curious about, it looks like you're passing jQuery objects as your data? If that's the case, $_POST is going to say something like [object][Object] or, for me it throws TypeError and breaks everything.
var form_data = {};
form_data.mm10 = $('#10MM').val(); // Input from a form
form_data.mm16 = $('#16MM').val(); // Input from a form
form_data.mm7 = $('#7MM').val(); // Input from a form
form_data.mm2 = $('#2MM').text(); // Text from a div
form_data.fines = $('#Fines').text();
form_data.bark = $('#Bark').text();
form_data.cqi = $('#CQI').text();
$.ajax({
type: "POST",
url: "classes/Post/ChipSubmit.php",
data: form_data,
success: function() {
alert('success');
}
});
}
Then to get those values in your PHP you'd use:
$_POST[mm10] // This contains '10MM' or the value from that input field
$_POST[mm16] // This contains '16MM' or the value from that input field
$_POST[mm7] // This contains '7MM' or the value from that input field
$_POST[mm2] // This contains '2MM' or the value from that input field
And so on...
I tried to put together a jsFiddle for you, though it doesn't show the PHP portion. After you click submit view the console to see the data posted.
I want to use the result value and pass it to php variable,
here is my code...
billingCoffee.php
$("#linkAddSize").click(function(e){
e.preventDefault();
var txtCoffeeName = document.getElementById("txtCoffeeName").value;
var cmbSizes = document.getElementById("cmbSizes").value;
var txtPrice = document.getElementById("txtPrice").value;
$.ajax({
url: "addSizeandPrice.php",
type: "POST",
data: {coffeename: txtCoffeeName, sizes: cmbSizes, price: txtPrice},
datatype: "json",
success: function (result){
//set it php variable
}
});
});
addSizeandPrice.php
if($tableresult){
$query = "INSERT INTO tbl$CoffeeName (CoffeeSize, Price) VALUES ('$Size', '$Price');";
$insertresult = mysqli_query($con, $query);
if($insertresult){
SESSION_START();
$_SESSION['nameCoffee'] = $CoffeeName;
echo $_SESSION['nameCoffee'];
}
else{
echo "Something went wrong!";
}
}
I want to use the variable without refreshing the page... and I got this idea to use AJAX but don't know how to set it in php variable.
You are using POST as the method to send variables to your PHP script. So in PHP, they will be in the superglobal named $_POST
For example,
$coffeename = $_POST['coffeename'];
Further reading: http://php.net/manual/en/reserved.variables.post.php
Please also do some research about preventing SQL injection.
I got several elements called workers, they all got an id, position left, and position top.
I have made it to an array and then made it to a json object, which a would like to send to my database. but when i test it, in the controller and model, it says the value is null.
what to do?
the first function:
function GetUnitInfo(){
for(i=0 ; i < $('.Worker').length ; i++){
$('.Worker').each(function(){
aUnitsInfo = [{'unitid':$(this).attr("id"),
'unitposleft':$(this).position().left,
'unitpostop':$(this).position().top
}];
jUnitsInfo.push(aUnitsInfo[i]);
aUnitsInfo = JSON.stringify(jUnitsInfo);
console.log(i);
});
console.log("unitinfo: "+jUnitsInfo[i].unitid);
console.log("uniposleft: "+jUnitsInfo[i].unitposleft);
console.log("unitpostop: "+jUnitsInfo[i].unitpostop);
console.dir(jUnitsInfo[i]);
}
}
in my log i see 3 objects with the correct values.
then i want to send it to the database:
setInterval(function(){
SaveUnits();
function SaveUnits()
{
GetUnitInfo();
$sLoginEmail = $('#TxtLoginEmail').val();
// TODO: Check that the email is valid
// console.log("The email is:"+$sLoginEmail);
$.ajax({
type: 'post',
url: 'bridge.php',
data: {"sFunction":"SaveUnits", "unitsInfo":jUnitsInfo[i]},
success: function(data){
console.log(data);
$oXml = $(data);
}
});
}
},5000);
And here's where it get's tricky. I know from the first function that my jUnitsInfo[i] is containing the right objects but after this part it seems to be null.
this is my bridge:
if($_POST['sFunction'] == "SaveUnits")
{
require_once 'Controllers/UserController.php';
$oUnitsInfo = new USerController();
echo $oUnitsInfo->SaveUnits($_POST['unitsInfo']);
}
The Controller:
public function SaveUnits($unitsInfo)
{require_once 'Models/UserModel.php';
$oUserModel = new UserModel();
$unitsInfo = json_decode($unitsInfo);
$saveUnits = $oUserModel->SaveUnits($unitsInfo);}
and the model:
public function SaveUnits($unitsInfo){
// Create connection
$con = mysqli_connect("localhost","root","","awesomegame");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$unitsInfo = array();
foreach( $unitsInfo as $row ) {
$sql[] = '("'.mysql_real_escape_string($row['unitId']).'", '.$row['unitPosTop'].','.$row['unitPosLeft'].')';
}
mysql_query('INSERT INTO units (unitid, unitpostop, unitposleft) VALUES '.implode(',', $sql));}}
And when i var dump it in the controller
var_dump(json_decode($unitsInfo));
it just comes back with a null.
how do i send the array correctly? - and get the values written to the database on drifferent rows (one for each worker).
It seems like
jUnitsInfo[i]
is reasonable since you are out of the for loop.
Take the code
function GetUnitInfoAndSave(){
var jUnitsInfo=[];
$('.Worker').each(function(){
var aUnitsInfo ={'unitid':$(this).attr("id"),
'unitposleft':$(this).position().left,
'unitpostop':$(this).position().top
};
jUnitsInfo.push(aUnitsInfo);
});
for(var i=0 ; i < jUnitsInfo.length ; i++){
var $sLoginEmail = $('#TxtLoginEmail').val();
// TODO: Check that the email is valid
// console.log("The email is:"+$sLoginEmail);
var data=$.extend({},{sFunction:"SaveUnits"},jUnitsInfo[i]);
$.ajax({
type: 'post',
url: 'bridge.php',
data: data,
success: function(data){
console.log(data);
$oXml = $(data);
}
});
//console.log("unitinfo: "+jUnitsInfo[i].unitid);
//console.log("uniposleft: "+jUnitsInfo[i].unitposleft);
//console.log("unitpostop: "+jUnitsInfo[i].unitpostop);
//console.dir(jUnitsInfo[i]);
}
}
setInterval(GetUnitInfoAndSave,5000);
PS: $.Ajax and setInterval functions are asynchronous, so you don't know when data are really sent to the server. (This code sends the array items one after another)
I am having some problems with insert query which is called from ajax. The ajax call comes back with success and I am able to see it with the changed html as noted below in the code under success:function(). I am not sure why the insert query in process.php is not working. dataString has the arguments correct (alert for dataString shows the right arguments) and my fields in database can take null values.
js code
var dataString=$('#testimonials').serialize();
alert (dataString);
$.ajax(
{
type: "POST",
url: "process.php",
data: dataString,
success:function() {
$('#testimonials').html("<div id='message'></div>");
$('#message').html("<h2>Your information has been submitted!</h2>")
.append("<p>Thank you for your help and support.</p>")
.hide()
.fadeIn(1500, function()
{
$('#message').append("<img id='checkmark' src='images/check.png' height='30' width='30'/>");
});
});
process.php file
$company =mysql_escape_string($_POST('company'));
$jobfunc = mysql_escape_string($_POST('jobfunc'));
$location = mysql_escape_string($_POST('location'));
$overall = mysql_escape_string($_POST('overall'));
$detail = mysql_escape_string($_POST('detail'));
$pros = mysql_escape_string($_POST('pros'));
$cons = mysql_escape_string($_POST('cons'));
$sr_mgmt = mysql_escape_string($_POST('sr_mgmt'));
$submitted_by = mysql_escape_string($_POST('submitted_by'));
$class = mysql_escape_string($_POST('classof'));
$school = mysql_escape_string($_POST('school'));
$anonymous = mysql_escape_string($_POST('anonymous'));
mysql_select_db($database_connTest, $connTest);
$query_AddTestimonial = "INSERT into testimonials (company,job_function,location,overall,project_details,pros,cons,sr_mgmt,submitted_by,class,school,anonymous) VALUES ('$company','$jobfunc','$location','$overall','$detail','$pros','$cons','$sr_mgmt','$submitted_by','$class','$school','$anonymous')";
$result_AddTestimonial = mysql_query($query_AddTestimonial) or die(mysql_error());
In the penultimate line when you create $query_AddTestimonial, the string you're creating isn't putting the php variables in because you're not telling it that they're variables. You can use the php variables like this:
$query_AddTestimonial = "INSERT into testimonials (company,job_function,location,overall,project_details,pros,cons,sr_mgmt,submitted_by,class,school,anonymous) VALUES ('{$company}','{$jobfunc}','{$location}','{$overall}','{$detail}','{$pros}','{$cons}','{$sr_mgmt}','{$submitted_by}','{$class}','{$school}','{$anonymous}')";
The problem was with the way I was calling the variables. It should have been $_POST['company'] rather than $_POST('company'). Completely missed it (the square brackets for $_POST since its an array)
I was chasing after JSON as a method to do this, but I'm wondering if I should have been looking in a different direction. I'll tackle this as simply as possible.
Jquery from "page1.php"
$(".button").click(function() {
var name = "Jeremy";
var car = "Saturn";
var color = "blue";
var state = "Mississippi";
// I need all four of these to get passed over to PHP in the following ajax
$.ajax({
url: "page2.php",
//dataType: '???????',
type: 'POST',
data: 'mydata=' + ????????,
success: function(result) {
alert(result);
}
});
});
So there are four jquery variables that I've fudged. Now I need to hand them over to page2.php for my backend PHP. Here is page2.php
if (filter_has_var(INPUT_POST, "mydata")) {
$mydata = mysql_real_escape_string(filter_input(INPUT_POST,'mydata'));
// Here I need to turn these into variables, or just an array and then throw them into my SQL
mysql_query("INSERT INTO mysqldata (namefield, carfield, colorfield, statefield)
VALUES ($name, $car, $color, $state)");
$sqlresult = mysql_insert_id;
if ($sqlresult != '') {
echo "SQL successfully updated.";
}
}
Thus, my question is: What is the most effective method to pass the data to PHP, in this case?
There's probably a simple answer here that I just don't know. Can I turn those jquery variables into an array and hand them to PHP that way? Is JSON still the best way to go, and I just need to know how to convert it on the back end?
As an array
var mydata = [name, car, color, state];
Or as an object
var mydata = { 'name' : name, 'car' : car, 'color' : color, 'state' : state };
-
$.ajax({
...
data: mydata
...
JavaScript/jQuery
$(".button").click(function() {
// create the data object
var myData = {
name : 'Jeremy',
car : 'Saturn',
color: 'blue',
state: 'Mississippi'
};
$.ajax({
url: "page2.php",
//dataType: '???????',
type: 'POST',
data: myData,
success: function(result) {
alert(result);
}
});
});
PHP
// check if the name has been posted, which means we have a submission to process
if(isset($_POST['name'])){
$query = sprintf("INSERT INTO mysqldata (namefield, carfield, colorfield, statefield) VALUES ('%s', '%s', '%s', '%s')",
mysql_real_escape_string($_POST['name']), // clean malicious code
mysql_real_escape_string($_POST['car']), // from user input
mysql_real_escape_string($_POST['color']), // to protect against
mysql_real_escape_string($_POST['state'])); // SQL injection
// run the query
$result = mysql_query($query);
// check if the insert was done successfully
if($result){
echo 'SQL successfully updated.';
}
}
If you notice, based on the id we used on the javascript object to assign the data, we are accessing it in the $_POST array. E.g.
The name
var myData = {
name : 'Jeremy',
...
}
Will be access on PHP side with
$_POST['name']
Hope this blog posts helps you..
http://www.factsandpeople.com/facts-mainmenu-5/26-html-and-javascript/89-jquery-ajax-json-and-php
It focuses on using json_decode method to decode the json