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.
Related
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.
this is my php script from which am returning the value to the ajax calling it
<?php
$questionid=$_GET['qid'];
$answer=$_GET['clickedvalue'];
$dbconnect=mysqli_connect('localhost','root','','quiz')or die("Error Connecting to database");
$query="select answer from question_answer where id=$questionid";
$result=mysqli_query($dbconnect,$query);
while($rows=mysqli_fetch_array($result))
{
$dbanswer=$rows['answer'];
}
//array values which will be passed to json
$result=array('correct'=>'Correct Answer',
'incorrect'=>'Incorrect Answer'
);
if($dbanswer==$answer)
{
//json to be passed to next page with key value pair
echo json_encode(array('display_msg'=>$result['correct'],'points'=>'positive'));
}
else{
echo json_encode(array('display_msg'=>$result['incorrect'],'points'=>'negative'));
}
?>
and this is my ajax code
$.ajax({
url:'checkanswer.php',
dataType:'json',
data:{'clickedvalue':clickedvalue,'qid':qid},
success:function(data){
$this.find(".report").html(data.display_msg);
$this.delay(1000).slideUp();
}
});
So my question is how do i store the value of data.points object that is passed from the php as a json in the javascript variable or is it not possible to store in javascript variable directly if yes how and if no what will be the way to get the value and store somewhere
Just add a temp variable before calling ajax
Some thing like this
var myTempVariable; //Temp JS variable to use somewhere else
$.ajax(
{
url: 'checkanswer.php',
dataType: 'json',
data:
{
'clickedvalue': clickedvalue,
'qid': qid
},
success: function(data) {
$this.find(".report").html(data.display_msg);
$this.delay(1000).slideUp();
myTempVariable = data; //assugn value to temp varaible
}
});
in your ajax success function :
var myVariable = data.points;
This might help
I'm trying to get the data used below to be caught in my alives.php page.
Essentially, alives.php requires a variable $passcode.
How do I pass the content of data below as the variable $passcode through a POST request?
<script>
$(document).ready(function() {
$('#alive').click(function () {
var data = '<?php $row['code']; ?>';
$.ajax({
type:"GET",
cache:false,
url:"alives.php",
data:data, // multiple data sent using ajax
success: function (html) {
}
});
return false;
});
});
</script>
alives.php
<?php
require("database.php");
$checkvote = "SELECT code FROM votes WHERE code = '$passcode'";
$updatealive = "UPDATE votes SET alive = +1 WHERE code = '$passcode'";
$addvote = "INSERT INTO votes (code, alive) VALUES ('$passcode',+1 )";
$checkvoterlt = mysqli_query($con, $checkvote);
if(mysqli_num_rows($checkvoterlt) > 0) {
$result = mysqli_query($con, $updatealive) or die(mysqli_error());
} else {
$result = mysqli_query($con, $addvote) or die(mysqli_error());
}
mysqli_close($con);
?>
So much is wrong.
Problem 1: You are specifying a GET request: $.ajax({ type:"GET",. If you want it to be POST:
$.ajax({
type:"POST",
Problem 2: Your javascript data variable should be key: value pairs like:
var data = { 'passcode' : code };
Then in PHP get the data with $_POST['passcode']
This sort of passcode should NOT be passed to the client side, as it can be easily manipulated.
Instead, store such information in a $_SESSION variable (assumes you've started your PHP with session_start), as this will keep the value safe, pass it to all pageloads where it may be needed, and be impossible to manipulate (while it is possible to hijack someone else's session, a malicious user still won't be able to actively change the value)
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