Calling function itself in jquery not works - javascript

function loadProvinces(data){
var province = "<tr><th>Options</th><th>Province</th></tr>";
var json = $.parseJSON(data);
for(var i=0; i<json.province_info.length; i++){
province += "<tr><td><input type='button' id='"+json.province_info[i].province_id+"' value='Delete' /></td><td>"+json.province_info[i].province_name+"</td></tr>";
}
$("#appendprovince").empty();
$("#appendprovince").append(province);
$("#appendprovince").show();
$(":input").click(function(e) {
var id = this.id;
var url = "http://localhost:8080/CurdServlet/ProvinceServlet";
$.post(url,{"getProvince" : "delete_province","province_id":""+id},
function(data){
alert(data); // its working and shows data successfully
loadProvinces(data); // here loadProvinces function not working only
});
});
}//end loadProvinces
i have called loadprovinces function when user add a province for a particular country
as user adds a province it inserts into a province table so it is working , a problem is that loadProvinces function is not calling when user presses a delete button .

As you are adding delete button dynamically then you shuld use .on to bind click event. Also keep this bind click event code outside function :
function loadProvinces(data){
var province = "<tr><th>Options</th><th>Province</th></tr>";
var json = $.parseJSON(data);
for(var i=0; i<json.province_info.length; i++){
province += "<tr><td><input type='button' id='"
+json.province_info[i].province_id
+"' value='Delete' /></td><td>"
+json.province_info[i].province_name+"</td></tr>";
}
$("#appendprovince").empty();
$("#appendprovince").append(province);
$("#appendprovince").show();
}//end loadProvinces
// bind click event for dynamically generated element
$(document).on("click",":input",function(e) {
var id = this.id;
var url = "http://localhost:8080/CurdServlet/ProvinceServlet";
$.post(url,{"getProvince" : "delete_province","province_id":""+id},
function(data){
alert(data); // its working and shows data successfully
loadProvinces(data); // here loadProvinces function not working only
});
});

There is syntax error. Not sure if it is the main Problem, but it can not works without this.
Have you checked console? F12
function(data){ miss }

Why don't you just do it this way:
function loadProvinces (data) {
var province = "<tr><th>Options</th><th>Province</th></tr>";
var json = $.parseJSON(data);
for(var i = 0; i < json.province_info.length; i++){
province += "<tr><td><input type='button' id='" + json.province_info[i].province_id + "' value='Delete' /></td><td>" + json.province_info[i].province_name + "</td></tr>";
}
$("#appendprovince").empty();
$("#appendprovince").append(province);
$("#appendprovince").show();
}
;//end loadProvinces
$(":input").click(function (e) { // it would be nice to add some more identifiers e.g. class to fire only when needed
var id = this.id;
var url = "http://localhost:8080/CurdServlet/ProvinceServlet";
$.post(url, {"getProvince": "delete_province", "province_id": "" + id},
function (data) {
alert(data); // its working and shows data successfully
loadProvinces(data); // here loadProvinces function not working only
});
});

Related

How to pass multiple variables from ajax to function in javascript?

How can I pass 2 variables from ajax to function ?
I can successfully pass 1 variable, but I don't know how to write the code to pass 2 variables. I'm stuck here:
<button id ="+data[i].id+" onclick='tahu("+data[i].id+","+data[i].nama+")'>Detail</button>
Here is my function
function tahu(x, y) {
window.alert(x);
window.alert(y);
}
Here is my full ajax code
function tampilkan() {
var data_table = "";
var head_table = "";
$.ajax({
url: "showkaryawan/da",
dataType: "json",
success: function(data) {
$('#oo').empty();
head_table +="<thead><tr class='bg-info'><th width='10%'>ID Karyawan</th><th width='30%'>Nama Karyawan</th><th width='15%'>Action</th></tr></thead>";
for (var i =0; i<data.length; i++) {
data_table +="<tr><td>"+data[i].id+"</td><td>"+data[i].nama+"</td><td>"+"<button id ="+data[i].id+","+data[i].nama+" onclick='tahu("+data[i].id+")'>Detail</button>"+"</td></tr>";
}
$('#oo').append(head_table);
$('#oo').append(data_table);
}
});
}
Ok, I've tried to solve your problem but without actually doing a json request so bear with me. Firstly, You are already using jquery for your ajax call so why not leverage jquery for your DOM manipulation as well? I have written your function to store the id and nama as attributes on the button element and instead of having an inline function call, I have written a click event handler in jquery to execute any time a button (with class detailButton) is clicked. This function will grab the data-id and data-name from the button itself and should display the information you want, specific to that button.
The final button element:
<button data-id ="id" data-name="nama" class="detailButton">Detail</button>
and the jquery:
//ajax request
function tampilkan() {
var data_table = "";
var head_table = "";
$.ajax({
url: "showkaryawan/da",
dataType: "json",
success: function(data) {
$('#oo').empty();
head_table +="<thead><tr class='bg-info'><th width='10%'>ID Karyawan</th><th width='30%'>Nama Karyawan</th><th width='15%'>Action</th></tr></thead>";
for (var i =0; i<data.length; i++) {
var id = data[i].id;
var nama = data[i].nama;
data_table +="<tr>";
data_table +="<td>"+id+"</td>";
data_table += "<td>"+nama+"</td>";
data_table += "<button data-id ="+id+" data-nama="+nama+" class="detailButton">Detail</button>";
data_table += "<td></td></tr>";
}
$('#oo').append(head_table);
$('#oo').append(data_table);
}
});
}
//click event handler
$('.detailButton').click(function() {
var id = $(this).data('id')
var nama = $(this).data('nama');
alert(id);
alert(name);
});
I took the liberty of expanding your data_table concatenation into multiple lines for ease of reading. Hope this is closer to your final solution.

I have dynamically generated 2 <tr> and I want to get the data of the <tr> I click

The Question might be confusing but this is the exact situation..
I have dynamically generated few ( as per data fetched from database) and now I want to allow the user to select one of the radio buttons and I want to capture the details of the row clicked so please check my code and assist
My ajax code
$.ajax({
data: data,
url: url,
type: 'POST',
datatype: 'JSON',
success: function (response) {
console.log(response);
var result = $.parseJSON(response);
var count = result.length;
for (var i = 0; i < count; i++) {
var $row = $("<tr><input type='hidden' id='"+ result[i].objId + "' value='"+ result[i].objId+"'><td><input type='radio' name='dbRadio' id='dbRadio'></td><td>" + result[i].name + "</td><td> Murgency Global Network</td><td>" + result[i].number + "</td><td>" + result[i].city + "</td><td> 0.5 Km</td></tr>");
$('table.queriedResponder > tbody:last').append($row);
}
console.log($row);
}
});
my radio button detection code
$('input[name=dbRadio]').change(function(){
console.log('clicked');
});
Use an instance of this and get the closest tr:
$('input[name=dbRadio]').change(function(){
console.log($(this).closest("tr"));
});
Of course, if this handler isn't being hit, it's probably because your rows are being added dynamically - so delegate the handler:
$('table.queriedResponder').on('change', 'input[name=dbRadio]', function() {
console.log($(this).closest("tr"));
});

how to map index using jquery to repair indexes when remove

Problem
when remove any course from table list html his position in center or first it make problem
in index in database
Details
IF I have list of courses as following :
Delphi
Flash
Photoshop
IF I remove flash by JQUERY remove button then click save button
it delete flash and Photoshop
because there are wrong in delete courses by using remove function in jquery
if i remove php it is working without any problem because it is last item
suggestion
using map function when remove but how to do that
if there are any solution for that without using map no problem
i use model as following
public class Cusomemp2
{
public List<EmployeeCourse> empcourses { get; set; }
}
}
i use for edit httppost
var result = db.Employees
.Where(p => p.Id == custom.Id)
.Include(c => c.EmployeeCourses)
.FirstOrDefault();
if (custom.empcourses.Any())
{
foreach (var ec in result.EmployeeCourses.ToList())//to remove existing EmployeeCourses
{
db.EmployeeCourses.Remove(ec);
db.SaveChanges();
}
}
result.EmployeeCourses = custom.empcourses;
db.SaveChanges();
in model view my code as following by jquery
actually i need to modify
code below using map function if there are any function do that never mind
$(function () {
//add courses using drop down
var index = 0;
$("#CourseId").change(function () {
var id = $(this).val();
var txt = $("#CourseId option:selected").text();
$("#tb").append("<tr><td><input type = 'hidden' name='empcourses[" + index + "].CourseId' value='" + id + "'/></td><td>" + txt + "</td><td><input type='button' value='remove' class='r'</td></tr>")
index++;
});
$("#tb").on("click", ".r", function () {
// remove function
$(this).parent().parent().remove();
$(this).parent().prev().prev().remove();
});
// retrieve data in edit view using ajax
$.ajax({
url: "/Employee/getcoursesbyempid",
data:{x:$("#hid").val()},
success: function (res) {
$.each(res, function (i, e) {
$("#tb").append("<tr><td><input type = 'hidden' name='empcourses[" + index + "].CourseId' value='" + e.Id + "'/></td><td>" + e.CourseName + "</td><td><input type='button' value='remove' class='r'</td></tr>")
index++;
});
}
})
});
see image below to understand what i need

How to get the value value of a button clicked Javascript or Jquery

I'll try to be as straight to the point as I can. Basically I using jquery and ajax to call a php script and display members from the database. Next to each members name there is a delete button. I want to make it so when you click the delete button, it deletes that user. And that user only. The trouble I am having is trying to click the value of from one delete button only. I'll post my code below. I have tried alot of things, and right now as you can see I am trying to change the hash value in the url to that member and then grap the value from the url. That is not working, the value never changes in the URL. So my question is how would I get the value of the member clicked.
<script type="text/javascript">
$(document).delegate("#user_manage", "pagecreate", function () {
$.mobile.showPageLoadingMsg()
var friends = new Array();
$.ajaxSetup({
cache: false
})
$.ajax({
url: 'http://example.com/test/www/user_lookup.php',
data: "",
dataType: 'json',
success: function (data) {
$.mobile.hidePageLoadingMsg();
var $member_friends = $('#user_list');
$member_friends.empty();
for (var i = 0, len = data.length; i < len; i++) {
$member_friends.append("<div class='user_container'><table><tr><td style='width:290px;font-size:15px;'>" + data[i].username + "</td><td style='width:290px;font-size:15px;'>" + data[i].email + "</td><td style='width:250px;font-size:15px;'>" + data[i].active + "</td><td><a href='#" + data[i].username + "' class='user_delete' data-role='none' onclick='showOptions();'>Options</a></td></tr><tr class='options_panel' style='display:none'><td><a href='#" + data[i].username + "' class='user_delete' data-role='none' onclick='showId();'>Delete</a> </td></tr></table></div>");
}
}
});
});
</script>
<script>
function showId() {
var url = document.URL;
var id = url.substring(url.lastIndexOf('#') + 1);
alert(id);
alert(url);
}
</script>
IDEAS:
1st: I think it would be easier to concatenate an string an later append it to the DOM element. It's faster.
2nd: on your button you can add an extra attribute with the user id of the database or something and send it on the ajax call. When getting the attribute from the button click, use
$(this).attr('data-id-user');
Why don't you construct the data in the PHP script? then you can put the index (unique variable in the database for each row) in the button onclick event. So the delete button would be:
<button onclick = "delete('indexnumber')">Delete</button>
then you can use that variable to send to another PHP script to remove it from the database.
$('body').on('click', 'a.user_delete', function() {
var url = document.URL;
var id = url.substring(url.lastIndexOf('#') + 1);
alert(id);
alert(url);
});
<?php echo $username ?>
Like wise if you pull down users over json you can encode this attribute like so when you create your markup in the callback function:
'<a href="#'+data[i].username+'" data-user-id="'+ data[i].username + '" class="user_delete" data-role="none" >Options</a>'
So given what you are already doing the whole scenerio should look something like:
$(document).delegate("#user_manage", "pagecreate", function () {
$.mobile.showPageLoadingMsg();
var friends = new Array(),
$member_friends = $('#user_list'),
// lets jsut make the mark up a string template that we can call replace on
// extra lines and concatenation added for readability
deleteUser = function (e) {
var $this = $(this),
userId = $this.attr('data-id-user'),
href = $this.attr('href'),
deleteUrl = '/delete_user.php';
alert(userId);
alert(href);
// your actual clientside code to delete might look like this assuming
// the serverside logic for a delete is in /delete_user.php
$.post(deleteUrl, {username: userId}, function(){
alert('User deleted successfully!');
});
},
showOptions = function (e) {
$(this).closest('tr.options_panel').show();
},
userTmpl = '<div id="__USERNAME__" class="user_container">'
+ '<table>'
+ '<tr>'
+ '<td style="width:290px;font-size:15px;">__USERNAME__</td>'
+ '<td style="width:290px;font-size:15px;">__EMAIL__</td>'
+ '<td style="width:250px;font-size:15px;">__ACTIVE__</td>'
+ '<td>Options</td>'
+ '</tr>'
+ '<tr class="options_panel" style="display:none">'
+ '<td>Delete</td>'
+ '</tr>'
+ <'/table>'
+ '</div>';
$.ajaxSetup({
cache: false
})
$(document).delegate('#user_manage #user_container user_options', 'click.userlookup', showOptions)
.delegate('#user_manage #user_container user_delete', 'click.userlookup', deleteUser);
$.ajax({
url: 'http://example.com/test/www/user_lookup.php',
data: "",
dataType: 'json',
success: function (data) {
$.mobile.hidePageLoadingMsg();
var markup;
$member_friends.empty();
for (var i = 0, len = data.length; i < len; i++) {
markup = userTmpl.replace('__USERNAME__', data[i].username)
.replace('__ACTIVE__', data[i].active)
.replace('__EMAIL__', data[i].email);
$member_friends.append(markup);
}
}
});
});
Here's a really simple change you could make:
Replace this part:
onclick='showId();'>Delete</a>
With this:
onclick='showId("+data[i].id+");'>Delete</a>
And here's the new showId function:
function showId(id) {
alert(id);
}

Array and while loop: make unique clickable

I have an array (via ajax) that looks like this:
data[i].id: gives the id of user i
data[i].name: gives the name of user i
I want to output the array like this:
X Leonardo Da Vinci
X Albert Einstein
X William Shakespeare
...
The X is an image (x.gif) that must be clickable. On click, it must go to functiontwo(), passing the parameter data[i].id. Functiontwo will open a jquery dialog with the question "Delete id data[i].id"?
I know this can't be too hard to do, but I can't seem to figure it out...
This is what I have so far:
function functionone() {
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
success : function(data){
var message = "";
var i = 0;
while (i < (data.length - 1))
{
var myvar = data[i].id;
message = message + "<div class=" + data[i].id + "><img src=x.gif></div>" + data[i].name + "<br />";
$('#somediv').html(message).fadeIn('fast');
$("." + data[i].id + "").click(function () {
functiontwo(myvar);
});
i++;
}
}
});
}
function functiontwo(id) {
...}
I know why this isn't working. Var i gets populated again and again in the while loop. When the while loop stops, i is just a number (in this case the array length), and the jquery becomes (for example):
$("." + data[4].id + "").click(function () {
functiontwo(myvar);
});
, making only the last X clickable.
How can I fix this?
Thanks a lot!!!
EDIT:
This is my 2nd function:
function functiontwo(id) {
$("#dialogdelete").dialog("open");
$('#submitbutton').click(function () {
$('#submitbutton').hide();
$('.loading').show();
$.ajax({
type : 'POST',
url : 'delete.php',
dataType : 'json',
data: {
id : id
},
success : function(data){
var mess = data;
$('.loading').hide();
$('#message').html(mess).fadeIn('fast');
}
});
//cancel the submit button default behaviours
return false;
});
}
In delete.php there's nothing special, I used $_POST['id'].
As I pointed out in my comment. The problem is the .click part. Either use bind, or use a class for all the elements, and a click-event like this $('.classnamehere').live('click',function () { // stuff });
function functionone() {
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
success : function(data){
var message = "";
var i = 0;
while (i < (data.length - 1))
{
var myvar = data[i].id;
message = message + "<div class=\"clickable\" id=" + data[i].id + "><img src=x.gif></div>" + data[i].name + "<br />";
$('#somediv').html(message).fadeIn('fast');
i++;
}
}
});
}
$('.clickable').live('click',function () {
alert($(this).attr('id') + ' this is your ID');
});
The usual trick is create a separate function to create the event handler. The separate function will receive i as a parameter and the generated event will be able to keep this variable for itself
make_event_handler(name){
return function(){
functiontwo(name);
};
}
...
$("." + data[i].id + "").click( make_event_handler(myvar) );

Categories

Resources