$_POST is empty as a result of AJAX - javascript

The problem: var_dump($_POST['day']) is NULL, var_dump($b); is string(0) ""
As a result - return empty json
HTML Form with checkboxes
<form id="filter">
<input type="checkbox" name="day[]" value="1">
<input type="checkbox" name="day[]" value="2">
<input type="checkbox" name="day[]" value="3">
</form>
JS
var a = 0;
var b = 5;
var c = $( "#filter" ).serialize();
var Data = 'a=' + a + '&' + 'b=' + b + '&' + c;
var process = false;
$.ajax({
url: 'script.php',
method: 'POST',
data: Data,
beforeSend: function() {
process = true;
}
});
script.php var_dump($_POST['day']) is NULL
$a = $_POST['a'];
$b = $_POST['b'];
$c = implode(',', $_POST['day']); // Warning: implode(): Invalid arguments passed
$in = str_repeat('?,', count($c) - 1) . '?'; // Warning: Second argument has to be greater than or equal to 0
$sql = "SELECT * FROM table WHERE day IN ($in) ASC LIMIT :a, :b";
$stmt = $pdo->prepare($sql);
$stmt->execute($с, [$a, $b]);
$data = $stmt->fetchAll();
echo json_encode($data);

$result = [];
$a = (int) $_POST['a'];
$b = (int) $_POST['b'];
$c = array_filter( (array) $_POST['day'] );
if ( !empty($c) )
{
$c = implode(',', $_POST['day']);
$c = explode(",", $c);
$in = str_repeat("?,", count($c) - 1) . '?';
$sql = "SELECT * FROM table WHERE day IN ($in) LIMIT ?, ?";
$stmt = $pdo->prepare($sql);
$params = array_merge($c, [$a, $b]);
$stmt->execute($params);
$data = $stmt->fetchAll();
$result = $data;
}
echo json_encode($result);

Related

Adding DropDown list in jQuery DataTable

I want to display table's data with jQuery DataTable and sometimes apply an extra data filtering, using the output of a dropdown select input.
The main code for fetching data (fetch.php) is:
<?php
include('db.php');
include('function.php');
$query = '';
$output = array();
$query .= "SELECT * FROM Part_tb ";
if(isset($_POST["search"]["value"]))
{
$query .= 'WHERE part_manufacturer LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR part_id LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY part_id ASC ';
}
if($_POST["length"] != -1)
{
$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connection->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
$sub_array = array();
$sub_array[] = $row["part_manufacturer"];
$sub_array[] = $row["part_id"];
$sub_array[] = $row["part_category"];
$sub_array[] = $row["part_stock"];
$data[] = $sub_array;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $filtered_rows,
"recordsFiltered" => get_total_all_records(),
"data" => $data
);
echo json_encode($output);
?>
while the DataTable is defined in index.php as follows:
var dataTable = $('#user_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"actions/fetch.php",
type:"POST"
},
"columnDefs":[
{
"targets":[0, 1],
"orderable":false,
},
],
});
In index.php, i've created 3 dependent dropdown lists, which load data from other tables. Now, i want to take the id of 3rd dropdown list and update the data of Part_tb in fetch.php accordingly. Below, you can see that when 3rd dropdown change, i call a function load_parts():
$(document).on('change', '#sub3_category_item', function(){
load_parts();
});
function load_parts()
{
var action = 'fetch_data';
var filter_part_id = $('#sub2_category_item').val();
$.ajax({
url:"actions/fetch.php",
method:"post",
data:{action:action, filter_part_id:filter_part_id},
success:function(data)
{
$('#user_data').DataTable().ajax.reload();
}
});
}
The problem is that i can't filter the data of fetch.php according to the selected id of #sub2_category_item. Could you help me on that?
I've modified the index.php as follows:
$(document).on('change', '#sub3_category_item', function(){
var filter_part_id = $('#sub3_category_item').val();
$('#user_data').DataTable().destroy();
fill_datatable(filter_part_id);
});
fill_datatable();
function fill_datatable(filter_part_id = '')
{
var dataTable = $('#user_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"searching" : false,
"ajax":{
url:"actions/fetch.php",
type:"POST",
data:{filter_part_id:filter_part_id}
}
});
and fetch.php:
$query .= "SELECT * FROM Part_tb ";
if(isset($_POST['filter_part_id']) && $_POST['filter_part_id'] != '')
{
$query .= "SELECT * FROM Part_tb WHERE part_id IN (SELECT pcfit_name from Part_car_fit_tb WHERE pcfit_id ='".$_POST["filter_part_id"]."') ";
}
but dataTable crashes, when #sub3_category_item is selected. Any idea, how to filter datatable with the value $_POST["filter_part_id"]?

JavaScript/AJAX prints weirdly

My JavaScript/AJAX prints comments. It's all good, until I want to insert/get more than one comment. It duplicates itself. This feels like a nesting/missed parenthesis problem in my code, but I can't be able to find it...
My JS code:
$(document).ready(function(){
var url = 'comment-get.inc.php';
$.getJSON(url, function(data) {
$.each(data, function(index, item) {
var t = '';
t += '<div class="comment_holder" id="_'+item.id+'">';
t += '<div class="user"> <img src="src/img/page3_img7.jpg" alt="" class="img_inner fleft">';
t += '<div class="extra_wrapper">';
t += ''+item.username+'<br>';
t += ''+item.date+'<br>';
t += '<button class="button2" type="button" id="'+item.id+'">Delete</button>';
t += '</div></div>';
t += ''+item.message+'<br><br>';
t += '</div>';
$('.comment_holder').prepend(t);
add_delete_handlers();
});
});
add_delete_handlers();
$('#postButton').click(function(){
comment_post_btn_click();
});
function comment_post_btn_click()
{
//text in textarea with username, page and date
var _username = $('#postUsername').val();
var _page = $('#postPage').val();
var _date = $('#postDate').val();
var _message = $('#postMessage').val();
if(_message.length > 0)
{
//proceed with ajax callback
$('#postMessage').css('border', '1px solid #ABABAB');
$.post("comment-set.inc.php",
{
task : "comment-set",
username : _username,
page : _page,
date : _date,
message : _message
}
).success(
function(data)
{
//Task: Insert html into the div
comment_set(jQuery.parseJSON(data));
console.log("ResponseText: " + data);
});
}
else
{
//text in area is empty
$('#postMessage').css('border', '1px solid #FF0000');
console.log("Comment is empty");
}
//remove text after posting
$('#postMessage').val("");
}
function add_delete_handlers()
{
$('.button2').each(function()
{
var btn = this;
$(btn).click(function()
{
comment_delete(btn.id);
});
});
}
function comment_delete(_id)
{
$.post("comment-del.inc.php",
{
task : "comment-del",
id : _id
}
).success(
function(data)
{
$('#_' + _id).detach();
});
}
function comment_set(data)
{
var t = '';
t += '<div class="comment_holder" id="_'+data.comment.id+'">';
t += '<div class="user"> <img src="src/img/page3_img7.jpg" alt="" class="img_inner fleft">';
t += '<div class="extra_wrapper">';
t += ''+data.comment.username+'<br>';
t += ''+data.comment.date+'<br>';
t += '<button class="button2" type="button" id="'+data.comment.id+'">Delete</button>';
t += '</div></div>';
t += ''+data.comment.message+'<br><br>';
t += '</div>';
$('.comment_holder').prepend(t);
add_delete_handlers();
}
});
Comments.php:
<?php
class Comments {
public function set($message, $username, $date, $page) {
$connect = mysqli_connect('localhost', 'root', '', 'trdb');
$sql = "INSERT INTO comments VALUES ('', '$username', '$page', '$date', '$message')";
$query = mysqli_query($connect, $sql);
if($query){
$std = new stdClass();
$std->id = mysqli_insert_id($connect);
$std->message = $message;
$std->username = $username;
$std->date = $date;
$std->page = $page;
return $std;
}
return null;
}
public function del($id) {
$connect = mysqli_connect('localhost', 'root', '', 'trdb');
$sql = "DELETE FROM comments WHERE id = $id";
$query = mysqli_query($connect, $sql);
if($query)
{
return true;
}
}
}
?>
Comment-get.inc.php:
<?php
$page = htmlentities("/index.php?page=maplepancakes", ENT_QUOTES);
$connect = mysqli_connect('localhost', 'root', '', 'trdb');
$sql = "SELECT * FROM comments WHERE page='$page' ORDER BY id DESC";
$result = $connect->query($sql);
$data = array();
while ($row = $result->fetch_assoc()) {
$row_data = array(
'id' => $row['id'],
'username' => $row['username'],
'date' => $row['date'],
'message' => $row['message']
);
array_push($data, $row_data);
}
?>
<?php
echo json_encode($data);
?>
Comment-set.inc.php:
<?php
if(isset($_POST['task']) && $_POST['task'] == 'comment-set'){
$username = $_POST['username'];
$date = $_POST['date'];
$page = $_POST['page'];
$message = $_POST['message'];
require_once 'comments.php';
if(class_exists('Comments')){
$userInfo = $username;
$commentInfo = Comments::set($message, $username, $date, $page);
$std = new stdClass();
$std->user = $userInfo;
$std->comment = $commentInfo;
echo json_encode($std);
}
}
?>
Picture of the problem (json_encode in the bottom of the picture containing 3 comments):
your comments div container has class .comment_holder so each time with new comment you prepend to all class's so create comment container with unique id an prepend to this. like this $('#comment_container').prepend(t); this with work.

Display a php cookie in html

I have set a cookie using php.
Here's my code:
<?php
include_once 'php/config.php';
session_start(); //starting the session for user profile page
if(!empty($_POST['username'])) //checking the 'user' name which is from Sign-In.html, is it empty or have some text
{
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$query = mysql_query("SELECT * FROM users where username = '$username' AND password = '$password'") or die(mysql_error());
$row = mysql_num_rows($query) or die(mysql_error());
if($row==1)
{
$_SESSION['username'] = $username;
setcookie('username', $username, time() + (86400 * 30), "/"); // 86400 = 1 day
echo $_SESSION['username'];
echo "SUCCESSFULLY LOGGEDIN...";
echo "<script>setTimeout(function(){window.location.href='index.html'},2000);</script>";
}
else
{
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
echo "<script>setTimeout(function(){window.location.href='index.html'},2000);</script>";
}
}
?>
I want display the 'username' cookie in html like Hi ""
.
Please Help.
Tried this javascript:
<script type="text/javascript">
function getCookie(name)
{
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
</script>
Use echo $_COOKIE['username']; instead of echo $_SESSION['username'];. It will echo out of the second reload of the page. (Why?)
<span id="myId"><span>
<script>
document.getElementById('myId').innerHTML=listCookies()
function listCookies() {
var theCookies = document.cookie.split(';');
var aString = '';
for (var i = 1 ; i <= theCookies.length; i++) {
aString += i + ' ' + theCookies[i-1] + "\n";
}
return aString;
}
</script>

Displaying existing content in editable textarea

Hi I am trying to make editable page with javascript and php and I want to display whats already stored in the area however it does not work. Its meant to be a blog page meaning that there are multiple posts. And I am unsure whether the problem is within the js or php.
This is the javascript I am using. The console.log() writes that post_id is unassigned.
$(document).on('click', '.editButton', function () {
var post_id = $(this).parent().data('id');
var self = this;
$.getJSON(settings.server, {post_id: post_id}, function(data){
var editableText = '<textarea class="editPostBody">' + data.body + '</textarea>';
console.log(post_id);
$(".post").parent().replaceWith(editableText);
});
});
var formatPost = function(d) {
var s = '';
s = '<div class="post" data-id="' + d.post_id + '"><h2 class="postHeading">' + d.title +'</h2>';
s += d.body;
s += '<p> Posted on: ' + d.date + '</p>';
s += '<div class="btn editButton">Edit Post</div>'
s += '</div>'
return s;
};
And this is the PHP file
connection to db established prior
if(count($_GET)) {
if(isset($_GET['post_id'])){
get_post_id( $_GET['post_id']);
}
}
else{
get_posts();
}
function get_posts() {
global $link;
// $sql = "SELECT COUNT(1) FROM posts";
// $result = mysqli_query($link, $sql);
// $total = mysqli_fetch_array($result);
$sql = "SELECT * FROM post ORDER BY date DESC LIMIT 0, 5";
$result = mysqli_query($link, $sql);
$rows = array();
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
// $json = '{"total":"' . $total[0] . '","posts":';
$json = json_encode($rows);
// $json .= "}";
print($json);
}
function get_post_id($postId){
global $link;
$sql = "SELECT * FROM post WHERE id = $postId";
$result = mysqli_query($link, $sql);
$toSend = mysqli_fetch_assoc($result);
print json_encode($toSend);
}
Thank you
I modified the code like this
function get_post_id($postId){
global $link;
$sql = "SELECT * FROM post WHERE post_id = $postId";
$result = mysqli_query($link, $sql);
$toSend = mysqli_fetch_assoc($result);
print json_encode($toSend);
}
and JS
$(document).on('click', '.editButton', function () {
var post_id = $(this).parent().data('id');
// console.log(post_id);
var self = this;
$.getJSON(settings.server, {post_id: post_id}, function(data){
var editableText = $('<textarea class="editPostBody">' + data.body + '</textarea>');
console.log(post_id);
$(".post").parent().replaceWith(editableText);
});

Get values of all selected checkboxes and add them to Query String

I will try to be as brief and objective as possible. I'm developing a shopping cart system and for some products categories I need to create checkboxes that corresponds to the additional products that can be added for a single product and the amount of it. I have one script to display the products by category, and if category id match with the specified number id, the additional products are recovered from the database table additionals and displayed in checkboxes with their price in the row of the product that belong to that category. In my page products.php I have the following code to display my products from database:
$sql = "SELECT p.product_id, p.product_name, p.product_price,
p.category_id, c.category_name FROM products p, categories c WHERE c.category_id = p.category_id ORDER BY p.category_id, p.product_name";
$stmt = $connection->prepare($sql);
$stmt->execute();
$sql2 = "SELECT additional_id, additional_name, additional_price FROM additionals ORDER BY additional_name";
$stmt2 = $connection->prepare($sql2);
$stmt2->execute();
$num = $stmt->rowCount();
$category = null;
if($num>0)
{
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
if($category != $category_id)
{
if(!is_null($category)) { echo "</table>"; }
echo "<h1>{$category_name}</h1>
<table>
<tr>
<th>NAME</th>
<th>PRICE</th>
<th>QUANTITY</th>";
if($category_id == 1) echo" <th>ADDITIONALS</th>";
echo "</tr>";
$category = $category_id;
}
echo "
<tr>
<td>
<div class='product-id' style='display: none'>{$product_id}</div>
<div class='product-name'>{$product_name}</div></td>
<td>${$product_price}
</td>
<td>
<input type='number' name='quantity' value='1' min='1' max='20'/>
</td>";
if($category_id == 1)
{
echo "<td>";
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC))
{
extract($row);
echo "
<input type='checkbox' name='acr[]' value='{$additional_id}'/>{$additional_name} - ${$additional_price} <input type='number' name='quantity_acr[]' value='1' min='1' max='5'/><br/>
";
}
echo "</td>";
}
echo "<td>
<form class='add'>
<button type='submit'>Add</button>
</form>
</td>
</tr>";
}
echo "</table>";
}
With this code, my output is something like this:
http://i.imgur.com/1mEPljR.png
The category id 1 corresponds to the Food category so, the additionals column will be displayed.
I use this jQuery code to get the values and add them to a Query String:
$(document).ready(function()
{
$('.add').on('submit', function()
{
var product_id = $(this).closest('tr').find('.product-id').text();
var product_name = $(this).closest('tr').find('.product-name').text();
var quantity = $(this).closest('tr').find('input').val();
window.location.href = "add_to_cart.php?product_id=" + product_id + "&product_name=" + product_name + "&quantity=" + quantity;
return false;
});
});
And here is my problem. I have no idea of how to store the additional selected checkboxes products and their respective quantities in the Query String too! In add_to_cart.php I have the following code to get the variables from Query String, compare them in database and add the product to the SESSION:
if (isset($_GET['product_id']) && $_GET['product_id'] != "")
{
if(isset($_SESSION['cart']))
{
$count = count($_SESSION['cart']);
$product_id_session = $count++;
}
else
{
$product_id_session = 0;
}
$product_id = isset($_GET['product_id']) ? $_GET['product_id'] : "";
$product_name = isset($_GET['product_name']) ? $_GET['product_name'] : "";
$quantity = isset($_GET['quantity']) ? $_GET['quantity'] : "";
$sql = "SELECT * FROM products WHERE product_id LIKE '{$product_id}' AND product_name LIKE '{$product_name}' LIMIT 1";
$stmt = $connection->prepare($sql);
$stmt->execute();
$num = $stmt->rowCount();
if($num == 1)
{
if($quantity <= 0 || $quantity > 20)
{
header('Location: products.php?action=invalidquantity&product_name=' . $product_name);
}
else if(!isset($_SESSION['cart']))
{
$_SESSION['cart'] = array();
}
if(isset($_SESSION['cart']))
{
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$columns = array
(
'product_id_session' => $product_id_session,
'product_id' => $product_id,
'product_name' => $product_name,
'product_price' => $product_price,
'quantity' => $quantity
);
}
$_SESSION['cart'][$product_id_session] = $columns;
header('Location: products.php?action=added&product_name=' . $product_name);
}
}
else
{
redirect_to("products.php");
}
}
I need to do the same with the selected checkboxes! Compare them in database with additional_id and insert the name and price of them in the SESSION in the respective product array, but I do not know how to do this. I hope you understood what I want to do. I'm trying this all day but my current knowledge does not allow me to pass beyond this point. I humbly ask someone to help me.
The name of the input field is acr[]. This means you will have a numerical array inside $_GET['acr'] assuming the submit method is GET.
So you'll have $_GET['acr'][0], $_GET['acr'][1], etc.
You can always use var_dump($_GET) to see all the input values.
It might make more sense for you to use a unique identifier inside the brackets for each product type.
For example use name acr[garlic] or acr[01234] signifying a product ID.
try this : http://jsfiddle.net/zkky5c0f/
$(document).ready(function(){
var allCheckbox = '';
$('input[type=\"checkbox\"]').each(function(){
if(allCheckbox !== ''){
allCheckbox += '-' + $(this).val();
}else{
allCheckbox += $(this).val();
}
});
alert(allCheckbox);
});
In your code it would be like:
$(document).ready(function()
{
$('.add').on('submit', function()
{
var product_id = $(this).closest('tr').find('.product-id').text();
var product_name = $(this).closest('tr').find('.product-name').text();
var quantity = $(this).closest('tr').find('input').val();
var allCheckbox = '';
$('input[type=\"checkbox\"]').each(function(){
if(allCheckbox !== ''){
allCheckbox += '-' + $(this).val();
}else{
allCheckbox += $(this).val();
}
});
window.location.href = "add_to_cart.php?product_id=" + product_id + "&product_name=" + product_name + "&quantity=" + quantity + "&checkbox=" + allCheckbox;
return false;
});
});
Then in PHP you can simply explode the string over -
example :
$checkbox = explode($_GET['checkbox']);
hope this helps :)

Categories