How to pass dynamically generated div id to ajax? - javascript

Hey i've got some problem.
My website is divided into two columns. On the left is sidebar which contains list of users dynamically generated from database, on the right-hand side should be unique chart generated by javascript framework (ajax) based on user_id. And this chart should be shown after choosing some user from list. The php file live-data.php which is used by this javascript/ajax needs GET parameter. Now it's:
url: "php/live-data.php"
and
$.get("php/live-data.php?Consultar=1", function(UltimosDatos)
but it should be
url: "php/live-data.php?user_id=2"
and
$.get("php/live-data.php?user_id=2&Consultar=1", function(UltimosDatos)
Where 2 is user_id got after clicking some user name from dynamically generated list. The php script live-data.php is ready for GET variable and returns proper json for chart framwork (this javascript shown below). I dont know how to pass div id to this ajax code.
HTML+PHP:
<div id="left" class="pre-scrollable col-lg-3">
<div class="list-group">
<?php include("php/dbSettings.php");
$result = $conn->query("SELECT * FROM user ORDER BY user_id");
if (!$result) {
die(mysqli_error($conn));
}
while ($user = mysqli_fetch_array($result)){
echo '' . $user['firstName'] . " " .$user['lastName'] . '';
}
?>
</div>
</div>
<div id="right" class="col-lg-9">
<div class="tab-content">
<?php include( "php/dbSettings.php");
$result=$ conn->query("SELECT * FROM users ORDER BY user_id");
if (!$result) {
die(mysqli_error($conn));
}
while ($user = mysqli_fetch_array($result)){
echo '<div class="tab-pane" id="'.$user['user_id'].'">
<div id="chart" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
</div>';
} ?>
</div>
</div>
Javascript/Ajax:
<script>
$(function() {
$(document).ready(function() {
var ultimox;
var ultimoy;
$.ajax({
url: "php/live-data.php", //i want this line to be "php/live-data.php?user_id=2" and 2 is variable got from user list onlick
type: 'get',
success: function(DatosRecuperados) {
$.each(DatosRecuperados, function(i, o) {
//some deleted code - unimportant
});
//some deleted code - unimportant
$('#chart').highcharts({
//draws chart
});
}
});
});
setInterval(function() {
$.get("php/live-data.php?Consultar=1", function(UltimosDatos) { //i want this line to be "php/live-data.php?php/live-data.php?Consultar=1&user_id=2" and 2 is variable got from user list onlick
//updates chart
}
});
}, 1000);
//some deleted code - unimportant
});
</script>
I hope someone can help me on my way.
Thanks, Paul

It looks like the hash will be set to the user id when the anchor is clicked, based on this <a href="#'.$user['user_id'].'" so you could read the hash value and pass it as data on the request. Either this:
$.ajax({
url: "php/live-data.php?user_id=" + window.location.hash.substr(1),
type: 'get',
success: function(DatosRecuperados) {
// ...
}
});
or this:
var dataObj = {};
dataObj['user_id'] = window.location.hash.substr(1); //create a data object to pass on query string, set user id value
$.ajax({
url: "php/live-data.php",
type: 'get',
data: dataObj, //pass object with request
success: function(DatosRecuperados) {
// ...
}
});

Related

Ajax update issues (SQL and extensions)

I have an ajax update feature with some specific issues, I am sure this just needs some tweaking before it will work out 100%.
I will summarize the issues below as clearly as I can.
I have two files that interact with each other:
orders.php
orders-claimed.vc.php
my ajax is trying to update a table int value based on the button clicked. NO=0, YES=1, CANCELLED=2.
orders.php
start of the page
<?php
session_start();
require_once('orders-claimed.vc.php');
?>
table column of the buttons:
<td data-target="scheduled">
<input id='userId' type='hidden'/>
<?php
if ($rowOrder['scheduled'] == 1) {
?>
<button class="btn-success">YES</button>
<?php
} else if ($rowOrder['scheduled'] == 0) {
?>
<button class="btn-danger">NO</button>
<?php
} else if ($rowOrder['scheduled'] == 2) {
?>
<button class="btn-warning">CANCELLED</button>
<?php
}
?>
</td>
modal used for interaction with the table
<!-- Modal content-->
<div class="modal-content" style="width: 300px; margin: 0 auto;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<div class="form-group">
YES<br>
NO<br>
CANCEL
</div>
</div>
</div>
</div>
ajax code
<script>
$(document).ready(function(){
// append values in input fields
$(document).on('click','a[data-role=update]',function(){
var id = $(this).data('id');
var scheduled = $('#'+id).children('td[data-target=scheduled]').text();
$('#userId').val(id);
$('#myModal').modal('toggle');
});
// now create event to get data from fields and update in database
$('#update_no').click(function(){
var id = $('#userId').val();
var scheduled = 0;
$.ajax({
url : 'orders-claimed.vc.php',
method : 'post',
data : {scheduled: scheduled , id: id},
success : function(response){
// now update user record in table
$('#'+id).children('td[data-target=scheduled]').html('<button class="btn-danger">NO</button>');
$('#myModal').modal('toggle');
}
});
});
$('#update_yes').click(function(){
var id = $('#userId').val();
var scheduled = 1;
$.ajax({
url : 'orders-claimed.vc.php',
method : 'post',
data : {scheduled: scheduled , id: id},
success : function(response){
// now update user record in table
$('#'+id).children('td[data-target=scheduled]').html('<button class="btn-success">YES</button>');
$('#myModal').modal('toggle');
}
});
});
$('#update_cancelled').click(function(){
var id = $('#userId').val();
var scheduled = 2;
$.ajax({
url : 'orders-claimed.vc.php',
method : 'post',
data : {scheduled: scheduled , id: id},
success : function(response){
// now update user record in table
$('#'+id).children('td[data-target=scheduled]').html('<button class="btn-warning">CANCELLED</button>');
$('#myModal').modal('toggle');
}
});
}); });
</script>
Note that all code above are all in the same file (orders.php)
table column UI
modal
SQL table name "order"
these are my extensions in the page. most are being stored in a folder and are being linked.
<script src="../_lib/v/jquery.slim.min.js"></script>
<script src="../_lib/v/bootstrap/js/bootstrap.js"></script>
<script src="../_lib/v/jquery-ui/jquery-ui.js"></script>
<script src="../_lib/v/jscolor/jscolor.js"></script>
<script src="js/cms.js"></script>
<link href="../_lib/v/bootstrap/css/bootstrap.min.css" rel="stylesheet">
Ajax does not function under slim.min.js and gets the "not a function error", so I changed it to the regular version of jquery from https://code.jquery.com/jquery-3.3.1.js
PROBLEM
If I switch to the full version of jquery, the column updates but the session (the logged in user) ends and logs out automatically. Why is this happening?
My second problem is in the orders-claimed.vc.php file
db.php
<?php
class config_db {
public function init() {
$db = new PDO('*MY DATABASE DETAILS GO HERE*');
date_default_timezone_set('Hongkong');
return $db;
}
}
?>
orders.claimed.vs.php
connecting to the database:
$routePath = "../";
require_once($routePath . "_config/db.php");
$dbConfig = new config_db();
$db = $dbConfig->init();
SQL update
if(isset($_POST['id'])){
$orderid = $_POST['id'];
$scheduled = $_POST['scheduled'];
$stmt = $db->prepare("UPDATE order SET scheduled = '$scheduled' WHERE orderid = '$orderid'");
$stmt->execute(); }
PROBLEM
the SQL code above does not update the table (the one shown in the screenshot, but ajax just updates the look of the button from the success functions (It goes back to its original value when the page refreshes). I would like to know what is the issue. It should be connecting to the buttons since it is using "if(isset($_POST['id']))".
I hope I have provided a clear explanation to my two problems, thank you for any help.
UPDATE
I used the following code below to check for an error on the button update:
console.log( 'scheduled: ' + scheduled + ' orderid: ' + $('#userId').val() );
when the button updates and the page refreshes that also logs out the session, i get the following error:
jquery-ui.js:1951 Uncaught TypeError: Cannot read property 'step' of undefined
at String.<anonymous> (jquery-ui.js:1951)
at each (jquery.slim.min.js:2)
at Function.color.hook (jquery-ui.js:1913)
at jquery-ui.js:1963
at jquery-ui.js:2005
at jquery-ui.js:14
at jquery-ui.js:16
From what you have listed, I think that you might have "session_destroy()" somewhere in your php files (though it might not be put up here). Try commenting that out and see if the session ends or not. Hope it helps you :).

How to use data from one HTML page to retrieve data to be used on another HTML page using ajax

I would like to use the 'sID' in the first HTML form to retrieve data from the database and then use the data retrieved from the database on the second HTML page. I can do this with just php, but I just can't figure out how to do it using ajax.
I'm really new to javascript/ajax so please be gentle with your answers :)
HTML 1
<div class="moreR">
<form action="moreR_2.0.php" method="GET">
<input type="hidden" name="sID[]" value="a_certain_ID"/>
<input type="image" src="Icons/PNG/greater_than.png" alt="submit"/>
</form>
</div>
PHP (moreR_2.0.php)
<?php
include ('session_start.php');
include ('db_connect_mO.php');
if (isset($_GET['sID'])) {
foreach($_GET['sID'] as $sID) {
}
}
$sql = mysqli_query($con, "SELECT * FROM mo WHERE sID=$sID");
$row = mysqli_fetch_array($sql);
while ($row = mysqli_fetch_assoc($sql))
{
$test[]= array(
'pZero'=> $row['pZero'],
'pZero_Gname'=> $row['gZero_key'],
);
}
header('Content-Type: application/json');
echo json_encode ($test);
//detailed error reporting
if (!$sql)
{
echo 'MySQL Error: ' . mysqli_error($db);
exit;
}
?>
JavaScript
$(document).ready(function() {
"use strict";
function connect2mR() {
$.ajax({
url:"moreR_2.0.php",
type: "GET",
data:'sID',
dataType:"json",
//async:false,
success:function(data)
{
$('#pZero').html('<img src="rPlanets/' + this.gZero + '.png" alt=""/>');
$('#pZero_keys').html(this.gZero_key);
}, //success
}); //end of ajax
} //end of function
if (window.attachEvent) {window.attachEvent('onload', connect2mR);}
else if (window.addEventListener) {window.addEventListener('load', connect2mR, false);}
else {document.addEventListener('load', connect2mR, false);}
});
HTML 2
<section class="moreR_section">
<div style="width:20%;"><div id="pZero"></div></div>
<div class="moreR_g" style="margin-left:26%" id="pZero_keys"></div>
</section>
What i'm trying to do is; start from HTML 1, collect sID -> then PHP/JS use sID from HTML 1 to get data from database -> then use the result from database on HTML 2. At the moment i'm struggling on how to make this process work. Can't figure out how to start from HTML 1 and end up in HTML 2.
You are not fetching the data from the input element at all.. change your ajax code to below.
$.ajax({
url:"moreR_2.0.php",
type: "GET",
data:{sID: $('input[name="sID[]"]').val()}, // this is the change
dataType:"json",
//async:false,
success:function(data)
{
$('#pZero').html('<img src="rPlanets/' + this.gZero + '.png" alt=""/>');
$('#pZero_keys').html(this.gZero_key);
}, //success
}); //end of ajax
Edit 1: you can use localstorage to save data and retrieve from there when ever required. So you can do as below
In your HTML 1 write this.
localStorage.setItem('sID', JSON.stringify( $('input[name="sID[]"]').val()));
And in HTML 2 you can access the value by reading it from the local storage like below,
var sIDofHTML1 = JSON.parse(localStorage.getItem('sID'));
You will have to update the ajax as below.
data:'sID', // this has to change to data:'sID='+sID,
$.ajax({
url:"moreR_2.0.php",
type: "GET",
data:'sID', // this has to change to data:'sID='+sID,
dataType:"json",
//async:false,
success:function(data)
{
$('#pZero').html('<img src="rPlanets/' + this.gZero + '.png" alt=""/>');
$('#pZero_keys').html(this.gZero_key);
}, //success
}); //end of ajax

how can I make one button correspond to different clicked div html jquery php?

You can see my code below. I face a challenge that I don't know how to use one button to correspond different click. On the php, if I put the button inside the foreach loop, it will create a lot of button, that's not what I want. In the js, if I put the on.click button inside the foreach elements loop, it will also create a lot of on.click button, so I click one button, it will run many times depends on the number of label_name. I think about addClass, if I clicked the heart div, I use js to add a class, and then get the attr('id') inside button.on.(click), so I can differentiate them in my server php and mysql can request the correspond data. But the problem is that if a user click every div, then every div add classes, then problem again.
var current_page = 1;
var elements_body = {
"heart": "1",
"eye": "2",
"ear_nose_throat": "3",
"hand_foot_mouth": "4"
};
jQuery.each(elements_body, function (label_name, label_num) {
var disease_label = $('#' + label_name + '_d');
disease_label.on('click', function () {
var data = {
action: 'body_part_keyword', //wordpress loading url
postSearchNonce: MyAjaxSearch.postSearchNonce,
current_page: current_page,
label_name: label_name //this label_name will differentiate data that need to request from mysql in the action.php
};
$.ajax({
url: MyAjaxSearch.ajaxurl,
type: 'POST',
cache: false,
data: data,
success: function (data) {
disease_menu_result.append(data);
current_page++
}
}); //ajax
});
}); //jQuery.each
$('#loadmorebutton_body').on('click', function () {
//I dont know how can I make this button to correspond above code
});
<div id="disease_menu">
<?php
$arr = Array(
'heart'=>'heart',
'eye'=>'eye',
'ear_nose_throat'=>'ear nose throat',
'hand_foot_mouth'=>'hand foot mouth'
);
foreach ($arr as $key=>$value) {
?>
<div class="disease_li" id="disease_li_<?php echo $key;?>">
<span class="disease_span" id="<?php echo $key;?>_d"><label>(<?php echo $value;?>)</label>diseases</span>
</div>
<!--disease_li-->
<?php }?>
</div>
<!--disease_menu-->
<button id="loadmorebutton_body">Load More</button>
Use javascript functions :
function MyFunction() {
jQuery.each( elements_body, function( label_name, label_num) {
var disease_label= $('#'+ label_name + '_d');
disease_label.on('click',function(){
var data={
action: 'body_part_keyword',//wordpress loading url
postSearchNonce : MyAjaxSearch.postSearchNonce,
current_page:current_page,
label_name:label_name//this label_name will differentiate data that need to request from mysql in the action.php
};
$.ajax({
url: MyAjaxSearch.ajaxurl,
type:'POST',
cache: false,
data: data,
success: function(data){
disease_menu_result.append(data);
current_page++
}
});//ajax
});
});
}
$('#loadmorebutton_body').on('click',function(){
MyFunction();
}

JQuery Value to PHP with Ajax?

My Website has a Video Player with a random Playlist and a Comments List.
All Comments ever written are loaded. Now I want to change the comments ID, everytime a new Video starts, so that the Site shows only comments for this Video.
The Player is set up in Javascript and has an on Ready Function, that fires an ajax function.
The Comments are set up as a php line with a $value.
This is my code:
<div id="comments">
<?php
$commentsID= 3; //Testnumber 3 shows all comments to video 3
Comment::getCommentSystem($commentsID);
?>
</div>
<script>
onReady: function(event) {
videoID; // actual videoID
//and here comes some Ajax Magic, to tell $commentsID = videoID, but how?
// My example doesn't work because it's my first try with Ajax whoohooo
$.ajax({
type: "GET",
url: "index.php",
data: videoID,
success: function(videoID){
$('#comments').empty(); // Clear Testnumber'n stuff
$(' <?php
$commentsID= videoID;
Comment::getCommentSystem($commentsID);
?>
').appendTo('#comments'); // rewrite the comments Div with the videoID
}
});
</script>
EDIT:
Now my code looks like this:
<div id="comments">
</div>
<script>
[...]
onReady: function(event) {
videoID; // actual videoID
$.ajax({
type: "GET",
url: "get_comments.php?videoId=" + videoID,
success: function(response){
$('#comments').html(response);
}
});
}
[...]
</script>
get_comments.php
<?php
session_start();
include "comment.class.php";
$videoID = $_GET["videoId"];
$comments = Comment::getCommentSystem($videoID);
return($comments);
?>
and it produces this:
<div id="comments">
<!-- The Form to add a comment ( always display none ) -->
<div style="display:none;">
<div class="comment-post comment-child">
<form id="addCommentForm" action="" method="post">
<!-- The Form container, that shows the Form comment -->
<!-- ( should be visible - maybe session fail? ) -->
<div class="comment-container" style="display:none;">
<div class="comment-content">
<!-- all comments to videoID 3 -->
<ul class="comment-list-3">
</div>
Do not send it index.php, send request to another endpoint like get_comments.php,
<script>
onReady: function(event) {
videoID; // actual videoID
//and here comes some Ajax Magic, to tell $commentsID = videoID, but how?
// My example doesn't work because it's my first try with Ajax whoohooo
$.ajax({
type: "GET",
url: "get_comments.php?videoId=" + videoID,
success: function(response){
$('.comment-list-3').empty(); // Clear Testnumber'n stuff
var html = '';
$.each(response, function(i, item) {
// Do your html here. I assume, your comment object has a field "text". Update it according too your need
html += '<div>' + item.text + '</div>';
});
$('.comment-list-3').html(html); // rewrite the comments Div with the videoID
}
});
</script>
and in your get_comments.php;
<?php
$videoID = $_GET["videoId"];
$comments = Comment::getCommentSystem($videoID); // Let say this is array
echo json_encode($comments);
?>
As Hüseyin BABAL mentioned you could use $_GET to recieve a video id and then prepare the page. Yuou could store the $_GET value in an attribute (for example: data-video-id="3") so you can read it using JS/jQUery. It is possible to fetch URL parts using JS but it is a bit more difficult.
WARNING: If you work with user input (like $_GET and $_POST) ALWAYS validate input.

Reload a div on AJAX request

I want to send an ajax request and reload the div from which it came. As of current I am getting the proper request but it isn't reloading the div - it just makes it blank (nothing there). And I have to refresh the page to see my data. How can I get it to display properly?
my add_amenity.php page works fine
*also, don't be suspicious of the var id = $('.editblock').find('#id').val(); It gets the value it needs and sends it to add_amenity.php just fine. My only problem is getting the div to reload on an add.
php and html on same page as JS below. (This is not add_amenity.php)
<div class="editunitamenities">
<?php
require_once('config/db.php');
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$query = 'SELECT id, unit, amenities FROM amenities WHERE unit = '.mysqli_real_escape_string($con, $_GET['id']).'';
$result = mysqli_query($con, $query);
while ($row= mysqli_fetch_assoc($result))
{
echo '<div class="checkbox"><input type="checkbox" id="'.$row['id'].'" checked
class="amenitiescheckbox" name="'.$row['amenities'].'" value="'.$row['amenities'].'" />
<label title="'.$row['unit'].'">'.$row['amenities'].'</label></div>';
}
mysqli_close($con);
?>
<div class="newamenitywrap">
<div class="button"><button class="smallbutton" id="addamenity">New</button></div>
<div><input type="text" name="amenity" style="width:120px;" id="amenity" placeholder="Amenity Name" /></div>
</div>
</div> <!-- end editunitamenities -->
Here is the AJAX request
<script>
$('#addamenity').click(function() {
var id = $('.editblock').find('#id').val();
var amenity = $( "#amenity" ).val();
var dataString ={id:id,amenity:amenity};
console.log(dataString);
if (amenity != '')
{
$.ajax({
type: "POST",
url: "classes/add_amenities.php",
data: dataString,
cache: false,
async:false,
success: function(html)
{
$('.editunitamenities').html(html);
}
});
}
});
</script>
I suggest the following changes:
(1) Remove the following line. I can't imagine it is doing what you expect it to because it will try to make an ajax call to the URL ".editunitamenities", and this may be what is blanking out the <div>.
$(".editunitamenities").load('.editunitamenities');
(2) Add the following property to the ajax options. This will prevent jQuery from converting the data value into an object if it thinks it looks like JSON.
dataType: 'html'
(3) Add the following line to the success handler to check what is getting returned.
console.log(data);
The following line also appears suspicious to me, but since you say the request is correct, I will assume it is working as it should.
var id = $('.editblock').find('#id').val();
I find the above line suspicious because there would have to be an element with an id value equal to "id". Also, since you are trying to find that element within another element, it makes me think you have multiple such elements, but id values should be unique throughout the entire page.
It would be useful to see the code for classes/add_amenities.php to see exactly what's going on, but you should check one or more of the following:
in the PHP you use $_GET['id'] and the ajax request is type: "POST"
also I see in your ajax request you do $('.editblock').find('#id').val(); but I see no element in your markup with class editblock or with id id - so either these nodes are not in the markup you posted or you should change you js call
the second line in the success function is redundant
I found a workaround. None of the other suggestions worked for me.
I made another page called display_amenities.php:
<?php
require_once('../config/db.php');
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$query = 'SELECT id, unit, amenities FROM amenities WHERE unit = '.mysqli_real_escape_string($con, $_GET['id']).'';
$result = mysqli_query($con, $query);
while ($row= mysqli_fetch_assoc($result))
{
echo '<div class="checkbox"><input type="checkbox" id="'.$row['id'].'" checked
class="amenitiescheckbox" name="'.$row['amenities'].'" value="'.$row['unit'].'" />
<label title="'.$row['unit'].'">'.$row['amenities'].'</label></div>';
}
mysqli_close($con);
?>
<div class="newamenitywrap">
<div class="button"><button class="smallbutton" id="addamenity">New</button></div>
<div><input type="text" name="amenity" style="width:120px;" id="amenity" placeholder="Amenity Name" /></div>
</div>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"> </script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$('#addamenity').click(function() {
var id = $('.editblock').find('#id').val();
var amenity = $( "#amenity" ).val();
var dataString ={id:id,amenity:amenity};
console.log(dataString);
if (amenity != '')
{
$.ajax({
type: "POST",
url: "classes/add_amenities.php",
data: dataString,
cache: false,
async:false,
success: function(html)
{
//$('.editunitamenities').html(html);
$('.editunitamenities').load('classes/display_amenities.php?id='+id);
}
});
}
});
</script>
And then called it from the main page:
$('#addamenity').click(function() {
var id = $('.editblock').find('#id').val();
var amenity = $( "#amenity" ).val();
var dataString ={id:id,amenity:amenity};
console.log(dataString);
if (amenity != '')
{
$.ajax({
type: "POST",
url: "classes/add_amenities.php",
data: dataString,
cache: false,
async:false,
success: function(html)
{
//$('.editunitamenities').html(html);
$('.editunitamenities').load('classes/display_amenities.php?id='+id);
}
});
//$('.editunitamenities').load('.editunitamenities');
}
});
Definitely not ideal, but it works.

Categories

Resources