Jquery and PHP update mysql database - php

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+"&notes="+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.

Related

Ajax - variables are seen in chrome network tab but they don't seem to pass to the PHP function

I am trying to update a php function using ajax.
I Have an array stored in localstorage.
The array contains values of clicked id's.
When I click the <tr>, the array gets updated and sent via ajax from a js file to the php file.
js file
function storeId(id) {
var ids = JSON.parse(localStorage.getItem('reportArray')) || [];
if (ids.indexOf(id) === -1) {
ids.push(id);
localStorage.setItem('reportArray', JSON.stringify(ids));
}else{
//remove id from array
var index = ids.indexOf(id);
if (index > -1) {
ids.splice(index, 1);
}
localStorage.setItem('reportArray', JSON.stringify(ids));
}
return id;
}
//ajax function
$('table tr').click(function(){
var id = $(this).attr('id');
storeId(id);
var selected_lp = localStorage.getItem('reportArray');
console.log(selected_lp);
var query = 'selected_lp=' + selected_lp;
$.ajax({
type: "POST",
url: "../inc/updatelponadvdash.php",
data: { selected_lparr : selected_lp},
cache: false,
success: function(data) {
return true;
}
});
});
updatelponadvdash.php file
<?php
require_once 'inc.php';
$selected_lparr = json_decode($_POST['selected_lparr']);
foreach($selected_lparr as $value){
$dbData = $lploop->adv_lploops($value);
}
?>
Now, in the chrome network tab, when I click the and I dump_var($selected_lparr) the array is updated and I see the values like this:
For some reason I get a 500 error.
As well I dont understand why the var_dump(inside the function below) dosent work. I seems that the function adv_lploops dosent get the variables. but i dont understand why.
This is the fuction I call:
public function adv_lploops($value){
$sql = "SELECT * FROM `lptitels` WHERE titleidNo = '$value'";
$row = $sql->fetch(PDO::FETCH_ASSOC);
var_dump($row);
}
You aren't executing the sql query, try the following:
$sth = $db->prepare($sql);
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC);
note: you will need the $db object which is a connection to your database

AJAX jQuery & PHP issue

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...

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.

Rating not add with ajax in wordpress

I have a problem
There is a rating system on songs (Its not my code i debugging it). but it could not add or update or show me the rating.
here is my code:
Ajax.js
function bindEvents() {
$(cssSelector.rating_succes).css('display','none');
//Set the new rating when the user clicks
$(cssSelector.ratingLevel).click(function() {
var $this = $(this), rating = $this.parent().children().index($this) + 1, index;
var trackname = $(cssSelector.title+':first').text();
var postdata1 = 'action=my_special_ajax_call5&rating='+rating+'&trackname='+trackname;
alert(postdata1);
jQuery.ajax({
type:'POST',
url:ajaxurl,
cache:false,
data: postdata1,
beforeSend:function(){
},
success:function(res){
$(cssSelector.rating_succes).html(res).fadeIn(500).delay(1000).fadeOut(500);
//window.setTimeout(function(){location.reload()},2000);
}
});
$this.prevAll().add($this).addClass(attr(cssSelector.ratingLevelOn)).end().end().nextAll().removeClass(attr(cssSelector.ratingLevelOn));
});
}
Proccess.php
function implement_ajax5(){
global $wpdb;
$table = $wpdb->prefix."songs";
$table1 = $wpdb->prefix."rating";
$song_title = strip_tags($_POST['trackname']);
$rating_value = strip_tags($_POST['rating']);
$songres = $wpdb->get_row("SELECT * FROM $table WHERE `title`='$song_title'") or die(mysql_error());
$song_id = $songres->id;
$total_votes = $songres->total_votes;
$total_votes = $total_votes+1;
$ip = $_SERVER['REMOTE_ADDR'];
$data = array(
'song_id' => $song_id,
'rating_value' => $rating_value,
'user_ip' => $ip
);
$check = $wpdb->get_results("SELECT * FROM $table1 WHERE song_id='$song_id' AND user_ip='$ip'");
if(!$check){
$insert = $wpdb->insert($table1,$data);
$wpdb->update(
$table,
array(
'total_votes' => $total_votes,
),
array( 'ID' => $song_id )
) or die(mysql_error());
echo 'Thank you';
}else{echo 'Already rated';}
die();
}
index.php
add_action('wp_ajax_my_special_ajax_call5', 'implement_ajax5');
add_action('wp_ajax_nopriv_my_special_ajax_call5', 'implement_ajax5');//for users that are not logged in.
I dont understand what happen when i alert it shows me right values but not add or update in database.
ok just try this in your Ajax.js at top of the page
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
And every thing goes perfect
and i think in your process page there is no need to update query. If you want to delete this there is no issue.
i get this a lot........ajaxurl needs to be defined, so i've learned that its just easier to not use ajaxurl and put in "/wp-admin/admin-ajax.php" in the url section.
Also i dont see you using non-conflict jQuery? (use the word jQuery instead of $)
You may also have issues with your postdata string, i may be wrong but what you need is action: '' ,
rating: '',
etc.
A good practice is to var_dump $_POST and exit at the beginning of your function to make sure they are passing over correctly. then in success- console.log(res) or whatever you are calling your return data
function bindEvents() {
jQuery(cssSelector.rating_succes).css('display','none');
//Set the new rating when the user clicks
jQuery(cssSelector.ratingLevel).click(function() {
var $this = jQuery(this), rating = $this.parent().children().index($this) + 1, index;
var trackname = jQuery(cssSelector.title+':first').text();
//alert(postdata1); -> console.log() is better for looking at objects
jQuery.ajax({
type:'POST',
url: "/wp-admin/admin-ajax.php",
cache:false,
data: {
action: 'my_special_ajax_call5',
rating: rating,
trackname: trackname
}
success:function(output){
console.log(output)
jQuery(cssSelector.rating_succes).html(output).fadeIn(500).delay(1000).fadeOut(500);
//window.setTimeout(function(){location.reload()},2000);
}
});
$this.prevAll().add($this).addClass(attr(cssSelector.ratingLevelOn)).end().end().nextAll().removeClass(attr(cssSelector.ratingLevelOn));
});
}
see how you get on with that :)

method to move multiple variables (array?) from jquery to PHP

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

Categories