I'm using jquery ajax in codeigniter framework to load a pop up modal on button click. I pass ajax request to a function in controller and receive some data which should be shown in my pop up modal. Number of labels of the modal is depend on the size of the array received by the ajax request.
I have no idea how to do this. But I tried of passing the size of the received array to a hidden type input field in form created on the pop up modal.
Following is my javascript.
<script type="text/javascript">
$(document).ready(function () {
$(document).on('click','#btn_more', function() {
empId = $('#employeeId').html();
fiter_employees(empId);
});
function fiter_employees(empId){
var empSet ={
empId: empId,
method: 'ajax'
};
var empSentUrl = 'http://localhost/eventmanagementsystem/index.php/employee/get_emp_positions';
$.ajax({
type: 'POST',
dataType: 'json',
url: empSentUrl,
data: empSet,
success: function(data){
$('#modal_pkg1').html(data.empPosition.length)
$('#employeePositions').modal();
}
});
}
});
In my pop up model I used the following codes which is not succeeded.
<div id="employeePositions" class="modal fade">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Employee Name :</h4><br/>
<form>
<?php
for ($i=0; $i < ?>
<input type="hidden" id="modal_pkg1" value="modal_pkg1" />
<?php
; $i++) { ?>
<h4 class="modal-title" id="event_name"></h4>
<?php
} ?>
</form>
Can someone tell me the correct me of doing this please...
Your PHP code has executed the moment you load the page, so when you change the modal_pkg1 value, nothing will happen.
Also, the foor loop itself will not work on load, as it's expecting a number that is not there.
I suggest you do it fully in JS, remove all php code from your script; something like below :
in your Ajax success function :
.success(function(data){
var htmlStr = ''
for(var i=0;i<data.empPosition.length;i++){
htmlStr+='<whatever html element you want to display>'
}
$('form').html(htmlStr) // add the generated html string to the <form> element
$('#employeePositions').modal();
}
Related
I have html page where I want to open dialog by button click and content of dialog should be dynamically generated.
The idea is the following:
I click button
JS(ajax)run my flask route , where http request to other site is executed and then json is returned
The returned json is passed to js (or html), then this json is parsed and according to found information, the elements (images as an example) are displayed in opened dialog
Python:
#app.route('/sales_inventory', methods=['POST'])
def tm_inventory(user):
response = some_function("authKey")
return make_response(jsonify(response)))
HTML:
<button class="inventory">Inventory</button>
<div class="modal">
<div class="modal-content">
<span class="close">×</span>
</div>
</div>
Elements should be generated inside div .modal-content
JS:
$(."inventory").click(function () {
$.ajax({data: {
user: $(this).next().text()
},
type: 'POST',
url: '/sales_inventory'
})
Js is not completed, because I have no idea how should it be
The class name and . should be wrapped by a string quotation. In your code the class indicator . is outside the string quotation.
According to your question your server is responding JSON data, so you should add dataType as JSON of your AJAX. Also add a success callback function which is automatically called when the server response. Of success function there is a parameter data which contains the response data as an object (JSON) and now using this data you can prepare your HTML and set in the certain place of the modal.
JS:
$(".inventory").click(function () {
// ^^^^^^^^^^^^
$.ajax({
data: {
user: $(this).next().text()
},
dataType: 'JSON',
type: 'POST',
url: '/sales_inventory',
success: function(data) {
// var prepared_html = using `data`
// $('.modal-body').html(prepared_html);
}
})
})
HTML:
<div class="modal">
<div class="modal-content">
<span class="close">×</span>
<div class="modal-body">
<p>Modal body text goes here.</p>
</div>
</div>
</div>
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 do you reload a page without re-fresh after sending a javascript variable to PHP via Ajax.
Below is an image of a webpage I'm creating which analyses asset performance.
What I'm trying to do is the following.
When a user selects a test block with in the graph, the selcection box is updated with all subtests within that specific test block. However, I do not want to refresh the page. I have managed to send the the selected tested block to the PHP code via ajax, but can not get ajax to reload the page without a refresh.
Currently, when a test block is selected, the label is return to PHP and is stored in the $_SESSION['label'] variable. This is then used in the panel header #subtest-chart-select. However the label will not update without a page refresh which is what I want to avoid.
Ajax:
$("#test_block_chart").click(
function(evt){
var activePoints = myNewChart.getElementsAtEvent(evt);
if (activePoints[0]) {
var chartData = activePoints[0]['_chart'].config.data;
var idx = activePoints[0]['_index'];
var label = chartData.labels[idx];
//alert(label);
$.ajax(
{
url:'test_performance.php',
type: 'POST',
datatype: 'json',
data: {'label':label}, // post to location.php
success: function(label) {
// success
},
error: function(label) {
alert("There may an error on uploading. Try again later");
}
});
}
});
});`
PHP:
session_start();
if(isset($_POST['label']))
{
$_SESSION['label'] = $_POST['label'];
}
PHP echo HTML
<?php
echo '<div class="row">
<div class="col-lg-12 subtest-select">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title" id="subtest-chart-select"><i class="fa fa-bar-chart-o fa-fw"></i>' . $_SESSION['label'] . ' Subtest Select </h3>
</div>
<select class="form-control">
<option>1</option>
</select>
</div>
</div>
</div>'
?>
I'm still to write the PHP code to update the options of subtests within the selected test block.
Any help will be greatly appreciated as I've been trying to get this working for what seems like forever.
In $.ajax() set
dataType: 'text',
In your $.ajax() success function say:
success: function(data) {
$('.inside_whereever_you_want_to_show_this').html(data);
}
Edit:
To update only one value on page you can:
a) in PHP print out only this value (so that whole page would be only this value).
<?php echo $_SESSION['label']
and in HTML put a span around the bit you want to update (avoid constructing longer strings in javascript, all constant parts should be in HTML)
<h3 class="panel-title" id="subtest-chart-select"><i class="fa fa-bar-chart-o fa-fw"></i><span class="subtest-updateable">' . $_SESSION['label'] . '</span> Subtest Select </h3>
then you can update only your needed bit with whole response
success: function(data) {
$('.subtest-updateable').html(data);
}
b) better (in systematic approach means) would be use json response, where you can return more isolated variables as well:
Set dataType to json.
Success function would use $('.subtest-updateable').html(data.label)
In PHP print json_encode(array('label' => $_SESSION['label'], 'someelse' => $someother_variable ))
You still should put span (or some other html element) around updateable bits of your page (to avoid writing constants into your javascript)
In your success function you need to update the part of the DOM that you want to change. On the PHP side just return your blade partial or whatever HTML you want to display.
$(document).on('submit', 'form#form-grad', function (e) {
e.preventDefault();
var context = $(this);
var thisForm = context.closest('form');
$.ajax({
url: thisForm.attr('action'),
method: 'PUT',
data: thisForm.serialize(),
success: function (response) {
$('#updatearea').html(response.pt_html);
// Close grading form
}
});
return false;
});
i'm having problem getting the value of a variable into the modal which is supposed to be openning. i have tried using post but nothing changed. Both codes are in index.php.
This is the jquery script passing the value
$(document).ready(function () {
$(".issue").click(function () {
var x = $(this).attr("id");
$.ajax({
url: "index.php",
type: "GET",
data: {data1: x,},
success: function () {
$("#modal2").modal('show');
}
});
});
});
And i tried echoing the id of class .issue but it doesn't works
<div class="modal fade" role = "dialog" id = "modal2" aria-labelledby = "myModalLabel" aria-hidden = "true">
<div class="dialog">
<div class="modal-content">
<div class="modal-body"><?php echo $_GET["data1"]; ?></div>
</div>
</div>
</div>
You're missing the variable in the success method. It should be success:function(ajaxData){}
So in all:
var x = $(this).attr("id");
$.ajax({
url: "index.php",
type: "GET",
data: {data1: x,},
success: function (ajaxData) { // ajaxData is the return data from php
// add the data to the modal
$("#modal2 .modal-body").html(ajaxData);
$("#modal2").modal('show');
}
});
Are you sending the data server side to save it, or grab information from the database? If all you're trying to do is move the data to the modal, ajax isn't necessary.
Part of me suspects you're not properly calling and passing the data to php, if you really do need ajax. The php you send the ajax data to should be a separate file, that receives it, processes it, and echos it back to the ajax success function. Then the ajax function puts the data in the modal and displays the modal.
Hope one of those thoughts points you in the right direction.
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.