AJAX dropdown within toggle(function) only works once - javascript

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.

Related

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

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.

place results in a textbox after click

i'm working on an auto complete with jquery which is working perfectly. the results get displayed as the user types. Now the problem is when the user starts typing and the results appear, when the user clicks on the desired results, it doesn't get placed in the textbox
JS
$(function(){
$(".search_tab").keyup(function()
{
var searchid = $(this).val();
var dataString = 'fname='+ searchid;
if(searchid!='')
{
$.ajax({
type: "POST",
url: "http://localhost/myapp/search.php",
data: dataString,
cache: false,
success: function(html)
{
//console.log(html)
$("#result").html(html).show();
}
});
}return false;
});
$('.search_tab').click(function(){
jQuery("#result").fadeIn();
});
});
HTML
<input type="text" class="search_tab" placeholder="Search" autocomplete="off">
<div id="result"></div>
You'll need to do some event delegation over the items that get placed into the div#result element. You'll want something like this:
$('#result').on('click', 'RESULT_ITEM', function (event) {
$('input.search_tab').val(event.target.innerHTML);
});
Where RESULT_ITEM is a selector that matches the individual items that are listed in the autocomplete results.
While i dig into this have you considered using jQuery UI to acomplish this?
https://jqueryui.com/autocomplete/
This is a nice and polished way of doing exactly what you are wanting.
Not quite sure why I am getting down voted really as my suggestion is a perfectly valid solution to this problem...
That being said here is a working fiddle for you.
https://jsfiddle.net/wxr5y5gu/
The main part you seem to be missing is something like this:
$('#result').on('click','li',function(){
/* I used li as the element as im unsure what your response html looks like */
let newValue = $(this).text();
$('.search_tab').val( newValue );
$('#result').html('').hide();
});
That will clear the results, set the clicked value, and hide the results box for you.
That contains a working soution for you. As i dont have access to AJAX your local resources I had to extrapolate and create my own auto fill to show how it works in principal however i can certainly help you tailor the solution to your needs.
This solution uses your code and is compatible with all current jQuery versions.

jquery Post value to PHP webpage

I have made a web page with a dropdown menu. The idea is when we click any option of the dropdown menu it open produccion.php with a POST parameter 'edicion'. This parameter I use to do a query in a Database.
At moment the problem is that it's open the produccion.php but I think that doesn't POST the value of the variable
Jquery code:
$('#drEdicion a').click(function(event){
alert($(this).text());
var ed = $(this).text();
$.ajax({
url:"produccio.php",
type:"POST",
data:{edicion: ed},
dataType:"text",
success:function(data){
window.location.href = 'produccio.php'
}
});
});
Is it possible that the problem is when it's send via ajax?
Thanks in advance.
Your code is currently POSTing the content of the hyperlink over to produccio.php via AJAX. When that call completes it is then redirecting the user to the same page but without the POSTed value. Based on your comment:
I want to open produccion.php after selection option in dropdown button. With this option I do a query
it appears you actually want to open produccio.php with the POSTed value in the browser.
By far the easiest solution to the problem would be to alter the PHP code to accept the value of edicion from $_GET["edicion"] instead, and output your hyperlink as:
...
This will also provide a better experience for users, especially if they have issues with JavaScript (or, for example, happen to be a search engine). However, if you're set on only using $_POST, the following code may - I've not tested this myself - allow this:
$('#drEdicion a').click(function(event){
event.preventDefault();
var ed = $(this).text();
$('<form action="produccio.php" method="POST">' +
'<input type="hidden" name="edicion" value="' + ed + '" />' +
'</form>').appendTo('body').submit();
});
(with credit to the top answer on Dynamically create and submit form)
Follow bellow code :
$('#drEdicion a').click(function(event){
//alert($(this).text());
event.preventDefault();
var ed = $(this).text();
$.ajax({
url:"produccio.php",
type:"POST",
data:{edicion: ed},
dataType:"html",
success:function(data){
//#dropdown-menu id show all produccio.php data
$("#dropdown-menu").html(data);
}
});
});
produccio.php
<?php
$edicion = $_POST['edicion'];
//now you can able to access edicion post param
?>
HTML like this :
<div id="dropdown-menu"></div>

Using jquery to submit one form on page that shares element names with other forms

To give you the most basic view of my question, I'm trying to create a page that is very similar to how facebook and twitter's dashboards and comment systems work. You have one page that will continuously create form elements (posts) from database rows in a loop as the user scrolls down. Users will then be able to comment on each of these posts. I want to be able to use ajax to submit comments on each post individually without reloading the page.
I run into a problem where when I try to submit a comment on any form other than the first one that is loaded on the page. In addition the ajax only posts the first form elements on submit (due to each form and elements having the same name I'm guessing).
Below is my comment loading script: [forgive the old php, I know I need to update it to mysqli or PDO]
php
<?php ...
$query = mysql_query("SELECT * FROM `posts`");
while ($row = mysql_fetch_array($query)) {
echo "
<div name='comment_body'>
<form name='comment_form'>
<td>User: ".$row['user']."</td>
<td>Post: ".$row['post']."</td>
<textarea name='comment'></textarea>
<p name='post_id' style='display:none;'>".$row['post_id']."</p>
<input type='submit' name='submit'>
</form>
";
$query2 = mysql_query("SELECT * FROM `comments` WHERE `post_id` = $row['post_id']");
while ($row2 = mysql_fetch_array($query2)) {
echo "
<td>User: ".$row2['user']."</td>
<td>Comment: ".$row2['comment']."</td>
</div>
";
}
... ?>
jscript
<script>
$('.comment_form').on('submit', function (e) {
e.preventDefault();
$.ajax ({
type: 'post',
url: 'submit_comment.php',
data: {comment : $('#comment').val(), post_id : $('#post_id').text()}
success: function() {
$("#comment_body").load("load_comments.php #comment_body");
}
});
});
</script>
The script works to a point because when I comment on the first post, it works as expected. I just can't seem to figure out how to target the forms further down the page individually. Here's an example:
The very top post has a post_id value of 40. If I comment on post_id = 38, ajax will submit the empty comment field and post_id = 40 into the database.
Any help with the script form targeting would be great. If I need to rebuild my php query to give each echoed form element an individual name, that's fine as well. Thanks in advance!
The data you're trying to send to in the ajax call is using:
$('#comment').val(), post_id : $('#post_id').text()
But your HTML doesn't have anything with an ID="comment" and ID="post_id". (the '#' in your selector means getElementById.) So you aren't sending any data to your php page. You need to use the correct selectors to get that data. (see below)
Get rid of the 'form' tags you don't need them. Change your
<input type="submit">
to a:
<input type="button" class="comment-submit">
Then your script can be:
<script>
$('.comment-submit').on('click', function (e) {
e.preventDefault();
// get a referenct to this particular comment_body div
var $commentbody = $(this).closest('.comment_body');
// find the textarea within this particular comment_body
var commenttext = $commentbody.find('textarea[name="comment"]').val();
// find the post_id paragraph within this particular comment_body
var postId = $commentbody.find('p[name="post_id"]').text();
$.ajax ({
type: 'post',
url: 'submit_comment.php',
data: {comment : commenttext , post_id : postId}
success: function() {
$comment_body.load("load_comments.php #comment_body");
}
});
});
</script>
Frankly I'm not sure what your success function is trying to do. But I think you need to work on it too. Normally an ajax call will return data so your success function should have a return value and that would be used to populate some part of your screen. The jQuery 'load()' function is another ajax call inside the success callback of an ajax call. I really don't think you want or need to do this.
You cannot select a unique form by class because your class is identical across all forms. Add an "id" field to the form element like this:
"<form name='comment_form' id='"+ .$row['id'] +"'>"
Then select a given form using that unique ID, and add your event handler. This must be in the same scope as you define your form. Like this:
$('#'+ .$row["id"]).on('submit', function (e) {
//Handle the event
})

Jquery: bind several dynamically added elements to an html() event

I have in my page several dropdowns that will be dynamically updated using AJAX, in this way:
$.ajax({
data: parametros,
url: 'getList.php',
type: 'POST',
success: function (response) {
element.html(response);
}
The dropdowns have names in this format:
<select id="elemento_1" class="dropdowns">
<select id="elemento_2" class="dropdowns">
<select id="elemento_3" class="dropdowns">
The PHP responds with a string response in the form <option value=1>Bla<option value=45>Ble … and it gets appended to the dropdown. You get the idea.
Initially there's only one dropdown, but whenever the user clicks a button, a new dropdown will be added and loaded using the method above, and I want it to have by default the same value than the previous dropdown. After reading this answer about how to trigger html() events:
https://stackoverflow.com/a/3616565/470994
I changed the code above to the following:
$.ajax({
data: parametros,
url: 'getList.php',
type: 'POST',
success: function (response) {
element.html(response).triggerHandler("cambia");
}
$(".dropdowns").unbind().bind("cambia", function() {
var nombre=this.id;
var numero=parseInt(nombre.slice(-1));
alert("Mooooo " + numero);
if (numero > 1) {
var anterior = $("#elemento_" + (numero - 1)).val();
this.find("option[value='" + anterior + "']").prop("selected", "selected").change();
}
});
Which inspects the dropdown in question and, if it's not the first one, will get the value of the previous dropdown and load it in the current one.
Now, this is all fine and well… except that, in my tests, the event only gets triggered when the first dropdown is loaded (the alert("Moooo") only appears in the first dropdown). If I press the button, the 2nd, 3rd… dropdowns appear, but the event isn't triggered. I suspect that it's because of the explanation here:
https://stackoverflow.com/a/6173263/470994
(bind only works for the elements that exist initially, not the ones added later).
The suggested solution is to use on()… but I don't know exactly how to use it to capture custom events like the one I've defined for html() changes. Can you even do that? Is there any other solution?
Thanks.

Categories

Resources