Generic jquery structuration question - php

please take a look of this:
$(function () {
$("#add").click(function() {
val = $('#add_lang').val();
val1 = $('#add_lang_level').val();
listitem_html = '<li>';
listitem_html += val + ' <strong>('+ val1 + '/100)</strong>';
$.ajax({ url: 'addremovelang.php', data: {addname: val,addlevel: val1}, type: 'post', success: function(output) { alert(output); }});
listitem_html += 'Remove'
listitem_html += '</li>';
$('#langs').append(listitem_html);
});
$('.remove_lang').live('click', function(e) {
e.preventDefault();
$(this).parent().remove();
$.ajax({ url: 'addremovelang.php', data: {delname: val}, type: 'post', success: function(output) { alert(output); }});
});
});
This simple jquery script adds strings to a html list when the user hits the button with the id add. Also, it puts a remove link to each line, so when the user hits remove it triggers the function remove_lang and the string is deleted.
When the users add a string, this text comes from a text field, and i stored it on the variable val (as you can see on the 5 line of the code). Then i call a php script via Ajax to add this info to my mysql database.
But, when the user remove the string, i dont know how to know what string was removed, i mean, the name of this one, that i need to send to my php script in order to remove it from the database.
Take a look of this version of my code without the ajax call: http://jsfiddle.net/wnFsE/
Thanks for any help!!!

When you click remove you can do something like this:
val = $(this).parent().find('input').val();
That will get the value from hidden input you added:
Demo Here

You need to think about the string as instead a group of elements:
var li = $('<li/>');
var strong = $('<strong/>', { text: '(' + val1 + '/100)' });
var link = $('<a/>');
link.click(function()
{
// Insert code here for the link click
});
li.append(strong).append(link);
$('#langs').append(li)
There are other patterns that would work too, like:
$(listitem_html').find('a').click(function()
{
// Insert code here for the link click
});
Just get a reference to the element, and then attach the click event handler.

An Object Oriented Programming approach would help keep the actions very organized. You basically store the actions for each given language in an object, modifying the action for that language whenever it's removed or added.
Here's a live example that will print that "storage" object out to the console every time you add or remove a language so that you can clearly see what's going on.
And here's just the JS code (you'll notice that I barely changed a thing):
languageActions = {}
$(function () {
$("#add").click(function() {
val = $('#add_lang').val();
listitem_html = '<li>';
listitem_html += val;
listitem_html += '<input type="hidden" name="languages[]" value="' + val + '" /> ';
listitem_html += 'Remove'
listitem_html += '</li>';
$('#langs').append(listitem_html);
//now add it to our object
languageActions[val] = 'add';
console.log(languageActions);
});
$('.remove_lang').live('click', function(e) {
e.preventDefault();
val = $(this).prev().val();
$(this).parent().remove();
//now change it's value in languageActions
languageActions[val] = 'remove';
console.log(languageActions);
});
});
The only other thing I'll point out is that you don't really need that hidden input element since you're doing this via AJAX rather than a standard form submit. Instead, you could just do <li><span>Spanish</span><a class="remove_lang">Remove</a></li> for your HTML and then the click event on .remove_lang would do $(this).prev().text() rather than $(this).prev().val(). Not a huge deal, but you're HTML will be a little cleaner.

I guess that would be a simple:
$i = 1;
while(xxx){
//get the list with a different value for each element
echo '<div id="add_' . $i . '>$whatever</div>';
$i++;
}

Related

Insert link to a php page using jquery

I am planning to insert a link to my another php page using jquery function, but the code doesn't work... Alternative methods such as attr() has been tried as well, but it was still the same result... Can someone pls give me advices regarding this matter? Following are my codes:
$(document).ready(
function(){
$('#date').change(
function(){
$.ajax (
{
url: 'process.php',
type: 'post',
data: {
item_no:2,
movie_id: $('#movie').val(),
movie_date: $('#date').val()
},
dataType: 'json',
success: function(response){
$('#showtime').empty();
for(var i = 0; i<response.length; i++){
var showtime = response[i]['showtime'];
$('#showtime').append("<a href='movie_seat.php?id="+showtime+"' id='seatlink'>");
$('#showtime').append("<font style='margin-right:50px;'>");
$('#showtime').append(showtime);
$('#showtime').append("</font></a>");
} // for loop
} // function taking response
} // block in ajax
); //ajax
} // function inside change
); // select->date change
} // function inside ready
); // document.ready
*Note that #showtime is the id of a attribute
My expectations:
The value displayed should be able to work as a link that will direct the user to another php page. But apparently, it doesn't....
You need append all together, because if you append something like this:
$('#showtime').append("<a href='movie_seat.php?id="+showtime+"' id='seatlink'>");
$('#showtime').append("<font style='margin-right:50px;'>");
$('#showtime').append(showtime);
$('#showtime').append("</font></a>");
That way the tags will be closed, and you html will seems like this:
<font style="margin-right:50px;"></font>
showtime
So what you need to do is append all together, i mean tags inside tags, try this:
var link = "<a href='movie_seat.php?id="+showtime+"' id='seatlink'>"
+ "<font style='margin-right:50px;'>"
+ showtime
+ "</font></a>";
$('#showtime').append(link);

Codeigniter: button which contains data doesn't seem to pass a specific data

I'm working with a modal+ajax+mvc CRUD and create works fine, but fetching a specific data (data-emiD="'+data[i].m_ID+'") is not working unlike the others that is passed through the button. Why is that? 'm_ID' is AI and INT in my database. I want to DISPLAY m_ID in my edit modal but it's not working.
tried editing the naming convention on the button in each data, but still only the m_ID is not working.
here's my ajax that fetch all data from the database and display in my view
function show_manager(){
$.ajax({
type: 'ajax',
url: 'admin/managers',
async: true,
dataType: 'json',
success: function(data){
var html = '';
var i;
for(i=0; i<data.length; i++){
html += '<tr>'+
'<td>'+data[i].m_ID+'</td>'+
'<td>'+data[i].m_username+'</td>'+
'<td>'+data[i].m_fname+'</td>'+
'<td>'+data[i].m_status+'</td>'+
'<td>'+data[i].m_lastlogintime+'</td>'+
'<td>'+data[i].m_lastloginIP+'</td>'+
'<td>'+data[i].m_loginsystem+'</td>'+
'<td style="text-align:right;">'+
<!----here is the btn that does not pass m_ID--->'Edit'+' '+
'Delete'+
'</td>'+
'</tr>';
}
$('#show_data').html(html);
}
});
}
here is where I want to display the m_ID value in my edit modal which is to verify that I'm fetching it from the datatable/database
$('#show_data').on('click','.manager_edit',function(){
var emid = $(this).data('emiD');
var estatus = $(this).data('m_status');
var epassword = $(this).data('m_password');
var efullname = $(this).data('m_fname');
var eemail = $(this).data('m_email');
var eusername = $(this).data('m_username');
$('#Modal_Edit').modal('show');
$('[name="emid"]').val(emid);
$('[name="eusername"]').val(eusername);
$('[name="estatus"]').val(estatus);
$('[name="efullname"]').val(efullname);
$('[name="epassword"]').val(epassword);
$('[name="eemail"]').val(eemail);
});
this has been answered by me...It gave me a headache only to realize '"data-emiD"=value' doesn't accept any capital letters. Not quite sure why but it solves my problem by changing it to data-emid="'+data[i].m_ID+'"

Dynamic element ID in jQuery script on click event

I'me trying to implement an on/off button on a php loop but I can't make it work because of the id of jQuery event. How can I get the correct id on click and pass it to the rest of the script?
The problem is in the $('#myonoffswitch')...
<script type="text/javascript">
$(document).ready(function(){
$('#myonoffswitch').click(function(){
var myonoffswitch=$('#myonoffswitch').val();
var wnfID=$('#wnfID').val();
if ($("#myonoffswitch:checked").length == 0) {
var a="2";
var b=wnfID;
} else {
var a="3";
var b=wnfID;
}
$.ajax({
type: "POST",
url: "ajax_wnf_status.php",
data: "statusWnf="+a+"&wnfID="+b,
success: function(html) {
$("#display").html(html).show();
}
});
});
});
</script>
I'm generating different id's for the loop rows (ex: id="#myonoffswitch1" ; id="#myonoffswitch2"; etc).
I'm not certain I fully understand the question, but .val() will not get the ID of an element. You should use .attr('id') instead.
Also, it looks like you're trying to format data for a GET request, not a POST.
If I understand the question correctly, I think you're looking for
event.target.id
where 'event' is passed in to your handler:
('#myonoffswitch').click(function(event){
id = event.target.id
. . .
Though at that point, you might not need the id, since you can just use event.target directly.

PHP Javascript Variable problem

I have a while loop in my PHP page where I look the following...
print $divLeft.strip_tags($row->twitterUser)."?size=normal\"/><br \/>".$row->twitterUser.$divRight."<a href='javascript:void(0);' id='vote_$row->id' class='getPoint'>Get " .$row->coff. "<input type='hidden' value='$row->coff' id='credoff'/> credit(s)</a><br /></div>$clearDiv</div></div>";
I have a value set in my hidden field which I then call in my javascript...
{
var theid = $(this).attr("id");
var onlyID = theid.split("_");
var onlyID = onlyID[1];
credoff = $("#credoff").val();
$.ajax({
url: 'do.php',
type: 'POST',
data: "userID=" + onlyID,
success: function(data) {
if(data != "success1" && data != "success5") {
$("#" + theid).text(data);
}else{
$("#thediv_" + onlyID).fadeOut("slow");
$('#creditsBalance').fadeOut("slow");
newbalance = parseInt($('#creditsBalance').text());
if(data != "success5") {
alert('Credits offered = '+credoff);
The only thing is in my javascript its grabbing the highest 'credoff' variable value on the page, not the one clicked on, does this make sense?
First off, $('#credoff') is an id... and IDs are unique to a page. Secondly, if there were more than one (and built properly through a CSS selector), the way you're calling $('#credoff') would only give you the value of the first one, since you're not associating it with the event target.
Since it looks structurally like the input is a child of the (which is odd, too, btw), you'll need to use a selector like this to get credOff:
$('.getPoint').click(function(){
// properly associated with the event target.
var credOff = $(this).find('input').val();
// etc.
}
Element IDs must be unique throughout the page; if they are not, then attempting to select by ID is undefined. Your best bet is to use something like this:
<input type="hidden" ... class="credoff" />
And then in the javascript something like this:
credoff = $(this).children('input.credoff:hidden').val()

Print the value in loop in Jquery ready function

somehow still not able to do what I’m inted to do. It gives me the last value in loop on click not sure why. Here I want the value which is been clicked.
Here is my code:
$(document).ready(function() {
var link = $('a[id]').size();
//alert(link);
var i=1;
while (i<=link)
{
$('#payment_'+i).click(function(){
//alert($("#pro_path_"+i).val());
$.post("<?php echo $base; ?>form/setpropath/", {pro_path: $("#pro_path_"+i).val()}, function(data){
//alert(data);
$("#container").html(data);
});
});
i++;
}
});
Here the placement_1, placement_2 .... are the hrefs and the pro_path is the value I want to post, the value is defined in the hidden input type with id as pro_path_1, pro_path_2, etc. and here the hrefs varies for different users so in the code I have $('a[id]').size(). Somehow when execute and alert I get last value in the loop and I don’t want that, it should be that value which is clicked.
I think onready event it should have parsed the document and the values inside the loop
I’m not sure where I went wrong. Please help me to get my intended result.
Thanks, all
I would suggest using the startsWith attribute filter and getting rid of the while loop:
$(document).ready(function() {
$('a[id^=payment_]').each(function() {
//extract the number from the current id
var num = $(this).attr('id').split('_')[1];
$(this).click(function(){
$.post("<?php echo $base; ?>form/setpropath/", {pro_path: $("#pro_path_" + num).val()},function(data){
$("#container").html(data);
});
});
});
});
You have to use a local copy of i:
$('#payment_'+i).click(function(){
var i = i; // copies global i to local i
$.post("<?php echo $base; ?>form/setpropath/", {pro_path: $("#pro_path_"+i).val()}, function(data){
$("#container").html(data);
});
});
Otherwise the callback function will use the global i.
Here is a note on multiple/concurrent Asynchronous Requests:
Since you are sending multiple requests via AJAX you should keep in mind that only 2 concurrent requests are supported by browsers.
So it is only natural that you get only the response from the last request.
What if you added a class to each of the links and do something like this
$(function() {
$('.paymentbutton').click(function(e) {
$.post("<?php echo $base; ?>form/setpropath/",
{pro_path: $(this).val()},
function(data) {
$("#container").html(data);
});
});
});
});
Note the use of $(this) to get the link that was clicked.

Categories