Setting a session variable in PHP using AJAX - javascript

After a user clicks a div this javascript function runs:
$('.test').click(function(e)
{
e.preventDefault();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {"id": "<?php echo $rows['id']?>"},
success:function(data){
window.location.href = 'index.php';
}
});
});
I want to pass in an ID associated with the div the user clicks into my ajax.php file where this code runs:
<?php
session_start();
//connect to db here
$_SESSION['id'] = $_POST['id'];
?>
However this is not working. To expand further what I did to pass get the rows['id'] variable is run this SQL code:
$sql_select = "SELECT id FROM ids WHERE id = '$id'";
$results_select = $conn->query($sql_select);
I then outputted a bunch of divs with id's corresponding to them:
<?php
while ($select_rows = mysqli_fetch_array($results_select))
{
echo "<div class = 'test'></div>";
}
?>
Does anyone know how I can accomplish this?

Use data attributes:
Try:
<?php
while ($select_rows = mysqli_fetch_array($results_select))
{
echo "<div data-id='".$rows['id']."' class = 'test'></div>";
}
?>
js:
$('.test').click(function(e)
{
e.preventDefault();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {"id": $(this).attr('data-id')},//fetch the data attribute
success:function(data){
window.location.href = 'index.php';
}
});
});

Please check your JS code for data: {"id": "<?php echo $rows['id']?>"}. This line may not be able to pass your actual value so store it into div with id attribute and get it by jQuery and pass it.
JS:
$('.test').click(function(e)
{
dataValue = $(this).attr('id');//Get user clicked div id attribute value...
e.preventDefault();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {"id": dataValue},
success:function(data){
window.location.href = 'index.php';
}
});
});
PHP:
With above JS code you need to make some change for PHP code as well:
while ($select_rows = mysqli_fetch_array($results_select))
{
echo "<div class = 'test' id='". $select_rows['id'] ."'></div>";
}
Please confirm this code by print_r($_POST); on AJAX post handler page. This will print the POST data requested by AJAX code.
Let me know if there is any concern regarding this.

Related

How to do an Ajax request to parse table row column data to PHP on click of table row?

I have a datatable with an numeric value in the first column of the <tr><td> row.
I want to click on that row and parse this value to a PHP page in order to assign this number into a session.
I have below code snippet, but this isn't do the push.
selected is the class of the row when I click on it.
$(".selected td").click(function(parsegroupid) {
var group_id = $(this).attr('data');
$.ajax({
url: "./includes/indexPage/assign_session.php",
type: "post",
data: {
id: group_id
},
success: function(response) {
}
});
});
This is my PHP code:
<?php
ob_start();
if (session_id() == '') {
session_start();
}
$GrpID = $_POST['group_id'];
$_SESSION['grp'] = $GrpID;
ob_end_flush();
?>
Below is a screenshot of the row when selected.
First, you need to check if the ajax call is made.
Based on your previous comments, it seems this is not happening.
You can try to specify the table id in your onclick event:
$("#table_id tbody").on( 'click', 'tr', function (){
var group_id = $(this).find("td:first-child").text();
$.ajax({
url: "./includes/indexPage/assign_session.php",
type: "post",
data: {
id: group_id
},
success: function(response) {
}
});
}
Make the change in your assign_session.php file your have pass the value in id and trying to access value of group_id.
Instead of $_POST['group_id'] use $_POST['id']
change the code like below
<?php
ob_start();
if (session_id() == '') {
session_start();
}
$GrpID = $_POST['id']; // change
$_SESSION['grp'] = $GrpID;
ob_end_flush();
?>
If the ID is in the cell of the and not as an attribute, try this:
var group_id = $(this).html();
Go with this code.
You are posting id and group_id is your value and you added $_POST['group_id'] instead of $_POST['id'].
Hope this will helps you :)
<?php
ob_start();
if (session_id() == '') {
session_start();
}
$GrpID = $_POST['id']; // Change here
$_SESSION['grp'] = $GrpID;
ob_end_flush();
?>

How to get id and type in php foreach loop and send to server via ajax?

So i have 2 files index.php and changeLikeDislike.php. I think the issue is where javascript is trying to get the type and id but I do not know how I would go about that. My javascript function is being called in the foreach->li->divs. It was working before like this: data: dataString, but I added schoolId into data of ajax as well so it's like this now data: {dataString:dataString, schoolId:schoolId},
index.php
<?php
$last_id = 0;
foreach ($list as $rs) {
$last_id = $rs['id']; // keep the last id for the paging
?>
<li>
<div style="width:100%; color:#000;">
<?php echo '<div class="product_like thumb-div"><img src="like.png" class="rating-image " onclick=changeLikeDislike("like","'.$rs['id'].'")> <br><span id="product_like_'.$rs['id'].'">'.$rs['pLike'].'</span></div>';?>
<?php echo '<div class="product_dislike"><img src="dislike.png" class="rating-image" onclick=changeLikeDislike("dislike","'.$rs['id'].'")><br> <span id="product_dislike_'.$rs['id'].'">'.$rs['pDislike'].'</span></div>';?>
</div>
</li>
<?php
}
?>
<script type="text/javascript">
//begin like and dislike
function changeLikeDislike(type,id){
var dataString = 'id='+ id + '&type=' + type;
$.ajax({
type: "POST",
url: "changeLikeDislike.php",
data: {dataString:dataString, schoolId:schoolId},
cache: false,
success: function(result){
if(result){
console.log('working');
}
}
});//end ajax
}
schoolId works in data but not dataString in ajax How would i go about grabbing those. My php file for reference:
//checks if school page id was brought and stores into variable
if (isset($_POST['schoolId'])) {
$schoolIdFinal = $_POST['schoolId'];
}else {
echo "nope";
}
if (isset($_POST['type'])) {
$type = $_POST['type'];
}else {
echo "nope type";
}
if (isset($_POST['id'])) {
$id = $_POST['id'];
}else {
echo "nope id";
}
my page is echoing out "nope type nope id"
Please change
data: {dataString:dataString, schoolId:schoolId},
to
data: {type:type, id:id, schoolId:schoolId},
to match the params to your PHP script.
data can either be a query string (like your dataString) OR a json struct (like {type:type, id:id, schoolId:schoolId}).
See the documentation of jQuery.ajax():
"The data option can contain either a query string of the form key1=value1&key2=value2, or an object of the form {key1: 'value1', key2: 'value2'}."
see http://api.jquery.com/jquery.ajax/
The issue is in the data bracket. change
data: {dataString:dataString, schoolId:schoolId}
to
data: {dataString:'dataString', schoolId:'schoolId'}
next time do a print_r of $_REQUEST or $_POST to see what fields are being recognized and in this case it looks like its not detecting anything.

JS Toggle Class

I am stuck on this. I have an ajax function posting to php. The post function is working fine. I just want css to toggle on and off with each click while posting with each click.
When I click the '.fav-btn' button the first time I want 'fav-h' to be added to the class for styling. Also post to the php script.
When I click the '.fav-btn' button the second time I want 'fav-h' to be removed and button returns to original style. Also post again to the php script.
I have tried various things including the .removeclass. My code is below, I am not sure how to get the fav-h class style to be removed on the second click.
$(document).ready(function(){
var pageID = <?php echo $pageID ?>;
var user_id = <?php echo $user_id ?>;
$('.fav-btn').click(function(){
$(this).addClass('fav-h');
$.ajax({
type:"POST",
url:"../ajax.php",
data: { act: 'fav', pageID: pageID, user_id: user_id },
success: function(){
}
});
});
});
$(document).ready(function(){
var pageID = <?php echo $pageID ?>;
var user_id = <?php echo $user_id ?>;
$('.fav-btn fav-h').click(function(){
$('.fav-btn fav-h').removeClass('fav-h');
$.ajax({
type:"POST",
url:"../ajax.php",
data: { act: 'fav', pageID: pageID, user_id: user_id },
success: function(){
}
});
});
});
Use $.toggleClass() to just have one block of code:
$(document).ready(function(){
var pageID = <?php echo $pageID ?>;
var user_id = <?php echo $user_id ?>;
$('.fav-btn').click(function(){
$(this).toggleClass('fav-h');
$.ajax({
type:"POST",
url:"../ajax.php",
data: { act: 'fav', pageID: pageID, user_id: user_id },
success: function(){}
});
});
});
PS: your code was not working because you used $('.fav-btn fav-h'):
<div class="fav-btn">
<fav-h></fav-h> <!-- This is what this selector leads to -->
</div>
instead of the correct selector $('.fav-btn.fav-h'):
<div class="fav-btn fav-h"></div> <!-- Found the right one! -->
It looks like it is the same ajax call either way. You can probably just bind to the button once. Also, you might want to only update the class if the post was successful.
$(document).ready(function(){
var pageID = <?php echo $pageID ?>;
var user_id = <?php echo $user_id ?>;
$('.fav-btn').on('click', function(){
var $t = $(this);
$t.addClass('fav-saving');
$.ajax({
type:"POST",
url:"../ajax.php",
data: { act: 'fav', pageID: pageID, user_id: user_id },
success: function(){
$t.toggleClass('fav-h');
},
complete: function(){
$t.removeClass('fav-saving');
}
});
});
});

Facing on Make Like Unlike Button in php , mysql using ajax calling

I m creating like and unlike button for my website , at my local server i used seprate file it it working fine but when i install at my website then it is not working properly.
I m Fetching some information using this code from url bar
<?php
error_reporting (0);
include "includes/session.php";
include 'database/db.php';
extract($_REQUEST);
if(isset($_GET["i"]))
{
$pid=($_GET['p']);
$lid=($_GET['i']);
}
?>
<?php
$likquery = mysql_query("select * from likes where userid=$id and postid=$lid");
if(mysql_num_rows($likquery)==1){
?>
<a class="unlike" id="<?php echo $lid ?>">UnLike</a> <span class="like_update" id="<?php echo $lid ?>"></span>
<?php }else{?>
<a class="like" id="<?php echo $lid ?>">Like</a>
<?php
}?>
AFTER this I use script
<script src="js/jquery-1.8.3.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$('body').on('click','.like',function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=<?php echo $id ?>';
$.ajax({
type: "POST",
url: "like_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('UnLike').addClass('unlike').removeClass('like');
}
});
})
$('body').on('click','.unlike',function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=<?php echo $id ?>';
$.ajax({
type: "POST",
url: "likeun_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('Like').addClass('like').removeClass('unlike');
}
});
})
});
</script>
And I m not getting any response but when i use
<script src="js/jquery-1.8.3.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$(".like").click(function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=<?php echo $id ?>';
$.ajax({
type: "POST",
url: "like_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('UnLike').addClass('unlike').removeClass('like');
}
});
})
$(".unlike").click(function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=<?php echo $id ?>';
$.ajax({
type: "POST",
url: "likeun_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('Like').addClass('like').removeClass('unlike');
}
});
})
});
</script>
only once it is changing the value
Ok, the second version works only once, because at the beginning, the event is on the button, then you re-render the button by changing it's class and text, so the events get unbinded.
Same is for the 1st version. Jquery says: Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().... If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page.
So re-bind the events after changing the button.
I suggest something like this:
function bindEvents() {
$('.like').off().on('click', function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=' + <?php echo $id ?>;
$.ajax({
type: "POST",
url: "like_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('UnLike').addClass('unlike').removeClass('like');
//rebind events here
bindEvents();
}
});
$('.unlike').off().on('click', function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=' + <?php echo $id ?>;
$.ajax({
type: "POST",
url: "likeun_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('Like').addClass('like').removeClass('unlike');
//rebind events here
bindEvents();
}
});
}
$(document).ready(function(){
bindEvents();
});
Also notice that in var postData = 'postid='+postId+'&uid=<?php echo $id ?>'; code, the php part won't be treated as php. It will be just a string. So replace that part with the following, assuming that the code is located inside a php file:
var postData = 'postid='+postId+'&uid=' + <?php echo $id ?>;

Data from all the dynamically generated input fields doesn't go to database

I regenerate the input fields by calling an external PHP function which generates those fields with the help an ajax function, but the save function doesn't save data from all the fields but only the data from last row is saved to database..
Code for ajax function to regenerate these fields looks like this:
var counter = 0;
function loadfields_addmore(checked)
{
$jd.ajax({
url: "<?php echo JURI::root(); ?>",
type: "POST",
data: {'option':'com_joomd', 'view':'itempanel', 'task':'loadfields', 'typeid':<?php echo $this->cparams->typeid; ?>, 'catid[]':checked, 'id':<?php echo (int)$this->item->id; ?>, "<?php echo jutility::getToken(); ?>":1, 'abase':1}
});
}
For save button that triggers the save process:
function save(task) {
var data = $jd("form[name='<?php echo $array['editform']; ?>']").serializeArray();
$jd.ajax({
url: "<?php echo $url; ?>",
type: "POST",
dataType:"json",
data: data
});
}
The actual save function is like this:
function store()
{
foreach($post['cats'] as $cat) {
$query = 'insert into #__joomd_item_cat values('.$cat.', '.$row->id.')';
$this->_db->setQuery( $query );
}
}
The image shows the form..
The data from all the fields is not going to the database..
If I understand correctly, it seems like some form elements are created on the fly through jQuery. These will not be posted as they are not part of the original source code but were added later.
Use on() to get fields that were created on the fly.
Your parameters will be 'click',buttonid,next static parent of button.

Categories