jQuery modal not show name after close and open - javascript

I create my custom modal window where i show image and that image contain comments and owner name. When i click on some image modal is opened and show big image, author name, comments etc... Problem is when i close current modal and opent it again name does not exist. But first time when i open modal name is there but only when i close that window and opent it again name does not exist. Check screenshots.
I try to debug it with firebook console and GET response return real name but that name is not rendered after closing and opening.
To prview image i use this code:
preview: function() {
$('body').on('click', '#open-picture-modal', function (e) {
e.preventDefault();
$("#photo_preview").show();
var $this = $(this);
var guid = $this.data('guid');
var photo_id = $this.data('id');
$.ajax({
method: 'post',
dataType: 'json',
url: baseurl + '/photo/preview',
data: {'photo_id': photo_id},
success: function(data) {
Photo.photo_author_meta(photo_id);
$(".pleft").html('<img class="fileUnitSpacer" src="'+ $this.data('href')+data['photo_name']+'">');
}
});
//window.history.pushState(null, null, pic_url);
// $(".image-source").attr("src", $this.data('href'));
});
},
// Close image preview modal
close: function() {
$("body").on("click", ".close", function(e) {
e.preventDefault();
$('#photo_preview').hide();
$('#photo_preview .pleft').html('empty');
$('#photo_preview .pright').html('empty');
});
},
// Show photo author meta(name, date created, etc..)
photo_author_meta: function(pid){
$.ajax({
method: "post",
dataType: 'json',
url: baseurl + '/photo/photo_details',
data: {'post_id': pid},
success: function(data) {
$("h4.photo-author-full-name").html(data['account_firstname'] +' '+ data['account_lastname']);
}
});
},
And here is modal where i append and set html
<div id="photo_preview" style="display:none">
<div class="photo_wrp">
<span class="pull-right close fa fa-times"> </span>
<div style="clear:both"></div>
<div class="pleft"></div>
<div class="pright">
<div class="photo-author-meta">
<div class="media">
<a href="#" class="media-left">
<img alt="64x64" data-src="holder.js/64x64" class="media-object" style="width: 64px; height: 64px;" src="test.png" data-holder-rendered="true">
</a>
<div class="media-body photo-author-name-box">
<div class="photo-author-name">
<h4 class="media-heading photo-author-full-name"></h4>
</div>
<div class="photo-datetime-box">
<div class="photo-date-posted"> Objavljeno: </div>
</div>
</div>
</div>
</div> </div>
<div style="clear:both"></div>
</div>
</div>
Like u can see on first image i have firstname and lastname in modal.
On second image i open again the some modal but name and surname does not exist. But check firebug console, data exist but not rendered.

Your close method is removing the HTML that renders the meta data.
$('#photo_preview .pright').html('empty');
That line is emptying all the HTML within . So, when photo_author_meta() is called a subsequent time after closing, h4.photo-author-full-name no longer exists.

You have various things:
1 - You are messing with .html() and .empty():
$('#photo_preview .pleft').html(); // or .empty()
2 - As you delete all the content from #photo_preview .pright, when you do:
$("h4.photo-author-full-name").html(data['account_firstname'] +' '+ data['account_lastname']);
This element don't exist. You could create it, or not empty all the div content.
You could change this:
$('#photo_preview .pright').html(); // or .empty()
to
$('h4.photo-author-full-name').html(); // or .empty()
In order to no delete the element, only the content on it.

Related

How to get values from a hidden field that is created in forEach with different values?

I’ve been working with jquery recently. I need to remove parameters from hidden fields that are created through forEach, that is, under class = "productID", the values ​​are different. How do I click on the button to take the value only from the desired hidden field.
<div id="successAdded" style="color: green">
<h3>${sessionScope.successAdded}</h3>
</div>
<c:forEach items="${sessionScope.allProducts}" var="products">
<div class="col-md-4 fashion-grid">
<a href="single.jsp"><img src="images/product/${products.imageName}" width="250" height="350" alt="" />
<div class="product">
<h3>PRODUCT NAME:</h3>
<input type="hidden" class="productID" value="${products.id}">
<span class="getName">${products.name}</span>
<p>${products.size}</p>
<p>${products.color}</p>
<p>${products.category.name}</p>
<p>${products.manufacturer.name}</p><br></br>
<p><span></span>${products.price}</p>
</div>
</a>
<div class="fashion-view"><span></span>
<div class="clearfix"></div>
<input type="button" class="addProductToCart" style="margin-top: 50%;" value="Add to cart" />
</div>
</div>
jQuery(document).ready(function() {
$('.addProductToCart').on('click', function getPage() {
var id = $(this).find('.productID').val();
alert(id);
$.ajax({
type: "GET",
url: "cart",
data: "productID=" + id,
success: function(page) {
$("#header men").text(page);
$("#productCount").text("(" + page['productCount'] + ")");
}
});
});
I get undefined value in my implementation
You have two issues here. Firstly, the hidden element has a class on it, so you need to prefix the selector with a ., eg. .productID.
Secondly, you're using find() from the clicked button to find the hidden field, yet it's not a child of this element. Instead it's a child of a parent's sibling. As such you need to combine closest(), prev() and find() to retrieve it, like this:
jQuery(document).ready(function() {
$('.addProductToCart').on('click', function getPage() {
var id = $(this).closest('.fashion-view').prev('a').find('.productID').val();
console.log(id);
$.ajax({
type: "GET",
url: "cart",
data: { productID: id },
success: function(page) {
$("#header men").text(page);
$("#productCount").text("(" + page['productCount'] + ")");
}
});
});
});

accessing jquery form and the parent of the a tag

With the following jQuery code.
$('#trade-offer form').on("submit", function(event) {
event.preventDefault();
var stock = $(this).closest('.allloopedover');
console.log(stock);
return;
$.ajax({
url: ajaxurl,
type: "POST",
dataType: 'json',
context: this,
data: $(this).serialize() + '&action=offer',
beforeSend: function() {
$('.alert-modal').remove();
$(this).closest('form').find('input').removeClass('form-error');
$(this).closest('form').find('.stm-ajax-loader').addClass('loading');
},
success: function(data) {
$(this).closest('form').find('.stm-ajax-loader').removeClass('loading');
$(this).closest('form').find('.modal-body').append('<div class="alert-modal alert alert-' + data.status + ' text-left">' + data.response + '</div>')
for (var key in data.errors) {
$('#request-trade-offer-form input[name="' + key + '"]').addClass('form-error');
}
}
});
$(this).closest('form').find('.form-error').live('hover', function() {
$(this).removeClass('form-error');
});
});
And the HTML code.
<div id="2012 FORD SUPER DUTY F-250 XLT" data-item="B01606" class="allloopedover listing-list-loop stm-listing-directory-list-loop stm-isotope-listing-item">
<div class="image">
<!--Video-->
<a href="http://x.com/listings/2012-ford-super-duty-f-250-xlt-2/" class="rmv_txt_drctn">
<div class="image-inner">
<!--Badge-->
<img width="300" height="225" src="http://x.com/blog/wp-content/uploads/2017/12/31-6-300x225.jpg" class="img-responsive wp-post-image" alt="" srcset="http://x.com/blog/wp-content/uploads/2017/12/31-6-300x225.jpg 300w, http://x.com/blog/wp-content/uploads/2017/12/31-6.jpg 640w" sizes="(max-width: 300px) 100vw, 300px"/>
</div>
</a>
</div>
<div class="content">
<div class="meta-top">
<!--Price-->
<div class="price offerc">
<div class="normal-price">
<span class="heading-font offercode">
<a class="rmv_txt_drctn" href="#trade-offer" data-toggle="modal" data-itemname="2012 FORD SUPER DUTY F-250 XLT" data-target="#trade-offer">Offer</a>
</span>
</div>
</div>
<!--Title-->
<div class="title heading-font mmbot">
<a href="http://x.com/listings/2012-ford-super-duty-f-250-xlt-2/" class="rmv_txt_drctn">
2012 FORD SUPER DUTY F-250 XLT
</a>
</div>
</div>
</div>
Now the div code it is not complete as it did not copied the whole code which is too big but it runs inside a loop and creates all the settings differently, notice the first div which have the
id="2012 FORD SUPER DUTY F-250 XLT" data-item="B01606"
and class as allloopedover.
now with jQuery, I want that when I click the submit button of a popup it should pass the id and data-item of that div, I tried using closest but that does not seems to be working, any idea?
When you attach a submit event handler to a form, the this inside your handler function will be the form itself, and not the button that you pressed to submit the form (which could be some div inside the form).
Therefore, $(this).closestwill traverse the parents of the form. If the div.allloopedover is inside the form that is being submitted, closest is not going to find it. If the div you're looking for is inside the form, you can get access to it with $(this).find(".alloopedover"). You should then be able to get the id and data-item value of that div from the jQuery object yielded by find.

How to get script variable value in php

I am using popup for showing message based on the id of click function.so i want get the id when popup is open in php. thanks in advance
<p>Link 1</p>
<a data-toggle="modal" data-id="ISBN564541" title="Add this item" class="open-AddBookDialog btn btn-primary" href="#addBookDialog">test</a>
<p> </p>
<div class="modal hide" id="addBookDialog">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h3>Modal header</h3>
</div>
<div class="modal-body">
<p>some content</p>
<?php //here i want to getting script variable value for database purpose?>
</div>
</div>
and my script is
$(document).on("click", ".open-AddBookDialog", function () {
var myBookId = $(this).data('id');
$(".modal-body #bookId").val( myBookId );
});
in ajax call i am getting the id from the next page but i want value in same page
function viwpost(id) {
var pid=id;
$.ajax({
type: "POST",
url: "view_more.php",
data: "pid=" + pid ,
success: function(data)
{
$("#myModal21").html(data);
}
});
}
Since you're already using jQuery framework/API:
you can simply use the
$.get('phpfile.php' { id: myBookId }).done(function (response) { alert(response); });
your PHP file can pick the request up like this:
$_GET['id'];
If you're trying to make a live pop-up to load the data, this is an incorrect method of doing so. PHP script is only loaded once on server running and sending a request will only give you a response so ensure you research.
I'd suggest you create your PHP file to echo out the data you want to pop-up.
Demonstration of PHP file to send a response back to the request (as requested):
if(isset($_GET['id']))
{
echo 'what ever is outputted to the client will be received in the response';
}
Hey there is mistake in getting id of the link. You can use like this -
first create input type hidden and set its id bookId in model body like this:
<input type="hidden" id="bookId" />
$(document).on("click", ".open-AddBookDialog", function () {
var myBookId = $(this).attr('data-id');
$(".modal-body #bookId").val( myBookId );
});

TinyMCE not being added to element on AJAX call

I'm having some issues applying TinyMCE onto the textarea element.
I have a page with a list of passengers. When you click a passsenger, AJAX is called and it displays info for the passenger, one field which happens to be a textarea element. My problem is that the first passenger (any passenger) you click on loads TinyMCE, but from here on out, it's just a normal textarea with no TinyMCE applied. I don't know what's happening. Here is the following code I have:
j$ = jQuery.noConflict();
j$(document).ready(function(e) {
tinyMCE.init({
mode : "textareas",
theme : "advanced",
theme_advanced_buttons1 : "bold, italic, underline, | ,bullist, numlist, | ,outdent, indent, | ,link, unlink, |, code",
relative_urls : false,
remove_script_host : false,
});
j$('.names strong').click(function(e) {
//Find passenger ID
var customer_ID = j$(this).closest('.passenger_Container').find("input[name='customer_ID']").val();
//Find placement of returned data
var insert_Data = j$(this).closest('.passenger_Container').find('.package');
j$.ajax({
type: "POST",
url: "/include/passenger_Detail.php",
data: { customer_ID_Data : customer_ID },
success: function(data) {
//get returned data and add into appropriate place
insert_Data.html(data);
var oldEditor = tinyMCE.get('notes');
if (oldEditor != undefined) {
tinymce.remove(oldEditor);
}
tinyMCE.execCommand('mceAddControl', false, 'notes');
//re-initialise WYSIWYG editor. Notes is the ID to re-initialize
/*tinymce.execCommand('mceRemoveControl',true,'notes');
tinymce.execCommand('mceAddControl',true,'notes');*/
}
});
});
});
<!-- content is displayed using PHP while loop -->
<div class="passenger_Container bottom-buffer">
<div class="names row">
<div class="col-xs-1 text-center">
<!-- Display checkbox -->
</div>
<div class="col-xs-4 col-sm-3">
<strong><?php echo $row['f_Name'].' '.$row['l_Name']; ?></strong> </div>
<div class="col-xs-3 hidden-xs">
<!-- display child names -->
</div>
<div class="col-xs-3">
<!-- Display order status -->
</div>
<div class="col-xs-1 col-sm-2">
<!-- Display form -->
</div>
</div>
<div class="package custom-well well-sm top-buffer">
<!-- passenger detail goes here. You will find the code in includes/passenger_Detail.php -->
</div>
</div>
<!-- end PHP while loop -->
I have left the examples I have tried to get TinyMCE to work. I have a sneaky suspicion bad coding practice is the culprit. Each of the textareas have an ID of #notes which I think is the cause. But looking at documentation I don't think tinyMCE lets you use classes to target textareas. Unless I have to loop through all textareas. I'm just spitballing here.
Please inform me if more info is required. Thanks again.
I ended up solving the issue but using a unique ID for each of the textarea elements. So instead of each textarea having the ID "notes", it is now "notes_unique customer_ID".
Following is my answer:
j$.ajax({
type: "POST",
url: "/include/passenger_Detail.php",
data: { customer_ID_Data : customer_ID },
success: function(data) {
//console.log("Returned data: "+data);
//get returned data and add into appropriate place
insert_Data.html(data);
notes = insert_Data.find('textarea').attr('id');
var oldEditor = tinyMCE.get('notes_'+customer_ID);
if (oldEditor != undefined) {
tinymce.remove(oldEditor);
}
tinyMCE.execCommand('mceAddControl', false, 'notes_'+customer_ID);
}
});

hide div depending on ajax response result

I want to hide a div depending on the result of the response from an ajax call to my server. My server is responding with an object {available: yes/no} depending on the domain and username searched for. If the response if yes I want to maintain the div on the available column of my html and hide the corresponding div on the unavailable column and if the response is no hide the div on the available column and maintain the div visible on the unavailable column.
My problem is attaching each response to the corresponding div. How could I do this?
html:
<div id="searchresults">
<div id="available">
<h4><span class="username"></span><span class="positive-result">is available</span> as a username on:</h4>
<div class="facebook"> <!--Class to hide and show this div can be toggled with jQuery -->
<i class="fa fa-facebook-square"></i>Facebook
</div>
<div class="pinterest"> <!--Class to hide and show this div can be toggled with jQuery -->
<i class="fa fa-pinterest"></i>Pinterest
</div>
<div class="twitter"> <!--Class to hide and show this div can be toggled with jQuery -->
<i class="fa fa-twitter"></i>Twitter
</div>
<div class="instagram"> <!--Class to hide and show this div can be toggled with jQuery -->
<i class="fa fa-instagram"></i>Instagram
</div>
<div class="github"> <!--Class to hide and show this div can be toggled with jQuery -->
<i class="fa fa-github"></i>GitHub
</div>
</div> <!--End of #available-->
<div id="unavailable">
<h4><span class="username"></span><span class="negative-result">is not available</span> as a username on:</h4>
<div class="facebook-unavailable"> <!--Class to hide and show this div can be toggled with jQuery -->
<i class="fa fa-facebook-square"></i>Facebook
</div>
<div class="pinterest-unavailable"> <!--Class to hide and show this div can be toggled with jQuery -->
<i class="fa fa-pinterest"></i>Pinterest
</div>
<div class="twitter-unavailable"> <!--Class to hide and show this div can be toggled with jQuery -->
<i class="fa fa-twitter"></i>Twitter
</div>
<div class="instagram-unavailable"> <!--Class to hide and show this div can be toggled with jQuery -->
<i class="fa fa-instagram"></i>Instagram
</div>
<div class="github-unavailable"> <!--Class to hide and show this div can be toggled with jQuery -->
<i class="fa fa-github"></i>GitHub
</div>
</div> <!--End of #unavailable-->
Javascript using jQuery
$(document).ready(function(){
console.log("Ready!");
var domains=[ ];
domains.push($(".facebook").find("a").text());
domains.push($(".github").find("a").text());
domains.push($(".twitter").find("a").text());
domains.push($(".instagram").find("a").text());
domains.push($(".pinterest").find("a").text());
// console.log(domains);
$("#searchbutton").on('click', function(event){
var username = $("#searchname").val().trim(); // store value from searchbox
console.log(username);
if(username === ""){
event.preventDefault();
}
if(username){
var newhtml = "<p>";
newhtml += username;
newhtml += "</p>";
$(".username").html(newhtml);
$(".username").remove("newhtml");
var domainCheck = function(domainName){
$.ajax({
url: "/"+username,
type: "get",
data: {domainName: domainName, username: username},
success: function(response){
console.log(domainName);
console.log(response.available);
//hide show logic here
var elem = $("#available").find("div"); returns an array of divs for each search result
console.log(elem);
}
});
};
//send ajax request to server for each domain name to check for username availability
var len = domains.length;
for(var i = 0; i<len; i++){
domainCheck(domains[i]);
console.log(domains[i]+'\n');
}
}
});
});
Your response data type looks JSON, not simple text. So, first of all you should pass the correct dataType argumento to ajax call:
$.ajax({
url: "/"+username,
type: "get",
data: {domainName: domainName, username: username},
dataType: "json",
[...]
then you can easily access the data inside your success() method as follows:
success: function(response){
if(response.available === "yes") {
//show?
} else if(response.available === "no") {
//hide?
} else {
//wtf?
}
}
You can probably adapt this:
on document load -> condition -> show or hide. You would only need to edit 'if ($("#maincontent").width() < 600){'
'$( document ).ready(function() {
if ($("#maincontent").width() < 600){
$( "#toolbarright").hide();
} else { $("#toolbarright").show();}
});'
http://jsfiddle.net/ablueman/vdgeLsgL/

Categories

Resources