Insert query in php not working with ajax - php

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)

Related

How to post more than 1 var’s with ajax

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.

Save to database without a form using jQuery and PHP

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.

how to pass AJAX response value to PHP variables?

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.

jQuery ajax returning 'Object Object'

I am trying to send data to a PHP script using jQuery Ajax. For some reason the Ajax request is throwing up an error and returning the following data from the PHP script - [object Object]
I've copied my code in below. I've also copied code using the exact same method elsewhere on the page which seems to work fine!
Can anyone explain why this is happening?
Firstly, the code that is working fine
jQuery
$("#reqtable a").click(function(){
var cells = [];
var name;
var account;
var module;
var email;
$(this).parent().parent().find("td").each(function(){
cells.push($(this).html());
});
$(this).parent().parent().find("input").each(function(){
email = $(this).val();
});
$(this).parent().parent().prop('id', 'die');
name = cells[0];
account = cells[1];
module = cells [2];
$.ajax({
url: "release.php",
type: "POST",
data: {name: name, account: account, module: module, email: email},
success: function(){
$("#die").remove();
}
});
});
PHP
<?php
include('../../dbconnect.php');
$name = $_POST['name'];
$account = $_POST['account'];
$email = $_POST['email'];
$module = $_POST['module'];
$releasequery = "INSERT INTO release_assignment(name, account, email, module) VALUES ('$name', '$account', '$email', '$module')";
$release = $conn->query($releasequery);
$erasequery = "DELETE FROM request_assignment WHERE email='$email' AND module = $module";
$erase = $conn->query($erasequery);
?>
And now the code that IS NOT working.
jQuery
$("#downloadtable a").click(function(){
var dlcells = [];
var dlname;
var dlaccount;
var dlmodule;
var dlemail;
var dlsub;
var dlpath;
$(this).parent().parent().find("td").each(function(){
dlcells.push($(this).html());
});
$(this).parent().parent().find("input.dlemail").each(function(){
dlemail = $(this).val();
});
$(this).parent().parent().find("input.dlsub").each(function(){
dlsub = $(this).val();
});
$(this).parent().parent().find("input.dlpath").each(function(){
dlpath = $(this).val();
});
$(this).parent().parent().prop('id', 'die2');
dlname = dlcells[0];
dlaccount = dlcells[1];
dlmodule = dlcells [2];
$.ajax({
url: "download.php",
type: "POST",
data: {dlname: dlname, dlaccount: dlaccount, dlmodule: dlmodule, dlemail: dlemail, dlsub: dlsub, dlpath: dlpath},
success: function(data){
$("#die2").remove();
},
error: function(data){
$('#downloaddiv').html('<p>' + data + '</p>');
}
});
});
PHP
<?php
include('../../dbconnect.php');
$name = $_POST['dlname'];
$email = $_POST['dlemail'];
$account = $_POST['dlaccount'];
$module = $_POST['dlmodule'];
$path = $_POST['dlpath'];
$submission = $_POST['dlsub'];
$feedbackquery = "INSERT INTO feedback_assignments(name, email, level, unit, assignmentpath, submission) VALUES ('$name', $email, '$account', '$module', '$path', '$submission')";
$feedback = $conn->query($feedbackquery);
$erasequery = "DELETE FROM uploaded_assignments WHERE email='$email' AND unit = $module";
$erase = $conn->query($erasequery);
?>
When I comment out all the PHP code and simply put echo ($_POST['dlname']); it returns the data [object Object]
Can anyone explain what is going on and why it seems to work with one block of code but not the other?
Thanks!
Chris
Update: It might be worth mentioning that the initial link ('#downloadtable a') actually instigates a file download as well as the ajax call, whereas in the code that is working it simply makes the ajax call and nothing else. I don't know if this is throwing a spanner in the works but thought it worth mentioning.
Update 2: Using the jQuery Ajax error callback as described below I'm getting the following response:
{"readyState":0,"responseText":"","status":0,"statusText":"error"}
AJAX error: error :
The code I've used in the error callback is as follows:
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
Unfortunately I don't understand what this means. Can anyone shed any light on this?
Update 3 OK, I've found the reason for Ajax blowing up on me, and it relates to update number 1 (above). Basically because the link is to a file download (a .docx file) it seems to be causing the problem with ajax. When I change the link to href='#' instead of href="document.docx", the ajax and PHP script works.
This throws up a new question, of course - how can I get the link to download the file whilst simultaneously updating the database?
Specify a dataType and use console to debug your data response.
Also, notice that the error callback contains the following arguments and not any "data";
error Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )
Update
The target file download.php might be throwing an exception. Possibly because of some missing quotes around $email on the line;
$feedbackquery = "INSERT INTO feedback_assignments(name, email, level, unit, assignmentpath, submission) VALUES ('$name', $email, '$account', '$module', '$path', '$submission')";
Debug download.php and make sure it generates the expected output/response.
I advice you to escape the values you are using to build your SQL query with to prevent SQL injection.

jQuery ajax call won't update mysql after pressing back button

I have a form that uses ajax to submit data to a mysql database, then sends the form on to PayPal.
However, after submitting, if I click the back button on my browser, change some fields, and then submit the form again, the mysql data isn't updated, nor is a new entry created.
Here's my Jquery:
$j(".submit").click(function() {
var hasError = false;
var order_id = $j('input[name="custom"]').val();
var order_amount = $j('input[name="amount"]').val();
var service_type = $j('input[name="item_name"]').val();
var order_to = $j('input[name="to"]').val();
var order_from = $j('input[name="from"]').val();
var order_message = $j('textarea#message').val();
if(hasError == false) {
var dataString = 'order_id='+ order_id + '&order_amount=' + order_amount + '&service_type=' + service_type + '&order_to=' + order_to + '&order_from=' + order_from + '&order_message=' + order_message;
$j.ajax({ type: "GET", cache: false, url: "/gc_process.php", data: dataString, success: function() { } });
} else {
return false;
}
});
Here's what my PHP script looks like:
<?php
// Make a MySQL Connection
include('dbconnect.php');
// Get data
$order_id = $_GET['order_id'];
$amount = $_GET['order_amount'];
$type = $_GET['service_type'];
$to = $_GET['order_to'];
$from = $_GET['order_from'];
$message = $_GET['order_message'];
// Insert a row of information into the table
mysql_query("REPLACE INTO gift_certificates (order_id, order_type, amount, order_to, order_from, order_message) VALUES('$order_id', '$type', '$amount', '$to', '$from', '$message')");
mysql_close();
?>
Any ideas?
You really should be using POST instead of GET, but regardless, I would check the following:
That jQuery is executing the ajax call after you click back and change the information, you should probably put either a console.log or an alert calls to see if javascript is failing
Add some echos in the PHP and some exits and go line by line and see how far it gets. Since you have it as a get, you can just load up another tab in your browser and change the information you need to.
if $j in your jQuery is the form you should be able to just do $j.serialize(), it's a handy function to get all the form data in one string
Mate,
Have you enclosed your jquery in
$j(function(){
});
To make sure it is only executed when the dom is ready?
Also, I'm assuming that you've manually gone and renamed jquery from "$" to "$j" to prevent namespace conflicts. If that isn't the case it should be $(function and not $j(function
Anyway apart from that, here are some tips for your code:
Step 1: rename all the "name" fields to be the name you want them to be in your "dataString" object. For example change input[name=from] to have the name "order_from"
Step 2:
Use this code.
$j(function(){
$j(".submit").click(function() {
var hasError = false;
if(hasError == false) {
var dataString = $j('form').serialize();
$j.ajax({ type: "GET", cache: false, url: "/gc_process.php?uu="+Math.random(), data: dataString, success: function() { } });
} else {
return false;
}
});
});
You'll notice i slapped a random variable "uu=random" on the url, this is generally a built in function to jquery, but to make sure it isn't caching the response you can force it using this method.
good luck. If that doesn't work, try the script without renaming jquery on a fresh page. See if that works, you might have some collisions between that and other scripts on the page
Turns out the problem is due to the fact that I am using iframes. I was able to fix the problem by making the page without iframes. Thanks for your help all!

Categories