We are on progress creating web page for live search and update file in bulk using JQUERY AJAX method. The files consist of index.php (for display to user and Javascript), and multiple_update.php (for fetch and update file in bulk). Initial reference we got is from here from webslesson website, but it does not have any reference for searching the record, hence we search for help for our journey.
Below is our index.php file
<div class="content-wrapper">
<div class="content-heading">
<div>STO Monitoring<small>Tables, one step forward.</small></div>
<div class="ml-auto"><input type="text" id="search" placeholder="Search" /></div>
<div id="display"></div>
<div class="ml-auto">
<button class="btn btn-primary btn-lg" type="button" data-toggle="modal" data-target="#myModalSmall"><i class="fas fa-plus-square"></i> Add Record</button>
</div>
</div>
<form method="post" id="update_form">
<div class="card">
<div class="card-body">
<table class="display" id="example" style="width:100%">
<thead>
<tr>
<th width="3%"></th>
<th width="5%">No</th>
<th width="15%">STO</th>
<th width="20%">PN</th>
<th width="8%">Qty</th>
<th width="10%">From</th>
<th width="10%">Dest</th>
<th width="15%">Status</th>
<th width="14%">Remark</th>
</tr>
</thead>
<tbody></tbody>
</table>
<div align="left">
<input type="submit" name="multiple_update" id="multiple_update" class="btn btn-info" value="Multiple Update" />
</div>
</div>
</div>
</form>
</div>
.....
Below is script inside our index.php, the one we suspect need troubleshoot at the moment.
<script>
function fill(Value) {
$('#search').val(Value);
if (name == "") {
$("#display").html("");
}
}
$(document).ready(function(){
function fetch_data()
{
$("#search").keyup(function() {
var name = $('#search').val();
if (name == "") {
//Assigning empty value to "display" div in "search.php" file.
$("#display").html("empty");
} else {
$.ajax({
url:"multiple_select.php",
method:"POST",
dataType:"json",
data: {
//Assigning value of "name" into "search" variable.
search: name
},
success:function(data)
{
var html = '';
for(var count = 0; count < data.length; count++) {
html += '<tr>';
html += '<td><input type="checkbox" id="'+data[count].num+'" data-num="'+data[count].num+'" data-sto="'+data[count].sto+'" data-pn="'+data[count].pn+'" data-qty="'+data[count].qty+'" data-supplant="'+data[count].supplant+'" data-dest="'+data[count].dest+'" data-stat="'+data[count].stat+'" data-remark="'+data[count].remark+'" class="check_box" /></td>';
html += '<td>'+(count+1)+'</td>';
html += '<td>'+data[count].sto+'</td>';
html += '<td>'+data[count].pn+'</td>';
html += '<td>'+data[count].qty+'</td>';
html += '<td><span class="btn btn-oval btn-primary">'+data[count].supplant+'</span></td>';
html += '<td><span class="btn btn-oval btn-warning">'+data[count].dest+'</span></td>';
html += '<td>'+data[count].stat+'</td>';
html += '<td>'+data[count].remark+'</td></tr>';
}
$('tbody').html(html);
}
});
}
});
}
fetch_data();
$(document).on('click', '.check_box', function(){
.....
</script>
We modify the AJAX to see if the input can be catched by the network, below is code for multiple_update.php
<?php
include('multiple_connection.php');
$name = $_POST['search'];
echo $name;
$query = "SELECT * FROM matreq_list, sto_list WHERE matreq_list.sto = sto_list.sto AND sto_list.sto LIKE '%$name%' LIMIT 5;
$statement = $connect->prepare($query);
if($statement->execute()) {
while($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
echo json_encode($data);
}
?>
We want to make every search is captured via AJAX, and respond from network will be live-reflected in our index file. Below is our expected final result (this result is without "LIKE" in mysql statement to show the result only) :
And we confirm AJAX can handle our input, below is the image :
--UPDATE-- Below is error messages :
Error messages
However, after we fired the input, nothing cames up in our index.php file. Network shows good respond, but the HTML is not responding the way we expected it to do. Please kindly advise us sir, what is wrong with our method and what should we fix?
Thank you and appreciate your kind help in our case
=====UPDATE=====
2020-07-02 : As mentioned by mr Nadir Baoun, tried to change the order of jquery.js and put it above the bootstrap.js, and somehow my table now able to search some part or whole part of the data.
Before :
.....
<script src="vendor/datatables.net/js/jquery.dataTables.js"></script>
<script src="vendor/datatables.net-bs4/js/dataTables.bootstrap4.js"></script>
<script src="vendor/datatables.net-responsive-bs/js/responsive.bootstrap.js"></script>
<script src="vendor/jquery/dist/jquery3.5.1.js"></script>
<script src="vendor/datatables.net/dist/js/jquery.dataTables.min.js"></script>
After ordered : I move the jquery to the top of all codes.
and below is network screenshot :
After change order of javascript
Surprisingly, this work well :D
The HTML isnt responding the way you want is because you have JavaScript errors thus your response code wont function accordingly.
First thing include your jquery file before bootstrap.
This should solve the " cannot read property fn of undefined " error.
Please update your post with debug messages in the success param of your ajax request after doing what i have mentionned above
After thoroughly reading on various articles with a guide from Mr Nadir Baoun, my problem is now fixed by changing the order of the script, putting the jquery script before the bootstrap script.
Similar answers also posted in stackoverflow website :
script order for jquery with bootstrap
Thank you :)
Related
Having successfully eliminated the issue from a previous question I posed in add limit to data passed to bootstrap modal with foreach() in codeigniter, I now find myself with the residue of that issue. As succinctly posited by #webcrazymaniac;
The idea is to have a unique modal window, with it's unique id for each article, uniquely called with the corresponding button
According to the solution listed in Send parameter to Bootstrap modal window?, I should be able to have my desired effect as stated above - adapted as;
On page Modal
<!-- alert view -->
<div class='modal fade' id='myModal' role='dialog'>
<div class='modal-dialog'>
<!-- Modal content-->
<div class='modal-content' id='#myModal<?php echo $a->art_id;?>'>
<div class='modal-header'>
<button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>
<h2 class='modal-title'>Title: <?php echo $a->title;?></h2>
</div>
<div class='modal-body'>
<h3>Category: <?php echo $a->cat_name;?></h3>
<h3>Date: <?php echo $a->public_date;?></h3>
<h3>Content: <?php echo $a->description;?></h3>
</div>
<div class='modal-footer'>
<button type='button' class='btn btn-default' data-dismiss='modal'>Close</button>
</div>
</div>
</div>
jQuery Script
<script type="text/javascript">
$( document ).ready(function() {
$('#myModal').on('show.bs.modal', function (e) { //Modal Event
var id = $(e.relatedTarget).data('id'); //Fetch id from modal trigger button
$.ajax({
type : 'POST',
url : 'query.php', //Here you will fetch records
data : 'post_id='+ id, //Pass $id
success : function(data){
$('.form-data').html(data);//Show fetched data from database
}
});
});
});
</script>
Modal Trigger Button
echo "<a href='#myModal/".$a->art_id."' class='btn btn-success btn-sm' data-toggle='modal' data-target='#myModal' data-id='".$a->art_id."'>View</a> ".
query.php
<?php
//Include database connection here
$dsn = 'mysql:host=localhost;dbname=articles;charset=utf8';
$user ='';
$pass ='';
$options = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES, false);
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
if($_POST['art_id']) {
$id = $_POST['art_id'];
$category = $_POST['cat_name'];
$public_date = $_POST['public_date'];
$description = $_POST['description'];
// Run the Query
$sql = "SELECT `art_id`, `cat_name`, `public_date`, `description` FROM `articles` WHERE `art_id`='?'";
$stmt = $pdo->prepare($sql);
// Fetch Records
$stmt->execute();
}
?>
It all works to call the modal, but this attempt only nets me the 5th result on-page for all (green) buttons clicked. As (maybe) an important note, I'm having trouble with data-id='#myModal<?php echo $a->art_id;?> fitting into the modal trigger button as it destroys the popup of the modal. I know I have to maybe pull a destruction mode in order to change to another ID like so;
$('#myModal').on('hidden.bs.modal', function () {
$(this).removeData('bs.modal');
});
Now, mind you, I'm not especially conversant in jQuery, so what I've come up with is based on a solid few hours of reading and experimentation. Having pored over numerous examples, I'm still at a loss as to exactly how to make this all work. I'm really stuck as I'm getting the same result (off by a factor of either the display of the first or fifth result for clicking green buttons) whether I'm trying this straight PHP or jQuery. It seems like every question that I've read in this category of question gets me to the current dilemma I'm in where if I use the PHP version solution, I'm returned the 1st page result for every view button on the page. jQuery solution returns the fifth page result for each view button. This is strange indeed... Not even changing out the jQuery for simplified js like this;
<script type="text/javascript">
//jQuery Library Comes First
//Bootstrap Library
($ 'a[data-toggle=modal]').click ->
target = ($ #).attr('data-target')
url = ($ #).attr('href')
($ target).load(url)
I was pulling for that snippet to rescue me, but, no. Neither did this one;
<script type="text/javascript">
//jQuery Library Comes First
//Bootstrap Library
$(document).ready(function(){
$('#myModal').on('shown.bs.modal', function () {
var $modal = $(this),
modal_title = $(this).data('modal-title'),
modal_params = $(this).data('modal-params');
if(typeof modal_title !== typeof undefined && modal_title !== false) {
title = modal_title;
}
else{
title = 'Title';
}
$.ajax({
cache: false,
type: 'POST',
url: 'query.php',
data: modal_params,
success: function(data) {
$modal.find('.modal-title').html(title);
$modal.find('.modal-body').html(data);
}
});
});
});
</script>
//crabbed from
//https://stackoverflow.com/questions/35702374/bootstrap-modal-with-individual-attributes
But, as par for the course, no love... There's either Human Error to blame, or I'm just missing something plainly hiding in full view. Having read more than 200-plus questions today, I'm having problems re-reading this for formatting, etc. (lol!). Learned tons, but still stuck.
UPDATE
In the time since I've looked at what #progrAmmar suggested, I went back to try and refine my approach. The key issue is how to make the jQuery reload process;
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
clear out the modal so that upon click of another button, the corresponding table row content flows in like water. I'm having problems figuring out what sequencing is correct for the jQuery - as it stands now;
<script type="text/javascript">
//jQuery Library Comes First
//Bootstrap Library
$(document).ready(function() {
// Fill modal with content from link href
$('.myModal').on('click', function(e) {
var link = $(this).data('href');
$('#myModal').modal('show');
$('#myModal .modal-body').load(link );
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
});
})
</script>
Which results in the view below:
If you look on the bottom-left of the image you'll see the corresponding id value is 3, but the open modal is pulling content from id value 5. I'm still having the process of calling the modal and displaying table row go smoothly, but the modal reload process is bent. Suggestions? I'm out of ideas at this point.
#progrAmmar, I went back to your proffered suggestion, but these are the following things preventing me from fully adapting;
article/index (controller/index function)
public function index()
{
$modal = $this->article_model->modal($art_id=NULL);
$category = $this->category_model->listAll();
$article =$this->article_model->index($this->limit);
$total_rows=$this->article_model->count();
$config['total_rows']=$total_rows;
$config['per_page']=$this->limit;
$config['uri_segment']=3;
$config['base_url']=site_url('article/index');
$this->pagination->initialize($config);
$page_link =$this->pagination->create_links();
$this->load->view('admin/article',compact('article', 'page_link', 'category', 'modal'));
}
article_model.php
public function modal($art_id)
{
$data = array();
$this->db->select('art_id', 'cat_name', 'public_date', 'description');
$this->db->from('tbl_article');
$query = $this->db->get();
if($query->num_rows() > 0)
{
$results = $query->result();
}
return $results;
}
Still trying to figure out where the needle is here. Thanks again for your suggestions #progrAmmar.
UPDATE ANNOYANCES
Back to purely PHP as jQuery wasn't doing anything different for me - even after playing around with #progrAmmar's code. Now I'm left back at ground zero and having read for another two hours (mainly # the jQuery forum). :sigh:
ALMOST THERE....
After consulting the BS 3.3.5 docs, I know my answer is in the Varying modal content based on trigger button section. Tried to extrapolate this;
//Modal window trigger button
echo "<a href='".base_url()."article/$a->art_id' class='btn btn-success btn-sm' data-toggle='modal' data-target='#myModal' data-id='".$a->art_id."'>View</a> ".
//jQuery code
$('#myModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var id = button.data('id') // Extract info from data-* attributes
var href = button.data('href') // Extract info from data-* attributes
var target = button.data('target') // Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this)
modal.find('.modal-title').text('Title:')
modal.find('.modal-body').val('Category:')
modal.find('.modal-body').val('Date:')
modal.find('.modal-body').val('Content:')
$('#myModal > div.modal-body).empty();
})
I'm pretty sure I'm doing it wrong as I just can't get my head around any attempted extrapolations - been poring over other solution examples on SO, but am still working out approaches to the above coding. Research in motion...
Extrapolating Code Proffered By #progrAmmar;
Controller Article(.php)
------------------------
public function index()
{
$data['modal'] = $this->article_model->modal($art_id); // Gets all the data
$this->load->view('('admin/article',compact('article', 'page_link', 'category', 'modal') $data);
}
View article(.php)
------------------
<div class='modal fade' id='myModal' role='dialog'>
<div class='modal-dialog'>
<!-- Modal content-->
<div class='modal-content' id='myModal'>
<div class='modal-header'>
<button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>
<h2 class='modal-title'>Title: <?php echo $a->title;?></h2>
</div>
<div class="modal-body">
<div class="row">
<div class="col col-md-12">
<h3>Category: <?php echo $a->cat_name;?></h3>
<h3>Date: <?php echo $a->public_date;?></h3>
<h3>Content: <?php echo $a->description;?></h3>
<input type="hidden" id="hidId" value="<?php echo $a->art_id;?>" />
</div>
</div>
</div>
<div class='modal-footer'>
<button type='button' class='btn btn-default' data-dismiss='modal'>Close</button>
</div>
//Finally call the html via JavaScript
$.get(window.base_url + 'index.php/article/'+ id, function (data) {
$('#myModal' > div.modal-body).empty();
$('#myModal').html('data');
$('#myModal').modal('show');
}
Did a little juggling to fit in this attempt, but there's no change as the fifth page result is never bumped out by another content ID as shown below;
Still stuck in the same position before...round and round we go ミ●﹏☉ミ
Of the section I'm interested in within the docs;
$('#exampleModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var recipient = button.data('whatever') // Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this)
modal.find('.modal-title').text('New message to ' + recipient)
modal.find('.modal-body input').val(recipient)
})
my primary issue is;
HOW do I extrapolate Update the modal's content?
THIS is essentially the core of my impedance and not located by an intensive search of the BS docs. If I could sync up some kind of way to force-reload the content within the modal, I have my answer. In fact the closest I've found to any example of how to (maybe) approach this was a post here (sorry forgot which one) detailing how to reload an image within a modal by targeting the src element;
//And then you just change the src attribute of the picture element from your function.
var picture = button.data('picture')
$('#picture').attr('src',picture);
THAT'S IT!* (theoretically)...Between the above example and the Varying modal content based on trigger button example, I'm on my way to losing it. I can't believe I can't just make the logical connection required to fire off the force-reload. I just don't see it, and every example I've used thus far keeps me in the same place.
Having gone through fifty-plus JQuery code examples, not one of them did squat as far as activating any functionality, so I'm off attempting to use it as any sort of solution. NONE of the answers under this topic worked (even a little). This is the 1st time in my career where I've been completely stumped with nowhere to turn.
Here are the things I've tried:
Situation 1
Initially dealing with an HTML table <table class="table table-condensed"> listing out the articles db elements of 'art_id', 'title', 'cat_name', 'public_date', 'image', the table elements are scooped from the db with foreach ($article->result() as $a){.
The table ends with the activity buttons, the 1st of which is the BS modal trigger (unable to change table being echoed out in PHP - just mucks it all up);
echo "<a href='".base_url()."article/#myModal/$a->art_id' button class='btn btn-success btn-sm' data-toggle='modal' data-target='#myModal' data-id='".$a->art_id."'>View</a> ".
Situation 2
The modal data-toggle (as posted above) is the trigger for the modal to popup and is located on page bottom;
<!-- alert view -->
<div id="myModal<?php echo $a->art_id" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<?php
$i=0;
foreach ($article->result() as $a){
?>
<div id="#myModal<?php echo $a->art_id ?>" class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h2 class='modal-title'>Title: <?php echo $a->title;?></h2>
</div>
<div class='modal-body'>
<h3>Category: <?php echo $a->cat_name;?></h3>
<h3>Date: <?php echo $a->public_date;?></h3>
<h3>Content: <?php echo $a->description;?></h3>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
<?php
if(!$i=0) break;
$i++;
}
?>
</div>
If the modal foreach isn't both included and augmented like so;
<?php
if(!$i=0) {
break;
} else {
$i++;
}}
?>
then the modal pulls all of the $a->art_id elements into view simultaneously like so;
And, even with the necessary jQuery at the bottom (after the modal);
<script type="text/javascript">
jQuery(document).ready(function($) {
jQuery(document).ready(function($) {
$('.myModal').click(function(event){
var $link = $(this);
new BootstrapDialog({
title : 'Title : ' + $link.attr('href'),
content : $('<div>Loading...</div>').load($link.attr('href')),
buttons : [{
label : 'Close',
onclick : function(dialog){
dialog.close();
}
}, {
label : 'View',
cssClass: 'btn-primary',
onclick : function(dialog){
alert('The content of the dialog is: ' + dialog.getBody().html());
dialog.close();
}
}]
}).open();
event.preventDefault();
});
});
});
</script>
//crabbed from - https://stackoverflow.com/questions/14045515/how-can-i-reuse-one-bootstrap-modal-div/14059187#14059187
Situation 3
NOTHING WORKS.... The jQuery is not destroying and reloading the modal, so I'm only getting that 1st on-page result from the 1st button on the page (completely correct content and ID). The most frustrating thing is if I hover over each button, the correct content ID is returned. I think it's safe to say that it's not any problem with the code - I have to investigate WHY that specific code isn't working on-page. Confusing because I'm using jQuery already;
<script src="<?php echo base_url(); ?>asset/js/jquery.js"></script>
<script src="<?php echo base_url(); ?>asset/js/jquery-latest.min.js"></script>
putting these two lines just above the modal and jQuery at the bottom of the page. It looks as if there is a conflict somewhere preventing the jQuery-driven script from firing. The only conflict I can maybe even see is that with the CKEditor that loads just above the jQuery.
Even with switching to another code block;
<script type="text/javascript">
jQuery(document).ready(function($) {
$('.myModal').click(function(){
$(this).find('.inner').clone().appendTo('#myModal .modal-content');
$('#myModal .modal-title .modal-body .control-group.hide').show();
$('#myModal').modal();
});
$('#myModal').on('hidden', function(){
$('#myModal .inner').remove();
});
});
</script>//forgotten SO crabbing
I keep getting the same results. Since throwing in the towel, I've come upon several SO solutions which suggest the scenario I want, but I can never physically fulfill them and it making me angrier than a rattlesnake in a Texans' boot. Not only were these questions completely similar to mine, but they (almost) all got upvoted # +1 or better, and the selected solutions did nothing to extract me from my bottleneck.
This is an issue that I'd like to see cleared up as I know there's a solution, and from the numerous Fiddles and Plunkers, they're all similar in nature with slight variations that I haven't been able to employ.
The simplest (and probably the easiest) way to call a MODAL for data is to call the HTML from the server.
Create a separate view for your model.
Call the data into it, load the model from the controller.
Here's how I am calling my Modal with codeigniter
Controller
public function EditData($id)
{
$data['entity'] = $this->Home_model->getData($id); // Gets all the data
$this->load->view('Home/modal_data', $data);
}
views/Home/modal_data.php
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Edit <?= $entity['name'] ?></h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col col-md-12">
<label>Name</label>
<input type="text" id="txtName" class="form-control" value="<?= $entity['name'] ?>" />
<input type="hidden" id="hidId" value="<?= $entity['id'] ?>" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success has-spinner" id="btnSave">
<span class="spinner"><i class="glyphicon glyphicon-spin glyphicon-refresh"></i></span>Save
</button>
</div>
Make sure you have a modal div on your page to call the html into.
views/Home/index.php
<html>
.
.
.
<body>
<div id="home_modal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content" id="home_modal_cont">
</div>
</div>
</div>
</body
</html>
Finally call the html via JavaScript
$.get(window.base_url + 'index.php/home/EditData/'+ id, function (data) {
$('#home_modal_cont').empty();
$('#home_modal_cont').html(data);
$('#home_modal').modal('show');
}
Working with two php files, index.php and search.php. index sends some parameters to search, which performs a few queries into a database, and then returns the information on a table, stored into $output.
I now want to add a bootstrap button to the output, that calls a simple show/hide jQuery function.
The button is created, but it doesn't work when I test it on index.php
<div class="col-sm-8">
<table class="table table-hover" id="output">
</table>
<div id="edit" >
<div class="page-header" id="editar" style="display: none;">
<h2 id="producto">Placeholder<button id="exit" type="button" class="btn pull-right"><span class="glyphicon glyphicon-remove"></button><!--Clicking this button hides the edit div and shows the output table--></h2>
</div>
</div>
</div>
The exit/editbtn button calls the following:
<script>
$(document).ready(function(){
$("#exit").click(function(){
$(document.getElementById("edit")).hide();
$(document.getElementById("output")).show();
});
});
$(document).ready(function(){
$("#editbtn").click(function(){
$(document.getElementById("edit")).show();
$(document.getElementById("output")).hide();
});
});
</script>
And the definition of the "editbtn" is made on the separate php file:
if($query->num_rows){
$rows = $query->fetch_all(MYSQLI_ASSOC);
forEach($rows as $row){
$output .= '<tr><td><button id="editbtn" type="button" class="btn btn-default"><span class="glyphicon glyphicon-pencil"></span></button></td><!--Clicking this button hides the output table and shows the edit div--></tr>';
}
$output .= '</tbody>';
So in the end, I have the table with the button created, but it does nothing when I click on it.
Why dont you try the same in order?
Like:
<script>
$(document).ready(function(){
$("#exit").click(function(){
$("#edit").hide();
$("#output").show();
});
$("#editbtn").click(function(){
$("#edit")).show();
$("#output")).hide();
});
});
</script>
This should work, always that you dont insert the edit button with ajax AND by definition, if you are using IDs, you are supposed to have only one element, if you have it between a foreach, it could cause you a problem.
It seems to be the jQuery selectors, they should be like this:
$("#edit").show();
Or in JavaScript:
document.getElementById('edit').styles.display = "none"; //or use addClass
PD: don't use two ready functions, put the listeners on the same one ;)
Edit:
Add a console.log in the function, and check out the console on the developer tools of your browser. Also try to comment the PHP query, except the output.
So I have an interesting problem
I am having issues with the jquery .load() function. I have a file structure as follows
index.php
|
|---header.html
|---body.html
|---footer.html
index.php sets three variables as so $variable_one = new Database('passedQuery');
header.html, body.html and footer.html are then included into index.php
In body.html I have something similar to
<div class="span4 well">
<h3>Current Statistics</h3>
<hr>
<table class="table table-striped">
<thead>
<tr>
<th>Users</th>
<th>Event One</th>
<th>Event Two</th>
<th>Event Three</th>
</tr>
</thead>
<tbody>
<tr>
<td><?php echo $var1->result[0][0]; ?></td>
<td><?php echo $var2->result[0][0]; ?></td>
<td><?php echo $var3->result[0][0]; ?></td>
</tr>
</tbody>
</table>
</div>
I also have a form in body.html which is submitted through a generic jquery function as so
$(document).ready(function(){
$('.btn').bind('click', function(e){
e.preventDefault();
var form = $(this).parents('form');
var vals = $(form).serialize();
var form_id = $(form).attr('id');
$.ajax({
url: $(form).attr('action'),
type: $(form).attr('method'),
data: vals,
dataType: 'json',
success: function(data){
console.log("Success");
$('#information').html('<div class="alert alert-success">Great Success! :)</div>');
setTimeout(function() {
$('#content').load('views/partials/body.html');
}, 5000);
},
error: function(a, b, c){
console.log("Error");
$('#information').html('<div class="alert alert-error">Epic Failure</div>');
setTimeout(function() {
$('#content').load('views/partials/body.html');
}, 5000);
}
});
});
});
When I submit the form and reload the body the PHP variables that were echo'd in the html are now gone and I get an apache error similar to the following
[dateTime] [error] [client IP] PHP Notice: Undefined variable: variable in /path/to/body.html on line 133, referer: myReferrer
I asked a few of my friends about this and they were all stumped, as was #jquery of Freenode. Anyone have any ideas?
UPDATE - FORM CODE AND index.php CODE
Form
<div class="span4 well">
<form class="form-horizontal" id="admin_add" name="admin_add" method="post" action="routes/to/add_admin.php">
<fieldset>
<legend>Add Administrator</legend>
<div class="control-group">
<label class="control-label" for="select03">Select a user</label>
<div class="controls">
<select id="select03" name="user">
<?php
foreach($var1->result as $key => $value)
echo "<option>".$value[0]."</option>";
?>
</select>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary form-submit-button">Submit</button>
</div>
</fieldset>
</form>
</div>
Index
$var2 = new Database('query', 'SELECT COUNT(uid) FROM attendees WHERE eid = 1');
$var3 = new Database('query', 'SELECT COUNT(uid) FROM attendees WHERE eid = 2');
/**
* List users to add to database
*/
$var1 = new Database('query', 'SELECT name FROM users WHERE admin=0');
/**
* Include all the visuals
*/
include('views/partials/header.html');
require_once('views/partials/body.html');
include('views/partials/footer.html');
When you load body.html the first time I guess that you're loading it using php's include() function. Well, what this does is "concatenate" the php so on the server side it's like its one long php file. This works with your variables because its as if there is no break in the code.
When you use jQuery's load() functions this happens client side. What is happening is that you're getting the html output of JUST body.html and you are dynamically (on the client side) putting that content into the client's page.
The problem you're having then is that the PHP is no longer concatenated. load() takes body.html in its singularity and puts it into the page.
Another way to look at it is that when someone goes to index.php the php is parsed, all the variables that are echo'd are turned into bog standard text/html and shipped to the browser. Once there they are no longer php variables, they are just text/html. Making a new request to body.html via javascript means that those variables you're referencing are no longer available. They've already been converted to HTML and shipped to the browser, then the php stopped, and this is a new request.
I don't know how you want to fix this to be honest. You might want to look into a templating system like smarty. Or you might want to put your functions into a file called functions.php include it into your body.html and then reference those functions in your body.html rather than relying on code in the index page.
i.e. your body.html will look like this:
<?php include "functions.php"; ?>
<div ...>
<?php
$var1 = getVar1(); // function in functions.php
echo $var1->result[0][0];
// ... etc
?>
</div>
Then when it is called from javascript, before it is delivered to the browser, the php will be evaluated and everything will work.
Hope I've explained this well dude. :)
When your jQuery request gets to the server it will be serving you back body.html, which doesn't have any PHP processing, so your variables set within index.php, don't exist.
When you open the application can you please click on the "Add Question" twice so it adds 2 table rows.
Now you will see in the application that above the horizontal line there is a textarea and a plus button, and below the horizontal line shows 2 table rows, both rows displaying its own textarea and plus button.
Now my question is that I want these 2 outcomes to happen but I do need help from somebody who is good at using Jquery/Javascript in order to solve this situation:
Situation 1. If the user clicks on the plus button ABOVE the horizontal line, then it displays a modal window which contains a search bar, Please type in search bar "AAA". You will now see a list of results. Now what I want is that if the user selects a row by clicking on the "Add" button, then I want the "QuestionContnet" within that row to be displayed in the textarea above the horizontal line. At the moment the Add button just closes the modal window but doesn't add anything into the textarea.
Situation 2: This deals with the user clicking on a plus button within one of the table rows BELOW the horizontal line. I want the same thing to happen except the "QuestionContent" added is displayed in the textarea within the same row the user has clicked the plus button, no where else.
How can both situations be solved so that it adds the QuestionContent into the correct textareas depending on which plus button is clicked? I am using an Iframe to display the content within the modal window.
UPDATE:
If you look at the application, it is now displaying "[Object] [object]" in textaea when I click "Add" button. Not the "Question".
Below is the code for the application:
<head>
<script type="text/javascript">
var plusbutton_clicked;
function insertQuestion(form) {
var $tbody = $('#qandatbl > tbody');
var $tr = $("<tr class='optionAndAnswer' align='center'></tr>");
var $plusrow = $("<td class='plusrow'></td>");
var $question = $("<td class='question'></td>");
$('.questionTextArea').each( function() {
var $this = $(this);
var $questionText = $("<textarea class='textAreaQuestion'></textarea>").attr('name',$this.attr('name')+"[]")
.attr('value',$this.val());
$question.append($questionText);
});
$('.plusimage').each( function() {
var $this = $(this);
var $plusimagerow = $("<a onclick='return plusbutton();'><img src='Images/plussign.jpg' width='30' height='30' alt='Look Up Previous Question' class='imageplus'/></a>").attr('name',$this.attr('name')+"[]")
.attr('value',$this.val());
$plusrow.append($plusimagerow);
});
$tr.append($plusrow);
$tr.append($question);
$tbody.append($tr);
form.questionText.value = "";
$('.questionTextArea').val('');
}
function plusbutton() {
// Display an external page using an iframe
var src = "previousquestions.php";
$.modal('<iframe src="' + src + '" style="border:0;width:100%;height:100%;">');
return false;
}
function closewindow() {
$.modal.close();
return false;
}
$('.plusimage').live('click', function() {
plusbutton($(this));
});
function plusbutton(plus_id) {
// Set global info
plusbutton_clicked = plus_id;
// Display an external page using an iframe
var src = "previousquestions.php";
$.modal('<iframe src="' + src + '" style="border:0;width:100%;height:100%;">');
return false;
}
function addwindow(questionText) {
if(window.console) console.log();
var txt = $(this).val(questionText);
if($(plusbutton_clicked).attr('id')=='mainPlusbutton') {
$('#mainTextarea').val(txt);
} else {
$(plusbutton_clicked).parent('td').next('td.question').find('textarea.textAreaQuestion').val(txt);
}
$.modal.close();
return false;
}
</script>
</head>
<body>
<form id="QandA" action="<?php echo htmlentities($action); ?>" method="post">
<div id="detailsBlock">
<table id="question">
<tr>
<td rowspan="3">Question:</td>
<td rowspan="3">
<textarea class="questionTextArea" id="mainTextarea" rows="5" cols="40" name="questionText"></textarea>
</td>
</tr>
</table>
<table id="plus" align="center">
<tr>
<th>
<a onclick="return plusbutton();">
<img src="Images/plussign.jpg" width="30" height="30" alt="Look Up Previous Question" class="plusimage" id="mainPlusbutton" name="plusbuttonrow"/>
</a>
<span id="plussignmsg">(Click Plus Sign to look <br/> up Previous Questions)</span>
</th>
</tr>
</table>
<table id="questionBtn" align="center">
<tr>
<th>
<input id="addQuestionBtn" name="addQuestion" type="button" value="Add Question" onClick="insertQuestion(this.form)" />
</th>
</tr>
</table>
</div>
<hr/>
<div id="details">
<table id="qandatbl" align="center">
<thead>
<tr>
<th class="plusrow"></th>
<th class="question">Question</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</form>
</body>
The details stored in the modal window comes from a seperate script known as "previousquestions.php", Below is the code where it shows the result of the "QuestionContent" field only displayed and it's "Add" button after the user has compiled a search:
<?php
$output = "";
while ($questionrow = mysql_fetch_assoc($questionresult)) {
$output .= "
<table>
<tr>
<td class='addtd'><button type='button' class='add' onclick='parent.addwindow();'>Add</button></td>
</tr>";
}
$output .= " </table>";
echo $output;
?>
Thank you
Application here
The first issue is this ->
<button id="add">
You cannot reuse an ID over and over, or, the page will iterate to the last element with that ID and NEVER run anything on any previous elements.
Quick fix:
<button class="add">
Simple enough.
We need to get the question text, from the first column, there are so many methods to do this with jQuery selectors it's mind blowing.
Situation 1
Let's take a peek at one option ->
$(document).on('click', '.add', function(){
//now that we've declared the click function, let's jump up to our parent element, and grab the text in the first cell.
var theQuestion = $("td:first-child", $(this).parent()).text();
//Now that we've figured out how to traverse the DOM to get the data we want, we need to move that data elsewhere.
$('.questionTextArea').val(firstCell);
});
Simple enough, right? That should solve the first problem you had.
Note: Textareas use value to set the data, whereas other elements will use .text()
Situation 2
Alright, now we need to figure out how to add a unique identifier to the "+" row when we click, and check for that "unique identifier" when appending the data, let's do it.
You have a <td> with a class of plusrow, sounds good, let's make a click function out of it, and give it a cool new class to reference.
$(document).on('click', '.plusrow', function(){
//adding a unique class for the purpose of the click.
$(this).addClass('activePlusRow');
});
So now the "+" we clicked has a new class -- activePlusRow, let's go back to our initial click handler for the add button, and give it some new conditional statements.
$(document).on('click', '.add', function(){
//lets get our Question Text...
var theQuestion = $("td:first-child", $(this).parent()).text();
//the row is present, let's then make sure that the proper cell gets your data.
if($('.activePlusRow').length > 0){
$('.activePlusRow').next('.textAreaQuestion').val(theQuestion);
$('.activePlusRow').removeClass('activePlusRow');
}
});
Alright, as you can see of the above, we test to see if the activePlusRow class exists, if it does, then we iterate to the next textarea with a class of textAreaQuestion and change the value of it, to theQuestion from the .add button we clicked.
Let me know if you've any questions.
I think best way to target chosen question to specified textarea is to parameterise your plusbutton function:
function plusbutton(plus_id) {
// Set global info
plusbutton_clicked = plus_id;
// Display an external page using an iframe
var src = "previousquestions.php";
$.modal('<iframe src="' + src + '" style="border:0;width:100%;height:100%;">');
return false;
}
Of course you have to declare global var plusbutton_clicked; before insertQuestion function so other functions could change/use this information. You have to call this function with unique parameter for each plusbutton (you generate it dynamically, so this is up to you how you want to do it)
Then you can simply use it in your $(document).on('click', '.add', function(){}); - when user clicks 'add' button you have your plusbutton id so you can navigate with jQuery to corresponding textarea and place text there.
I'm thinking next() isn't the right function, since it only searches for the immediately following sibling... Try this:
$(document).on('click', '.add', function(){
console.log("clicked");
//lets get our Question Text...
var theQuestion = $("td:first-child", $(this).parent()).text();
//the row is present, let's then make sure that the proper cell gets oru data.
if($('.activePlusRow').length > 0){
$('.activePlusRow').next('.question').find('textarea.textAreaQuestion').val(theQuestion);
$('.activePlusRow').removeClass('activePlusRow');
}
$.modal.close();
return true;
});
I'm working on a site using the Big Commerce platform. The cart page is built in snippets called by PHP. I don't have access to the PHP files. What I need to do is get the value of a span tag(at a given index) and retrieve the value, I use this value to determine what my minQTY text field should be. I want my code to run after the page has been loaded. However my script isn't working on the page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).load(function(){
$("a.CustomizeItemLink");
$changeIndex = $("a.CustomizeItemLink").index('a.CustomizeItemLink');
$change = $("a.CustomizeItemLink").length;
$productTestArray = ['/american-boxwood-buxus/', '/lavander-crape-myrtle-lagerstroemia-fs/']
$productLength = $productTestArray.length;
for(i=0, j=0; i<=$change, j<=$productLength; i++, j++){
$productTest = "http://www.tnnursery.net";
$productTestValue = $("td.blah a").get(i);
$productTest = "http://www.blah.net" + $productTestArray[j];
$MD = $productTestValue;
$MS = $productTest;
$minQTYArray = ['100','100','75','50','25','20','15'];
$cartSpanValue = $(".productAttributes td span:eq("+i+")").text();
$rdTestArray2 = ['6-12','12-18',"1-2'","2-3'","3-4'","4-5'","5-6'"];
$arr2Test = jQuery.inArray($cartSpanValue, $rdTestArray2);
$minQTYValue = $minQTYArray[$arr2Test];
$cartQtyValue = $(".qtyInput:eq("+i+")").val();
if($MD != $MS){
}
else{
if($cartQtyValue >= $minQTYValue){
}
else{
if ($arr2Test == -1){
$cartQtyValue = $(".qtyInput:eq(" + i + ")").val('100');
}
else{
$cartQtyValue = $(".qtyInput:eq(" + i + ")").val($minQTYValue);
alert($cartQtyValue);
}
}
}
}
});
});
});
</script>
</td>
<td class="ProductName" colspan="1">
Item Name1<table class="productAttributes" cellpadding="0" cellspacing="2">
<tr>
<td>
<label>Plant Sizes:</label>
</td>
<td>
<span>12-18"</span>
</td>
Change
28500
()
<div style="display: none" class="WrappingOptions">
Gift Wrapping:
Add
<span style="display: none">
(Change or Remove)
</span>
<br />
<span style="display: none">
Gift Message:
</span>
</div>
</td>
<td align="center" class="CartItemQuantity">
<span style="padding: 0; margin: 0;"><input type="text" size="2" name="qty[4eea86d587825]" id="text_qty_4eea86d587825" class="qtyInput quantityInput" value="50"/></span>
<div style="">
Remove
</div>
</td>
My question is how do I set my jQuery to run after the PHP has been loaded into the page?
First, you should restore the $(document).ready(function(){});
Second, the php runs on the server side, and thus before the page itself is loaded. You shouldn't have any worry that your javascript will run before the PHP.
Lastly, I think the reason your code isn't running may be due to syntax errors. If you've copied your code in directly then you have multiple endings to your opening function. I'm not sure if this was intentional or not but you have three sets of closing for the load function when its unnecessary.
Also, this line :
$productTestArray = ['/american-boxwood-buxus/', '/lavander-crape-myrtle-lagerstroemia-fs/']
Does not have a semi-colon ending the statement. Make these changes and see if your code begins to function properly.
EDIT: Also, in your For loop you define i and j. Why is that? I believe they will always be the same number the way you have it setup. Am I missing something?
Try replacing $(document).load with $(window).load.
$(document).ready(function(){
//your code here
});