Passing loop data as variable from JavaScript to AJAX via Bootstrap modal - javascript

My code below was used to retrieve records from a loop using JavaScript. Everything works fine. Each of the records button has a unique id that when click
should alert users_id in a Bootstrap Modal popup.
The problem is that the looped button that contains users_id is not alerting anything when each button is clicked.
Below is the code for retrieving records in JavaScript along with Bootstrap modal button:
<script>
$(document).ready(function () {
$.post('users.php', function(response){
$.each(JSON.parse(response).items, function(i,v) {
$('.userslist').append('<span>'+v.id+'</span> Profile');
});
});
});
</script>
Below is the code for posting the users_id and then alert it:
<script>
$(document).ready(function(){
$(".modalLink").click(function() {
var id = $(this).attr("id");
alert(id);
var dataString = 'id='+ id;
$.ajax({
type: "POST",
url: "ajax_modal.php",
data: dataString,
cache: false,
success: function(data) {
$("#rmm").html(data);
}
});
});
});
</script>
but if I take the Modal button outside the retrieve records in a javascript loop
it will alert users_id and everything will work fine as in code below
Profile
Can someone help me make each of the JavaScript looped button to post its own unique users_id and then alert it in a Bootstrap modal popup. I have attached a screen shot of the result obtained from the JavaScript loop.
Thanks

If I understand your question properly;
Try changing
$(".modalLink").click(function() {
to
$(document).on('click', '.modalLink', function() {
Without seeing the rest of your code or a working fiddle, I suspect your content is dynamic and JQ cannot bind the click handler, simply because there is no content to bind to. this answer does a good job of explaining the difference between .on and .click.
If you get the expected result, I would drop the document selector and use the closest parent static element.

Related

Attach jquery events to dynamically created elements (jquery load php file)

I have a php employee directory website that lists all our employees in a table (connected to mysql), and you are able to click each employee to open up their details in another div.
$('.emptab').click(function(event) {
var status = $(this).attr('id');
$("#empview").load("employee.php", {'data': datastring, 'current': status});
});
I originally had the above code, but needed to be able to attach events to dynamic elements, so I changed to the following code:
$('tbody').on('click', 'tr.emptab', function() {
var status = $(this).attr('id');
$("#employeedetails").load("employee.php", {'data': datastring, 'current': status});
});
I did it that way as I read in another question (In jQuery, how to attach events to dynamic html elements?) that you can use that format to attach events to dynamic elements. Just to clarify, this code continues to work with the initial page, but fails after the search filter is used.
My dynamic elements comes from a filter/search function I have that will change the list of employees based on a search text box which changes the list of employees based on a filter.php document I created.
$('#search').on('input propertychange paste', function() {
var string = $('#search').val();
$("#employeelist").load("filter.php", {'data': datastring, 'search': string});
});
However, when those elements are created from that php file, I am unable to access the elements through my jquery, I'm not sure what I'm doing wrong. There were about 4 other questions I saw where the answer was to use the jquery on function, which I've tried with no success.
Thanks for your time.
You can use following code for this
$(document).on('click', '.emptab', function() {
var status = $(this).attr('id');
$("#employeedetails").load("employee.php", {'data': datastring, 'current': status});
});

Dropdown jQuery box to close after clicking outside

I'm looking to get that a dropdown box closes after clicking outside of it with jquery. I've tried the below code already but seems something is not working correctly, so when I remove the part from "body: not(ul.nav li.dropdown)", the script executes well but it doesn't close outside obviously, and when I insert the close part, the script doesn't execute properly. What can be wrong in this syntax or in code that is avoiding both closing and execution to work correctly together?
$(document).ready(function(){
jQuery('ul.nav li.dropdown').click(function() {
jQuery(this).find('.dropdown-menu').fadeIn();
$("#actionStatus").html("");
});
$("body:not(ul.nav li.dropdown)").hover(function(){
$("ul.nav li.dropdown").find('.dropdown-menu').fadeOut();
});
$("#btnSendOption").click(function(){
var data = $("#frmUserOption").serialize();
$.ajax({
url: "/users.php",
data: data,
success: function( data ) {
$("#actionStatus").html("");
$("input[type='radio']").attr('checked', false);
$('.dropdown-menu').delay(1000).fadeOut();
},
error: function(data) {
$("#actionStatus").html("<div class='alertMsg alertMsg-danger'>Error, try again later</div>");
}
});
});
});
Thank you in advance

onClick Modal Dialog

Similar to: jquery modal dialog onclick?
However I have a different requirement and cannot apply the solutions provided in that post.
At the moment I am using JQuery within php to parse through an xml file and produce content on a HTML page:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: "uploads/data.xml",
dataType: "xml",
error: function() {
$('#message').text('Please upload the XML file.');
},
success: xmlParser
});
});
function xmlParser(xml){
$('.tmpli').hide();
$(xml).find("vendor-one").each(function(){
$("#vendor-one").append('<li class="sweet">' + $(this).find("name").text() + '</li>');
$(".sweet").fadeIn();
});
}
</script>
I attempted an alert triggered by onClick however it's not able to contain images:
$(xml).find("vendor-one").each(function(){
$("#vendor-one").append('<li class="sweet" onClick="alert(\''+$(this).find("name").text()+'\');">' + $(this).find("name").text() + '</li>');
$(".sweet").fadeIn();
});
I then attempted this however it opens a dialog box for every li element on the page and I'm unsure how to edit the text and add an image:
$(xml).find("vendor-one").each(function(){
$("#vendor-one").append('<li class="sweet">' + $(this).find("name").text() + '</li>');
$(".sweet").fadeIn();
$('li.sweet').click(function(){ $('li.sweet').dialog(); });
});
I need a facility where I am able to click on each individual li item created and have a message box appear that contains an image and text.
I was intending to use this: Modal Dialog however I'm unsure of how to mend it to my needs.
How do you do this?
Instead of using the manual onclick inline option, you can use the Javascript way to do it.
document.getElementById('ElementID').addEventListener('click', function(event){
console.log(event);
});
Or the JQuery way (which results in the same thing) :
$('#ElementID').click(function(event){
console.log(event);
});

AJAX dropdown within toggle(function) only works once

I have a table where rows are dynamically added.
In one of the cells I would like to toggle between a dropdown and an input box.
The dropdown is a PHP file loaded via AJAX. The issue is the dropdown only renders once.
First time you click the toggle button, the dropdown appears, as it should.
Second click switches it to the input field, as it should.
Third click does nothing, it just stays on the input box and does not toggle back to the dropdown.
If I comment out the AJAX call and put in a simple dropdown, it toggles back and forth just fine. So I believe the issue is with the AJAX portion.
Link to http://jsfiddle.net/6h5BD/1/
NOTE: the AJAX is currently commented out in jsfiddle and replaced with a temp dropdown so you can see what results I am looking for.
The portion of JS in question:
$('input[name="button"]').toggle(function() {
$.ajax({
url: 'http://localhost/brandDropdown.php',
type:'POST',
dataType: 'html',
success: function(output_string){
$('#brand').html(output_string);
}
});
}, function() {
$(this).closest('td').prev().html("<input type=\"text\" name=\"itemBrand[]\" id=\"itemBrand\" size=\"10\" placeholder=\"New Brand\" style=\"text-transform: uppercase\"/>");
});
The PHP:
$sqlbrand = "SELECT BRD_Name FROM Brands ORDER BY BRD_Name asc";
$resultbrand = odbc_exec($conn, $sqlbrand);
ECHO "<select name='itemBrand[]' style='width:120px' size='1'>";
while ($rowbrand = odbc_fetch_array($resultbrand)) {
echo "<option value='".$rowbrand['BRD_Name']."'>".$rowbrand['BRD_Name']."</option>";
}
echo "</select></td>";
I am very open to handling this in a different manner. I have tried several different approaches, but to no avail.
Thank you in advanced for any assistance with this issue.
I cant completely help you debug if I can't see the PHP file.
But from the HTML/JS I can see a potential problem. You are selecting $("#brand") and changing the html to the output_string. But when you are cloning your rows, you are making multiple divs with id of #brand and ids are supposed to be unique, you should use class instead.
Can you try if this works?
$('input[name="button"]').toggle(function() {
var $this = $(this);
$.ajax({
url: 'http://localhost/brandDropdown.php',
type:'POST',
dataType: 'html',
success: function(output_string){
$this.closest('td').prev().html(output_string);
}
});
}, function() {
$(this).closest('td').prev().html("<input type=\"text\" name=\"itemBrand[]\" id=\"itemBrand\" size=\"10\" placeholder=\"New Brand\" style=\"text-transform: uppercase\"/>");
});
In your code (in the fiddle)
$(this).closest('td').prev().html(...)
should be
$(this).closest('td').prev().find('#brand').html(...)
because $(this).closest('td').prev().html(...) is replacing the html of td which means it's just removing the div with id #brand from within the td so in your ajax success callback $('#brand').html(output_string); is not working because it's not inside the td once you toggled it.

Javascript doesn't affect html code added with javascript

I'm using jquery and uploadify to upload photos to server. After uploading photos they are added to a div container using ajax. Everything works great except DELETE button. All delete buttons work on page load but those added via ajax don't work. I suppose that's because I defined function that enables image deletion and didn't use 'classic' way of deleting (form deletion):
// Delete photo
$(".blog_slike .delete_slika").click(function() {
var commentContainer = $(this).parent().parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
type: "POST",
url: "./include/ajax-edit/delete.php?polje=blog_slika",
data: string,
cache: false,
success: function(){
commentContainer.fadeOut("slow");
$('#load').fadeOut();
}
});
return false;
});
Any idea how to make button work after it's added to html code using append() function?
One more thing... to add photos to tinymce editor I use this function:
Ubaci sve slike u blog
...which was also added on page load. How can I add content to place where is $slike_u_sadrzaj located and how to delete it?
Thanks,
Ile
You need the jquery live method.
Added in jQuery 1.3: Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events.
jQuery documentation
Sample code:
$(".blog_slike .delete_slika").live('click',function() {

Categories

Resources