AJAX POST not working, php doesn't create session - javascript

I want to send id of element to php and create session for this.
This is piece from php file:
<?php
$sql = "SELECT id FROM products";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
?>
<tr class="table-manufacture-tr">
<td class="table-manufacture-td-statys">
<div class="warehouse-window-content-dropdown-plus2 plus">
<a class="open_item" data-id=<?php echo "\"".$row['p_id']."\"";?>
style="text-decoration: none; color: #D3D3D3;">Click</a>
</div>
</td>
</tr>
<?php
}
?>
And in this file javascript code:
$(document).on('click', '.open_item', function(event){
var data_item = this.getAttribute("data-id");
$.ajax({
url: 'get_id.php',
type: 'POST',
data-type: 'json',
data: { id: data_item },
contentType: 'application/x-www-form-urlencoded',
success: function(data){
console.log(data);
},
error: function(){
console.log("not working");
}
});
});
This is get_id.php:
<?php
session_start();
$_SESSION['item_id'] = json_encode($_POST);
header("Content-Type: application/json", true);
?>
I have tried also without content types and without json. "var data_item" prints id correct, but php doesn't create session and in console also clear(nothing).

The reason that you are not getting data in session is, you are not assigning proper value to session. Also it should be json_decode not json_encode.
replace
$_SESSION['item_id'] = json_encode($_POST);
with
if (!empty($_POST['id'])) {
$_SESSION['item_id'] = json_decode($_POST['id']); // use json_decode
}

It seems to me that you are making some small mistake in your code like you are echoing $row['p_id'] while your query should return id instead p_id also you are making mistake in ajax you are sending data-type JavaScript assuming your code is subtracting so try to use this code i code below.
// modify your php code
<?php
$sql = "SELECT id FROM products";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result)) { ?>
<tr class="table-manufacture-tr">
<td class="table-manufacture-td-statys">
<div class="warehouse-window-content-dropdown-plus2 plus">
<a class="open_item" data-id=<?php echo "\"".$row['id']."\"";?>
style="text-decoration: none; color: #D3D3D3;">Click</a>
</div>
</td>
</tr>
<?php } ?>
// modify your jQuery
$(document).on('click', '.open_item', function(event){
var data_item = $(this).data("id");
$.ajax({
url: 'get_id.php',
type: 'POST',
dataType: 'json',
data: { id: data_item },
success: function(data){
console.log(data);
},
error: function(){
console.log("not working");
}
});
});
<?php
session_start();
header("Content-Type: application/json", true);
$_SESSION['item_id'] = json_encode($_POST["id"]);
echo json_encode(['data_id' => $_SESSION['item_id']]);
?>

You can use
$_SESSION['item_id'] = json_encode($_POST['id']);
instead of
$_SESSION['item_id'] = json_encode($_POST);
this will work fine.

I don't know what you are trying to do, but from your JS, it looks like that you are expecting that the PHP script --which you post some data to it-- to return a json with the data you have just posted in it. In that case, try this, change your get_id.php to be like:
<?php
session_start();
$_SESSION['item_id'] = json_encode($_POST);
header("Content-Type: application/json", true);
echo $_SESSION['item_id'];
?>

I'd troubleshoot this by making sure the click handler is actually going off. Put alert("clicked"); as the first thing in the in the click handler to make sure.
For the meantime, remove the contentType in the json call. Also remove the dataType (data-type) entirely. On the php side, replace the header() line so (as mentioned) the php is just:
session_start();
$_SESSION['item_id'] = $_POST["id"];
echo $_SESSION['item_id'];
Do not use json_encode/decode right now. From your code, it is not needed.

Related

Display content from the database when a div with an ID is clicked (AJAX)

I have a list of divs with unique IDs (they are inserted from my database). When I click on one of them I want to display content from my database in another div. For example, I have a div with class pizza. The query should look like this: SELECT * FROM product WHERE name = 'pizza'. So depending on what div you click you get different content. The code below doesn't work and is incomplete. I was trying to do some research myself, but I couldn't find anything useful.
//head
<script>
$(function () {
$('.product').on('click', function (e) {
e.preventDefault();
$.ajax({
type: "post",
url: 'php/recipe-container.php',
data: new FormData(this),
processData: false,
contentType: false,
success: function(response) {
$(".display_recipe").html(response);
},
error: function () {
}
});
});
});
</script>
//HTML
<div class="product" id="pizza">pizza</div>
<div class="product" id="lasagna">lasagna</div>
<div class="product" id="sushi">sushi</div>
<div class="display_recipe"></div>
// PHP (recipe-container.php)
<?php
function display_recipe(){
$con = mysqli_connect("localhost", "root", "", "cookbook");
$product = "'pizza'"; //just a placeholder
$sql = "SELECT * FROM product WHERE name = $product";
$res = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($res)) {
$name = $row['name'];
$description = $row['description'];
$date = $row['date'];
echo $name;
echo "<br>";
echo $description;
echo "<br>";
echo $date;
echo "<br>";
}
mysqli_close($con);
}
display_recipe();
?>
Right now when I click the button nothing happens, even "pizza" placeholder doesn't work. Is there a simple way to do it?
JS file (AJAX code)
You can get the id attribute on click of the div with the class 'product' as coded below:
jQuery(function () {
jQuery('.product').on('click', function (e) {
var product = jQuery(this).attr('id');
$.ajax({
type: "post",
url: 'php/recipe-container.php',
data: {data:product},
processData: false,
contentType: false,
success: function(response) {
$(".display_recipe").html(response);
}
});
});
});
PHP file: get the posted data in this file use it in a query to fetch the result and return the result to the AJAX success handler as a response.
To fetch the data posted from the ajax in this php file you can use $_POST['data'] as stated below:
$product = $_POST['data'];
Use that variable in your sql query to fetch the result and then change the structure of your response as stated below:
//saving the html response in a variable named "response"
$response = $name.'<br>';
$response .= $description.'<br>';
$response .= $date.'<br>';
//echo response will send the response variable back to the AJAX success handler.
echo $response;

I cannot figure out why my ajax is not sending the data to my php file

I'm having a problem with my Ajax. It seems to not be sending the data to my php file even though it worked properly 2 days ago. HTML:
<form id='comment' action='process.php' method="POST">
<textarea></textarea>
<button type='submit'>Comment</button>
</form>
My ajax code:
$('#comment').submit(function(event) {
var form = $(this);
var method = form.attr('method');
var url = form.attr('action');
info = {
comment: $('textarea').val()
};
console.log(method);
console.log(url);
console.log(info);
$.ajax({
type: method,
url: url,
data: info,
success: function(data){
alert(data);
}
});
event.preventDefault();
});
I'm doing this for a friend and I'm using this exact same Ajax code (slightly modified) on my website and it's working flawlessly.
I think the biggest red flag here is that in my php file I have an if-else that should send an alert in case the textarea is empty but for some reason it's not doing that here even though nothing is getting through. I used console.log on all the variables to see if their values are correct and they are. The alert(data) just returns an empty alert box.
EDIT: As requested, PHP code from process.php
<?php
session_start();
include_once 'db_connection.php';
date_default_timezone_set('Europe/Zagreb');
if(isset($_POST['comment'])){
function SQLInsert($id, $date, $komentar, $conn){
$sql = "INSERT INTO comments (user, date, comment) VALUES ('$id', '$date',
'$comment')";
$conn -> query($sql);
$conn -> close();
}
$id = $_SESSION['username'];
$date = date('Y-m-d H:i:s');
$comment = htmlspecialchars($_POST['comment']);
SQLInsert($id, $date, $komentar, $conn);
} else {
echo '<script>';
echo 'alert("Comment box is empty.");';
echo '</script>';
}
?>
EDIT: Problem solved, thanks for the help everyone.
You are no getting alert because you are no displaying anything as response in php file. Add the insert function out side the if condition too
function SQLInsert($id, $date, $komentar, $conn){
$sql = "INSERT INTO comments (user, date, comment) VALUES ('$id', '$date',
'$comment')";
if($conn -> query($sql)){
return true;
}else{
return false;
}
$conn -> close();
}
if(isset($_POST['comment'])){
$id = $_SESSION['username'];
$date = date('Y-m-d H:i:s');
$comment = htmlspecialchars($_POST['comment']);
$insert = SQLInsert($id, $date, $komentar, $conn);
//On based on insert display the response. After that you will get alert message in ajax
if($insert){
echo 'insert sucess';
die;
}else{
echo 'Error Message';
die;
}
}
<form id='comment' action='process.php' method="POST">
<textarea></textarea>
<button id="submit_button">Comment</button>
</form>
starting from this html you have to trigger your function as:
$("#submit_button").click(function(e){
I have added an id to your button for simplicity and removed the type because it is useless in this case.
If you want to catch the submit event of the form you have to change your html as:
<form id='comment' action='process.php' method="POST">
<textarea></textarea>
<input type='submit'>Comment</button>
</form>
and then you can keep the same javascript
This here is the issue. Have you tried providing a "method" ?
$.ajax({
**type: method,**
method : method,
url: url,
data: info,
success: function(data){
alert(data);
}
});
Also if this doesn't solve it. show me the console output
<form name="fileInfoForm" id='comment' method="post" enctype="multipart/form-data">
<textarea id="textarea"></textarea>
<button type="submit"></button>
</form>
<script type="text/javascript">
$('#comment').submit(function (e) {
e.preventDefault();
var textarea=$('#textarea').val();
var form=document.getElementById('comment');
var fd=new FormData(form);
fd.append('textarea',textarea);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: 'action.php',
data: fd,
dataType: "json",
processData: false,
contentType: false,
cache: false,
success: function (data) {
alert(data);
}
})
});
</script>
in action.php
$textarea= $_POST['textarea'];
echo $textarea;

Ajax Post and retrieve multiple variables

I need help on how to post and retrieve multiple variables using Ajax Post. I actually needed to retrieve the posted variables for SQL query. See below the Ajax Code where i needed to include variable names selschool, selprogram, selsession to the post
<script>
$("#session").change(function()
{
$("#loding2").show();
var id=$(this).val();
var dataString = 'id='+ id;
var selschool=document.getElementById("selectedschool").val();
var selprogram=document.getElementById("selectedprogram").val();
var selsession=document.getElementById("selectedsession").val();
$("#semester").find('option').remove();
$("#class").find('option').remove();
document.getElementById("selectedclass").value= " ";
document.getElementById("selectedsemester").value= " ";
$.ajax
({
type: "POST",
url: "get_class.php",
data: dataString,
cache: false,
success: function(html)
{
$("#loding2").hide();
$("#class").html(html);
}
});
});
</script>
Also see below PHP script where i wanted to use the posted variable for the query;
<?php
include('dbconfig.php');
if($_POST['id'])
{
$id=$_POST['id'];
// Todo: I actually needed something like where session SELECT * FROM class where session_id=$id and program_id="selprogram" and school_id="selschool"
$stmt = $DB_con->prepare("SELECT * FROM class where session_id=$id ");
$stmt->execute(array(':id' => $id));
?><option selected="selected">Select Class :</option>
<?php while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<option value="<?php echo $row['class_id']; ?>"><?php echo $row['class_name']; ?></option>
<?php
}
}
?>
Let me explain the solution
consider the ajax call to demo.php
$.ajax({
url: 'demo.php',
type: 'post',
data: {
'name': 'abc',
'phone': '1234567899'
}, //data is in json form
success: function(res) {
console.log(JSON.parse(res)); //parsing because we will pass the data from demo.php in encoded form you will get it.
}
});
now in demo.php you will access data as $_POST['name'] and $_POST['phone']. lets pass the same to ajax call. will store it in array and will pass it.
<?php
$Arr = [];
$Arr[0] = $_POST['name'];
$Arr[1] = $_POST['phone'];
echo json_encode($Arr);
?>
like this, we can pass data to ajax and can pass the data from PHP file to request.
Hope that you got the result. Thank you.

How to do a AJAX click post on every PHP foreach result

I have read multiple sorts of answers but none works.
what i try to do is to make every result from a PHP foreach loop clickable and then send that data with AJAX to a other PHP file, the problem now is that whatever i do, only the last foreach result always get send and not the result that i clicked on? (without Database)
the loop exist in a function functions.php:
public function getForeachResult ()
{
$response = $this->GetObject($parameters);
include 'template.php';
}
the template that handles the result template.php:
<?php
foreach ($response->Result->List as $key =>$value) {
?><table id="mytable"><tr>
<th>ID</th>
<th>Date</th>
<th>firstname</th>
<th>lastname</th>
</tr>
<?php foreach ($value as $key=>$value) {?>
<tr class="myrow">
<td><?php echo $value->ID; ?></td>
<td><?php echo date("d-m-Y", strtotime($value->Time)); ?></td>
<td><?php echo $value->FullName; ?></td>
<td><?php echo $value->LastName; ?></td>
</tr>
<?php } ?>
</table><br />
<?php } ?>
In template.php the AJAX script is called at the bottom:
<script>
$('.myrow').click(function() {
$.ajax({
type: "POST",
cache: false,
url: "post.php",
data: { action: 'goTo', value: <?php echo $value->ID ?>}
}).done(function( msg ) {
$('.Data').html(msg);
});
});
In post.php where the dat is send i only get the last result of the foreach loop
post.php:
if($_POST['action'] == 'goTo') {
var_dump ($_POST);
}
so how can i make sure AJAX sends the data that i clicked on?
Try:
`<td class="id"><?php echo $value->ID; ?></td>
<script>
$('.myrow').click(function() {
var id = $(this).find('.id').text();
$.ajax({
type: "POST",
cache: false,
url: "post.php",
data: { action: 'goTo', value: $(this).find(td:first).text().trim()}
}).done(function( msg ) {
$('.Data').html(msg);
});
});`
I think your php expression in the data field just hold the last id because you looped in your html but in your ajaxcall your are already in the end of the loop.
Edit: took the comment
So, to explain the why, i think you mess up a little things in your head and that causes a confusion. Your PHP file does send nothing in Ajax to another PHP file. Your PHP file builds an HTML page, and the Javascript in this page sends data in Ajax.
Keep that in mind, that in PHP you build a future JS code that is executed later. If dynamic variables have to be retreived during the Ajax call or for its data to send, it will be JS that will do it, not PHP.
So like others answers suggest, you have to retreive the id in JS, not PHP.
Only you need to do is get the clicked id just like this
$('.myrow').click(function() {
var id = $(this).children("td.first").text();
$.ajax({
type: "POST",
cache: false,
url: "post.php",
data: { action: 'goTo', value: id}
}).done(function( msg ) {
$('.Data').html(msg);
});
It will work fine no need to change your table html
You need use traverse to find the each row value dynamically on click like this
var clicked_row_id = $(this).find('td:first').text().trim();
Data should be send like this
data: { action: 'goTo', value: clicked_row_id }
Update 1 :
$('.myrow').click(function() {
var clicked_row_id = $(this).find('td:first').text().trim();
$.ajax({
type: "POST",
cache: false,
url: "post.php",
data: { action: 'goTo', value:clicked_row_id }
}).done(function( msg ) {
$('.Data').html(msg);
});
});
At the end of foreach loop you will only have last iteration value only in $value->ID; . so when you echo it in js. so it will echo only last value .

Ajax delete data from database function not working

I have created an AJAX that can store and delete data from database. The adding of data is working fine also the delete function is working fine when the page is already refresh but the delete is not working when data is newly added or when the page is not refresh.
This how it works. When a new data is added, the data will display, the user has an option to delete the data or not. The data has a "X" to determine that it is a delete button. Right now, The delete only works when the page is refresh.
This my SAVING script, as you can see if saving is success it displays the data automatically, together with the span that has the delete function.
$("#wordlistsave").click(function()
{
var user = $("#getUser").val();
var title = $("#wordbanktitle").val();
var words = $("#wordbanklist").val();
var postID = $("#getPostID").val();
var ctrtest = 2;
var testBoxDiv = $(document.createElement('div'))
.attr("id", words);
var dataString = 'user='+user+'&title='+title+'&words='+words+'&id='+postID;
<?php if (is_user_logged_in()): ?>
$.ajax({
type: "POST",
url: "<?=plugins_url('wordlistsave.php', __FILE__ )?>",
data: dataString,
cache: false,
success: function(postID)
{
testBoxDiv.css({"margin-bottom":"5px"});
testBoxDiv.after().html('<span id="'+words+'" style="cursor:pointer">x '+postID+'</span>&nbsp&nbsp<input type="checkbox" name="words[]" value="'+ words+ '">'+words );
testBoxDiv.appendTo("#test_container");
ctrtest++;
}
});
<?php else: ?>
alert('Fail.');
<?php endif; ?>
});
This is my delete function , when the user click the "X" span, the data will be deleted, but this only works after the page is refresh.
$("span").click(function()
{
var queryword=$(this).attr('id');
var postIDdel = $("#getPostID").val();
var dataString = 'queryword='+queryword+'&postID1='+postIDdel;
<?php if (is_user_logged_in()): ?>
$.ajax({
type: "POST",
url: "<?=plugins_url('worddelete.php', __FILE__ )?>",
data: dataString,
cache: false,
success: function(html)
{
$('div[id="'+queryword+'"]').remove();
}
});
<?php else: ?>
<?php endif; ?>
});
This is my HTML, the one that holds the querying of data and displaying of data.
<?php
global $wpdb;
$query_wordbanklist = $wpdb->get_results("SELECT meta_value, meta_id FROM wp_postmeta WHERE post_id = '$query_id' AND meta_key = '_wordbanklist'");
if($query_wordbanklist != null)
{
echo "<h3> Wordlist </h3>";
foreach($query_wordbanklist as $gw)
{
?> <div id="<?php echo $gw->meta_value ?>">
<span id="<?php echo $gw->meta_value ?>" style="cursor:pointer">x</span> &nbsp&nbsp<input type="checkbox" name="words[]" value="<?php echo $gw->meta_value ?>"><?php echo $gw->meta_value; ?>
</div>
<?php
}
}
?>
All I wanted to achieve is to make the delete function works right after the data is stored. Right now it only works when the page is refresh. Any idea on this?
Perhaps try this...
$(document).on('click', 'span', function() {
// delete stuff in here
}

Categories

Resources