I'm trying to create a modal that allows a user to edit a memo field on a corresponding database.
The issue is, it works until I submit some form data, after that the textarea is not updating with the new data, it just displays the submitted data.
Some things to bear in mind:
The memo field is stored as plain text within the backend database.
The 'AjaxGetData.wc' (see code below) returns the field content in HTML format.
I'm using a javascript class called jquery.form.js to submit the form data within the modal.
So, I have a modal that contains a form and on that form is a textarea, the name of this textarea is changed dynamically depending on what element was clicked within a data table.
Then, when the href is clicked to open the modal an ajax request is run which collects the data (with HTML formatting) for the requested element and inserts it into the textarea using $('#myTextArea').html(string).
This all works, but after submitting some changed text all subsequent modal requests load the first submitted string no matter which row I click within the data table. Although in the console.log it is showing the correct string being returned by the ajax post.
Ideally, I like to understand why the .html() function stops working after I have submitted some data.
Please see my code below :
\\HTML
<!-- START -->
<div class="modal fade" id="editLogoPnotModal" tabindex="-1" role="dialog" aria-labelledby="editLogoPnotLabel"
aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-centered" role="document">
<div class="modal-content">
<form id="editLogoPnot-Form" action="AjaxTableFieldUpdate.wc" method="post">
<!--Header-->
<div class="modal-header alert-primary">
<h4 class="modal-title" id="myModalLabel">Artwork Production Notes</h4>
<button type="button" id="editLogoPnot-closebtn" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<!--Body-->
<div class="modal-body">
<div class="md-form">
<i class="fas fa-pencil-alt prefix"></i>
<textarea id="editLogoPnot" name="ThisChangesDynamically" class="md-textarea form-control" rows="10" style="white-space: pre-wrap; overflow-y: scroll;"></textarea>
</div>
</div>
<!--Footer-->
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
<!-- END -->
\\SCRIPTS
$('#dtSjob').on('click', 'a.editLogoPnot', function (e) {
e.preventDefault();
// Get the data of the selected row from the data table
epData = sjobTable.row( $(this).closest('tr')).data()
// Change the name attr of the textarea to identify the requested data
console.log($("#editLogoPnot").attr('name'))
$("#editLogoPnot").attr('name', 'logosxzxurnxzx'+epData['sjob']['logourn']+'xzxpnotxzxM');
console.log($("#editLogoPnot").attr('name'))
// Get the latest notes for LogoURN
$.ajax({ url: "AjaxGetData.wc?ti=Logos;urn&fl=pnot&key=urn:C:"+epData['sjob']['logourn'],
type: "POST",
success: function(data) {
// The below line ALWAYS displays the correct data
console.log("Returned data: "+data);
// The below line only works before I submitted some changed data, then it stops working.
$("#editLogoPnot").html(data);
}
});
});
\\ The below function handles the submit of the modal form
var editLogoPnotoptions = {
success: editLogoPnot_showResponse
};
$('#editLogoPnot-Form').submit(function() {
$(this).ajaxSubmit(editLogoPnotoptions);
// !!! Important !!!
// always return false to prevent standard browser submit and page navigation
return false;
});
function editLogoPnot_showResponse(responseText, statusText, xhr, $form) {
$('#editLogoPnotModal').modal('hide');
}
I have tried using .val() which solves the issue but, I cannot get the data to display correctly within the textarea (it includes all the HTML formatting). If anyone has any suggestions on how to fix this, then that would also solve my issue.
Any suggestions would be greatly appreciated, as I have exhausted all my ideas!
Thanks, Chris
If I understand the issue correctly you can put the response string into a temporary element as html and retrieve it as text from that element to put in the textarea.
const str ='**E5654 ** Add Flat Neck Label
Test123';
const $div = $('<div>').html(str)
$('textarea').val($div.text())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea cols="60" rows="10"></textarea>
Related
I have a question. Can somebody explain me, how can I include another .latte file and send dynamic data with it?
I am creating api function, where you should be able to get information about company just by writing it's name. When I click to search, I can see in console that my request is getting through and sending back response, with correct data, but it won't refresh already loaded data.
Some examples of my code:
Javascript:
btn.onclick = function() {
modal.style.display = "block";
var firma = $("#firmaName").val();
console.log( "var is " + firma );
$.ajax('data', {
data: { 'firma' : firma}
});
}
.latte
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
{include 'data.latte'}
</div>
</div>
best way to approach this is by snippets and $.netteAjax().
viz: https://doc.nette.org/en/application/ajax
also, include tag can accept parameters, which are then used within loaded template, like here: https://latte.nette.org/cs/tags#toc-include
I also would recomend, insted of using include of antoher latte file, I would create component for your modal, viz. https://doc.nette.org/en/application/components
I'm trying to create a modal which should show position variable mention in my code
here is my ejs code (i'm using ejs and node js and java script for modal)
<div class="container-fluid">
<%for(i=0;i<Vac.length;i++){%>
<div class="alert alert-dark" role="alert">
<h4 class="alert-heading">Postion:- <%=Vac[i].position%></h4>
<hr>
<h5>Type:- <%=Vac[i].type%></h5>
<h6>Skills:- <%=Vac[i].Skills%></h6>
<p class="lead"><%=Vac[i].Description%> </p>
<button type="button" class="btn btn-primary" data-toggle="modal" onclick="showApply()">Apply</button>
<br>
</div>
<%}%>
</div>
here is my javascript code for the modal
<script>
function showApply()
{
$('#applyModal').modal('show');
$('#applyModal').('#applyModaltitle').text($('#alert-heading'));
}
</script>
but i'm getting the error as below:
SyntaxError: missing name after . operator[Learn More] careers:216:23 [Show/hide message details.] ReferenceError: showApply is not defined
can anybody tell me whats wrong and how i can correct it ?
After Searching for the answer for many answer i had found this out from one of the answer on stackoverflow .Since I'm accessing data from database generated , i have to access data through the elements from the data set displayed like from my example :-
i have displayed my data in an alert box and from alert box i have to take the required data and displayed it in the modal,in order to display the data on the modal we have to do the following :-
$(document).ready(function(){
$('#modalname').on('show.bs.modal',function(e){
var _button =$(e.relatedTarget);
var info =_button.parents(".alert");
var position=info.find(".classofelementneeded").text(); //text as i was using h5 tag for displaying data
$(this).find("#element where you want to display data").val(position); //val because i want to display data in text box
});
});
you can use this for displaying data from web page to modal via javascript
Refer to: Multiple selector chaining in jQuery?
function showApply()
{
$('#applyModal').modal('show');
$('#applyModal').('#applyModaltitle').text($('#alert-heading'));
}
The error you get tells you that showApply doesn't exist.
That is so, because there is a . (dot) operator that is wrong in this function.
You can try that:
function showApply()
{
$('#applyModal').find('#applyModaltitle').innerHTML=$('#alert-heading').text;
$('#applyModal').modal('show');
}
I'm working with Laravel 5 and I need to destroy data from database, I've the following code
HTML
<div class="modal fade" id="deletePub" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h6 class="modal-title" id="modalPublicationTitle">Confirm Publication Delete</h6>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row align-items-center">
<div class="col-lg-12" align="center">Really, do you want to delete this publication?</div>
Yes, Delete
</div>
</div>
</div>
</div>
</div>
JS
$(document).ready(function(){
$("#btn-confirmDeletePub").click(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var publicationId = window.location.href.split("/")[4]
console.log(publicationId);
$.ajax({
type: "DELETE",
url: "/publications/" + publicationId,
data: JSON.stringify(publicationId),
contentType: "application/json; charset=utf-8",
dataType: "json",
});
});
});
web.php
Route::resource('publications','PublicationController);
PublicationController.php
public function destroy($id)
{
$publication = Publication::find($id);
$publication->users()->detach($publication->id);
$publication->topics()->detach($publication->id);
$publication->authors()->detach($publication->id);
$publication->details()->delete();
//$publication->delete();
Redirect('/users')->with('success', 'Publication deleted correctly.');
}
All the following code should call the btn-confirmDeletePub function of the JS file when I click on the Yes, delete button. The JS button captures the id of the publication to be deleted and will sent to the destroy($id) function of the PublicationController, but for some reason this function it's not called, the error is inside the JS and I'm sure, but I do not know how to solve.
In Google Chrome's Console I get the following error:
DELETE http://localhost:8000/publications 500 (Internal Server Error)
If you want to use delete method you must add the method field to ajax call and set the type to post.
as jQuery docs say about the type option: "Other HTTP request methods, such as PUT and DELETE, can also be used, but they are not supported by all browsers.
However, if you really want to do that, Symfony should handle this for any request, think of it as a form:
when you send a delete request from a form you should set the method attribute to post and add {{method_field('DELETE')}} in the form. in ajax you must do it like that except you pass the method field as data:
$.ajax({
url: route,
type: 'post',
data: {_method: 'delete'},
success: function....
In detail:
when you send a delete request from a form your form should look like this:
<form action="route" method="post">
{{csrf_filed()}}
{{method_filed('DELETE')}}
</form>
when you press a submit button laravel looks form input with the name of "_method" and matches the request with route method and URL.
So if you want to send a request through ajax you must do it the way you are doing right now, except you must add the method field in data that you send with ajax.
I have been trying to get the description to show up in a bootstrap modal. I can pull the price, quantity, list price, and title from the database but when I try to pull the data for the description it makes my info all disappear. I am trying to figure out why?
I have tried several different things and to no avail I have not been able to figure this issue out. I would love a answer to this issue. It is stopping the progress of my project that needs to be completed soon.
When I add description to the code my info disappears on the first modal button clicked. The 2nd modal button clicked shows all info but then whenI go to the 4th and 5th modal button I get the same info as the 4th modal button. When I take out description from SELECT then all data shows up in modal except for the description. I am at a loss and truly need more understanding of what I might have done wrong. Thank you for your time. The actual site is up http://www.pdnauction.com and right now the description is in the code so that it shows the issues.
$(document).ready(function(){
$(document).on('click', '#getProducts', function(e){
e.preventDefault();
var id = $(this).data('id');
$('#products-detail').hide();
$('#products_data-loader').show();
$.ajax({
url: 'empData.php',
type: 'GET',
data: 'id='+id,
dataType: 'json',
cache: false
})
.done(function(data){
console.log(data.title);
$('#products-detail').hide();
$('#products-detail').show();
$('#id').html(data.id);
$('#products_title').html(data.title);
$('#products_price').html("$"+data.price);
$('#products_list_price').html("$"+data.list_price);
$('#products_image').html(data.image);
$('#products_description').html(data.description);
$('#products_quantity').html(data.quantity);
$('#products_data-loader').hide();
})
.fail(function(){
$('#products-detail').html('Error, Please try again...');
$('#products_data-loader').hide();
});
});
});
<?php
include_once ("core/init.php");
if($_REQUEST['id']) {
$sql = "SELECT id, title, price, list_price, quantity, description FROM products WHERE id='".$_REQUEST['id']."'"; $resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
$data = array();
while( $rows = mysqli_fetch_assoc($resultset) ) {
$data = $rows;
}
echo json_encode($data);
}
?>
<div id="emp-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria- hidden="true"></button>
<h4 class="modal-title">
<i class="glyphicon glyphicon-user"></i> Product Description
</h4>
</div>
<div class="modal-body">
<div id="products_data-loader" style="display: none; text- align: center;">
<img src="ajax-loader.gif">
</div>
<div id="products_data-loader">
<div class="row">
<div class="col-md-12">
<div class="table-responsive">
<table class="table table-striped table-bordered">
<tr>
<th>Product</th>
<td id="products_title"></td>
</tr>
<th style="color: green">Price</th>
<td id="products_price" style="color: green"></td>
</tr>
<tr>
<th><s style="color: red">List Price</s></th>
<td id="products_list_price" style="color: #ff0000"></td>
</tr>
<tr>
<th>Quantity</th>
<td id="products_quantity"></td>
</tr>
<tr>
<th>Description</th>
<td id="products_description"></td>
</tr>
<tr>
<th>Gallery</th>
<td id="products_image"></td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
One issue (that may or may not be the primary cause, but you need to fix before you can really debug well) is you have many id's with the same value. An id must be unique. If you need two elements to have the same selector, e.g. "getProducts", use a class="getProducts" or a data- attribute. In my projects, I like to completely separate js and html/css, so I use data- attributes (there are some drawbacks, mainly speed to this method, but you can do more reading later on that).
So I would recommend:
1.) View the page source of your page
2.) Copy and paste it all into here: https://validator.w3.org/#validate_by_input
3.) Fix all the errors shown by the validator
If after that you still have an issue, come back and ask your question again and/or edit your question.
EDIT
Other than duplicate id's, you'll notice you have some issues with things like this:
alt="Boss Elite 320-Watt 6.5" Touch Screen Multimedia Car Stereo with Bluetooth, GPS and Rear View Camera - Black, BN965BLC"
The " after 6.5 is read by html as closing the alt tag, when actually you want to close the alt tag after BN965BLC. What you may want to look into there is URL encoding. https://www.w3schools.com/tags/ref_urlencode.asp Basically, a " symbol will be changed to %22, spaces are changed to %20, etc. so that the contents inside the alt tag won't affect the html. If you want to do that on the php side, take a look at rawurlencode(). If you want to do that on the js side, Encode URL in JavaScript?
The main source of your error is that your server does not respond for some of the ids, and apparently your javascript displays the details of the previously shown product.
Please note that the response from http://www.pdnauction.com/empData.php?id=1 and http://www.pdnauction.com/empData.php?id=5 are blank pages, while on http://www.pdnauction.com/empData.php?id=2 you have the expected results.
First, check your server side code in order to have the proper responses.
Second, make a check in your javascript .done() callback to display the modal only if you have answer from the server. Something like this:
// … existing code
})
.done(function(data){
if (!data.id) {
console.log('no response from server');
$('#products-detail').html('Error, Please try again…');
$('#products_data-loader').hide();
return;
}
// … existing code
})
.fail(function(){
// … existing code
I have JavaScript to change the value of an input tag whenever I open my popup in which it all executes successfully. When I inspect the tag, the value is exactly what it should be every time. Now within that popup I have, I just want to echo out the value using my PHP variable but this doesn't seem to work. I understand the whole concept of PHP is server side and JavaScript it client side but because the value is changed it should not matter as the value is there and PHP should be able to pick it up even when I reopen the popup.
Any idea how to achieve this?
My code is below. I can't have the page reload (e.g., use post methods and such).
HTML input tag:
<td class="alarmvalue" style="">
<input type="checkbox" name="tracknameneeds" id="tracknameneeds" style="text-align:center;" class="form-control" value="">
</td>
Code trying to echo input tags value:
<?php
$trackname = "<script>document.getElementByID('tracknameneeds').value;</script>";
?>
<!-- Play Options localstorage etc -->
<div class="context-menu">
<div id="modal-pl-playpopup" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="modal-pl-playpopup-label" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 class="modal-title" id="modal-pl-clear-label">Play Options</h3>
</div>
<div class="modal-body">
Choose from the following...<br>
<p>You Chose: <?php echo $trackname;?></p>
<br>
<br>
<i class="fa fa-plus-circle sx"></i> Add To Queue<br> <div style="padding-top:5px"></div>
<i class="fa fa-play sx"></i> Add And Play<br><div style="padding-top:5px"></div>
<i class="fa fa-share-square-o sx"></i> Add, Replace And Play
</div>
</div>
</div>
</div>
</div>
My JS:
var tracknamepopup;
tracknamepopup = o.data("path"); //assign song name to variable
document.getElementById('tracknameneeds').value = tracknamepopup; //assign the grabbed song name to inputs value to try grab that in php
All HTML code and Javscript execution is done (on client side) after PHP execution is complete on Server Side and response is sent to the client.
So you can not bind or assign HTML tag value to PHP directly.
But you can set it by AJAX and store it in session for next script execution on PHP.
Code in JS should be :
var tracknamepopup;
tracknamepopup = o.data("path"); //assign song name to variable
document.getElementById('tracknameneeds').value = tracknamepopup; //assign the grabbed song name to inputs value to try grab that in php
// you can write code for call update session varible using ajax
updateServerSession('tracknameneeds',tracknamepopup);
function updateServerSession(session_index,value) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "update_ajax?index"+session_index+"&value="+value, true);
xhttp.send();
}
Code in update_ajax.php
<?php
session_start();
$_SESSION[$_GET['index']]=$_GET['value'];
I think easiest way is to just use a get variable:
window.open("http://www.yoursite.com/popup.php?trackname=".concat(document.getElementByID('tracknameneeds').value));
and then use
$_GET['trackname']
But you should escape all get variables before posting!
What i did might not be the best solution but worked perfectly.
Have a blank tag (In my case i used a header (h1,h2 etc tag)) and give it an id. Use js to manipulate the Inner-HTML to display the current track.
HTML:
<h2 id="songbacktag"></h2>
JS:
var tracknamepopup;
tracknamepopup = o.data("path");
document.getElementById("songbacktag").innerHTML = tracknamepopup;