What I'm looking is that when the button is clicked then the values are taken and put into variables. The variables are then used in the AJAX call, so I can post them.
function addTask(){
$("#add_task_button").click(function(){
var task_title = $('#add_task_title').val();
var task_description = $('#add_task_desc').val();
var task_member = $( "#task_member option:selected" ).text();
var task_status = $( "#task_status option:selected" ).text();
$.ajax({
url: '../php_scripts/add_task.php',
type: 'POST',
data: {'title': task_title, 'description': task_description, 'member': task_member, 'status': task_status},
success: function() {
alert("SUCCESS");
},
error: function(jqXHR,textStatus,errorThrown) {
alert("FAILURE");
}
});
});
}
This is the jQuery and AJAX call
<?php
require_once "cdbconnect.php";
$taskTitle = $_POST['title'];
$taskDescription = $_POST['description'];
$memberName = $_POST['member'];
$groupName = "test";
$status = $_POST['status'];
$query = "INSERT INTO task_tbl (Task_title, Task_description, Member_Name, Group_Name, Status) values('$taskTitle', '$taskDescription', '$memberName', '$groupName', '$status')";
$result = $conn -> query($query);
if(!$result)
{
$conn -> error;
}
mysqli_close($conn);
?>
This Is the PHP file. I always receive the failure alert as the data is not submitted to the table.
Am I missing something here?
A failing ajax request does not mean there is a logical error in your php script, but rather that the request could not be executed in the first place. Think "Server could not be reached", so your php code wasn't even executed.
Possible reasons are:
Network problems
Wrong url
In your case the url looks suspicious...
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.
I am trying to update a database entry through jQuery and AJAX.
I am checking that the values i send over is correct - but I am not sure how to check why the database is not updated.
My code is as follows:
$(document).on("click", ".approve", function(){
var classes = $(this).parents('div:eq(0)'); // this gets the parent classes.
i = 0;
var pros = [];
classes.find(".prosncons .pros ul li").each(function(){
pros.push($(this).text());
});
var cons = [];
classes.find(".prosncons .cons ul li").each(function(){
cons.push($(this).text());
});
var notes = classes.find(".notes").text();
var id = classes.find(".id").text();
var data = "method=approve&pros="+pros+"&cons="+cons+"¬es="+notes+"&id="+id;
$.ajax({
type: "POST",
url: "../scripts/upload.php",
data: data,
success: $(this).closest(".approval").remove(),
});
});
PHP::
if($method == "approve"){
$sql = "UPDATE `approval` SET approved = 1 WHERE pros=:pros, cons=:cons, notes=:notes, id=:id";
$statement = $conn->prepare($sql);
$statement->execute(array(':pros' => $pros, ':cons' => $cons, ':notes' => $notes, ':id'=> $id));
}
You are t sending in the right way your data to the php file
Change your ajax request with this:
$.ajax({
type: "POST",
url: "../scripts/upload.php",
data: { method: "approve", pros: pros, cons:cons, note:notes, id:id },
success: $(this).closest(".approval").remove(),
});
To get your variable into the php file you can retireve that with $_POST['var_name']
In your php try this to check method:
if($_POST['method'] == "approve"){
$sql = "UPDATE `approval` SET approved = 1 WHERE pros=:pros, cons=:cons, notes=:notes, id=:id";
$statement = $conn->prepare($sql);
$statement->execute(array(':pros' => $_POST['pros'], ':cons' => $_POST['cons'], ':notes' => $_POST['notes'], ':id'=> $_POST['id']));
}
You can check $conn->error for the last error. This should tell you if you have an error.
I would normally check if there is an error and if there is I would return a status of error so my JS code knows there was a problem, then handle it.
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.
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'm trying to delete a mysql record with javascript but I fail.
So this is my js function
function delpost(id){
if(confirm('Are you sure?')){
$('#comment_'+id).hide();
http.open("get","/index.php?p=delcomment&id=" + id, true);
http.send();
}
}
And this is my delcomment.php(included through index.php)
$comment_id = $_GET['id'];
if(logged() && $status=="administrator"){
$delquery = mysql_query("DELETE FROM comments WHERE id='$comment_id' LIMIT 1");
die();
}else{
die();
}
I hope you can help me with this :)
update:
try using
http.send(null)
instead of
http.send()
also, use firebug to see if your ajax request is actually being sent to the server
better solution:
(php rusty!)
delcomment.php
$comment_id = $_POST['id'];
$comment_id = mysql_real_escape_string($comment_id);
if(logged() && $status=="administrator"){
$query = "DELETE FROM comments WHERE id='{$comment_id}'";
$result = mysql_query($query, $con);
die();
}else{
die();
}
using jquery to post (make sure to include the jquery.js), your javascript function should be like this:
function delpost(id){
if(confirm('Are you sure?')){
$.ajax({
type: "POST",
url: "/index.php",
data: {p: "delcomment", id: id},
success: function(){
$('#comment_'+id).hide();
},
error: function(){
alert('failure');
}
});
}
}