Avoid duplicated function call in jquery? - javascript

I have build a function getuser() in which I recieve json data from php into javascript. I call this function when document gets ready. My problem is that I am also using jquery post for live updation of that record and for that reason I have to call that function getuser() again due to this it shows duplicate result. First when document gets ready socend on jquery post function.
HTML
<!--It has onclick event-->
<button type="submit" class="btn btn-primary modify" onclick="update_user()">UPDATE</button>
JQUERY
//This is function which gets json array from php
function getuser() {
$.get("getuser.php", function (data) {
var data = JSON.parse(data);
for (var i = 0, len = data.length; i < len; ++i) {
var student = data[i];
var slash = " / ";
$("#output").append("<tr><td>" + student.name + "</td><td>" + student.gender + "</td><td>" + student.age + "</td>" +
"<td>" + student.city + "</td><td><a href='#' style='text-decoration: none' class='update' id='" + student.id + "' onclick='reply_click(this.id)'>Update</a>" + slash + "<a style='text-decoration: none' href='#'>Delete</a></td></tr>");
}
});
}
//when document gets ready it will show the record
if($(document).ready()) {
// getuser();
getuser();
}
//This is jquery post. When I click button (in html section) it will get form values and sent to php page
//in return it will call getuser() function again which results of duplicate display of record
$(document).ready(function(){
$('.modify').click(function() {
var gender = '';
if($('.male').is(':checked')){
gender='Male';
}else{
gender='Female';
}
$.post("update.php",
{name: $('.name').val(),gender:gender,city:$('.city').val(),age:$('.age').val(),id:$('.id').val()},
function (data) {
//here is the function call again
getuser();
}
);
});
});
Kindy tell me that is there any way I avoid second call in post function and the record gets update without function call again.I need to avoid duplicate result. Thanks in advance!

First off, you need to read the docs on jquery document ready, and learn the difference between a function reference and actually calling a function. document.ready expects you to pass in a function definition to be called when the page is ready. It doesn't actively tell you if the page is ready, the first way you're calling it. The second way you're calling it is actually correct.
Second, replace $("#output").append with $("#output").html, which will update/replace the contents of that element every time, instead of just adding more and more.

Your if test will always return true because document.ready returns the JQuery object. So, you are always causing the call to getuser() to happen.
You can see the return value from document.ready() here:
console.log($(document).ready());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This is an incorrect usage of document.ready(). You don't need to write a test for document.ready, just write a callback function for that event and let the browser do it correctly for you.
Read the docs on document.ready()
Solution:
This:
//when document gets ready it will show the record
if($(document).ready()) {
// getuser();
getuser();
}
Should be this:
//when document gets ready it will show the record
$( document ).ready(getuser);
Or even:
$(getuser);
As for you getting the results a second time, just overwrite the old results instead of appending them.
This: $("#output").append(...
Should be: $("#output").html(...

All of you thanks for your suggestions. I have found the solution here by just adding $("#tbody").html(''); in getuser() before loop. Here is the code which works fine for me
function getuser() {
$.get("getuser.php", function (data) {
var data = JSON.parse(data);
$("#tbody").html('');//newly added
for (var i = 0, len = data.length; i < len; ++i) {
var student = data[i];
var slash = " / ";
$("#output").append("<tr><td>" + student.name + "</td><td>" + student.gender + "</td><td>" + student.age + "</td>" +
"<td>" + student.city + "</td><td><a href='#' style='text-decoration: none' class='update' id='" + student.id + "' onclick='reply_click(this.id)'>Update</a>" + slash + "<a style='text-decoration: none' href='#'>Delete</a></td></tr>");
}
});
}
All of you thanks again!

Related

How can I run a function on page load and then after click?

hi this is my very first time using jquery on any project at all. I am needing a little help if someone can
on my page i have some code to load a json file this file contains menu details for the main menu such as
name / action / poster
this is my code
var Items = "";
var flixAPI = "https://example.com/api.php?action=MAIN";
$.getJSON(flixAPI, function (data) {
$.each(data, function (i, item) {
Items += "<div class='img'>";
Items += "<a target='_blank' href='" + item.ACTION + "'>";
Items += "<img src='"+ item.POSTER +"' alt='" + item.NAME + "'>";
Items += "</a>";
Items += "<div class='desc'>" + item.NAME.substr(0, 16) + "</div>";
Items += "</div>";
});
$('#content').html(Items);
});
i can get this code working when i place it into the document ready.
my issue is after the main menu is populated and added to the page i then need to stop the page redirecting when a href link is clicked and get the value of the href link to then send another get json request to load the next page
i have tried loading the main menu on the document ready and then sticking one call into a .click binding to load the next set of items based on the href link clicked but when i try do this inside or outside the document ready the .click binded function wont work
Put the code in a named function so you can call it from both places.
function getFlix(flixAPI) {
var Items = "";
$.getJSON(flixAPI, function(data) {
$.each(data, function(i, item) {
Items += "<div class='img'>";
Items += "<a class='menu-link' target='_blank' href='" + item.ACTION + "'>";
Items += "<img src='" + item.POSTER + "' alt='" + item.NAME + "'>";
Items += "</a>";
Items += "<div class='desc'>" + item.NAME.substr(0, 16) + "</div>";
Items += "</div>";
});
$('#content').html(Items);
});
}
$(document).ready(function() {
getFlix("https://example.com/api.php?action=MAIN");
$("#content").on("click", ".menu-link", function(e) {
e.preventDefault();
getFlix(this.href);
});
});
This uses event delegation because the menu links are added dynamically. See Event binding on dynamically created elements?
You would need to identify the menu items with either classes or id's.
Then you would have to define the onClick event for each one of those who you need to fetch the JSON for.
ON the onClick event, you need to use e.stoppropagation or e.preventdefault (check the usage online) and then use ajax to fetch the JSON and populate whatever you are populating.

How to pass a variable in ajax append function (into html element with razor)?

I need to pass the Id of a object into a html element (razor part), but it doesn't recognize it. Look like the Id is not in its scope, or something. Is there a way to pass the value into the razor part of my html element in the append function?
$.ajax({
data: data,
url: url + "?searchTerm=" + data
}).success(function (response) {
console.log(response);
var table = $('#companyTable');
var tBody = table.children('tbody');
tBody.html("");
var textbox = document.getElementById("searchBar");
textbox.value = "";
tBody.append(
"<tr><td>" +response.CompanyName + " </td><td>" +
response.CompanyIdNumber + "</td><td>" +
response.CompanyTaxNumber + "</td><td>" +
"<p><button onclick=\"location.href='#Url.Action("Edit", "Company", new { #id = response.CompanyId })'\"> Edit</button></p>" +
"</td></tr>"
);
table.removeClass("hidden");
var originalTable = $('#originalTable');
originalTable.remove();
}).error(function (response) {
console.log(response);
});
}
Thank you.
I do those things this way:
+ "<p><button onclick=\"location.href='#(Url.Action("Edit", "Company"))?id=" + response.CompanyId + "'\">Edit</button>"
You are totally missing the concept of server-side rendering and browser execution. Consider this example, your server renders your js code, and just leaves all work to browser, then browser stars to execute Ajax request somehow(button click), when Ajax completed - you have a response value, but this value exists only inside browser context, so it doesn't make sense to pass value into razor, as it already done its work while rendering your file
Now, what to do? The simplest solution would be to hardcore Url of company edit by yourself, as razor simply doesn't know anything what's happening client-side, example:
location.href="/company/1/edit" //where 1 is id from Ajax request
The easiest complete solution is
public ActionResult WhateverMethod()
{
// ....
var urlHelper = new UrlHelper(this.ControllerContext.RequestContext);
response.Url = Url.Action("Edit", "Company", new { #id = response.CompanyId });
// ....
}
And
tBody.append(
"<tr><td>" +response.CompanyName + " </td><td>"
+ response.CompanyIdNumber + "</td><td>"
+ response.CompanyTaxNumber + "</td><td>"
+ "<p><button onclick=\"location.href='" + response.Url + "'\"> Edit</button></p>"
+ "</td></tr>");
Calling a Razor methods in JavaScript is going to cause you nothing but grief.
response.CompanyId is considered as string , so try by concatenating it as below
var a="location.href='#Url.Action("Edit", "Company", new{#id='"+response.CompanyId+"'})'"
response.CompanyId ( "<tr><td>" +response.CompanyName + " </td><td>" +
response.CompanyIdNumber + "</td><td>" +
response.CompanyTaxNumber + "</td><td>" +
"<p><button onclick=\""+a +"\"> Edit</button></p>" + "</td></tr>")

Append image in function jquery

Good evening.
I have this jquery code which allows me, once you press the Enter key, to post a comment.
Fattio that I run an append with the username and the content that the user wants to publish.
In addition to the username I would also like to "hang" the profile picture using their path. How do I post a photo?
Thanks for your help. Here's the code:
function commento_post(id_post)
{
$('.form-commento'+id_post).click(function ()
{
$('#ins_commento'+id_post).keydown(function (e)
{
var message = $("#commento"+id_post).val();
var username = $("#username").val();
var id_user = $("#id_user").val();
if(e.keyCode === 13)
{
$.ajax(
{
type: 'POST',
url: 'http://localhost/laravel/public/index.php/post/ins_commento',
data: { commento: message, id_post: id_post },
success: function(data)
{
$('#commento'+id_post).val('');
$('#commentscontainer'+id_post).append
(
/*$(".username-commento"+id_post).html
(*/
$('<a/>',
{
text : username, href : 'http://localhost/laravel/public/index.php/utente/'+id_user
}).css({'font-weight':'bold'})
//)
).append(' ').append(message).append($('<br/>'));
var el = $('#numero_commenti'+id_post);
var num = parseInt(el.text());
el.text(num + 1);
}
});
}
});
});
}
In your success function, you could simplify everything quite a bit in the following way while not using jQuery append so much, but just using a variable to store your code and then appending it in one go. This will allow you to append all sort of elements, it's easily parseable for the you and it reduces the amount of calls you have to make.
// Add whatever you want your final HTML to look like to this variable
var html = "<a href='http://localhost/laravel/public/index.php/utente/" + id_user + "' style='font-weight: bold;'>" + username + "</a>";
html += message;
// add an image
html += "<img src='path/to/image.jpg' />"
html += "<br />";
// append to code you constructed above in one go
$('#commentscontainer' + id_post).append(html);
Update
I amended an incorrect quote and changed + id_user + "to + id_user + "', which makes everything after it work.

FB api call in for loop

I'm trying to get all facebook comments with profile pictures of commentators through fb.api() call. Currently all comments gets outputed i just can't get profile pictures to append to appropriate comment.
In for loop which loops through all comments is another FB.api call which gets the profile pic of user who commented on video and than append them into single comment block. With this code i get profile pictures of all users who commented in every single comment.
What am i doing wrong?? Thank you in advance!
var komentarji_length = response.comments.data.length;
for (var i = 0; i < komentarji_length; i++) {
var user_id = response.comments.data[i].from.id;
FB.api("/" + user_id + "/picture", {
access_token: access_token
}, function (response) {
var profile_pic_link = response.data.url;
$(".comments_profile_pic" + i).append("<img src=" + comments_profile_pic_link + ">");
});
var ime = response.comments.data[i].from.name;
var message = response.comments.data[i].message;
$(".fb_comments").append('<div class="single_comment"><div class="comments_profile_pic' + i + '"></div><div class="name">' + name + '&nbsp says:</div><div class="single_message">' + message + '</div></div>');
}
Issue 1: comments_profile_pic_link is not defined, the variable is: profile_pic_link.
But then also the problem will not be solved. When you call "/" + user_id + "/picture" it is redirected to the image url automatically. So you can directly use the image url as: https://graph.facebook.com/{user-id}/picture. No need to make the API call unnecessarily.
Example
Still if you wish to get the proper image url (not required though), use redirect=0 with your call-
FB.api("/" + user_id + "/picture?redirect=0", {
access_token: access_token
}, function (response) {
var profile_pic_link = response.data.url;
$(".comments_profile_pic" + i).append("<img src=" + comments_profile_pic_link + ">");
});

Asp.net MVC 4 getJson work for create but not for edit. Seems to have an odd url in edit

I'm writing a MVC 4 app, I have a javascript function to support a couple of cascading dropdowns. The javascript is in a js file and I'm trying to use it for both create and edit view. It works great for the create view, but doesn't work from my edit view. I've looked at the network traffic using IE's developer tools, and notice the url from the create call is correct, Controller/MyActionMethod. The url from the edit call is controller/edit/controller/MyActionMethod.
I currently am using the default route config, it's seems to have worked fine, so I haven't delved into it too deeply.
Any thoughts on why controller/edit/ is preappended to the url in the edit case?
Any idea how to fix it?
I'll post code if it's useful, but thought this was probably something I don't understand about urls and routing.
Thanks
Here is the javascript
$(function () {
$.getJSON("ProfessionTypeList", function (data) {
var items = "<option>---------------------</option>";
$.each(data, function (i, professionType) {
items += "<option value='" + professionType.Value + "'>" + professionType.Text + "</option>";
});
$("#ProfessionTypeId").html(items);
})
});
The following line
$.getJSON("ProfessionTypeList",
will generate the URL of the form
http://domain.com/Controller/ActionName/ProfessionTypeList
i.e. it will append ProfessionTypeList at the end of the URL.
You should try to make explicit URL will complete path.
In CSHTML file, you can do so by using #Url.Action("ProfessionTypeList")
Thanks Comet!
Here's some details of what I did in case it helps someone else. I'm sure there's a cleaner way that doesn't use hidden fields. Not sure if it matters though.
I created hidden fields with the urls as values.
#Html.Hidden("ProfessionTypeListUrl",#Url.Action("ProfessionTypeList", "IsolatedPersonDetailAtEvent"), new { id = "ProfessionTypeListUrl" })
#Html.Hidden("ProfessionSubTypeListUrl",#Url.Action("ProfessionSubTypeList", "IsolatedPersonDetailAtEvent"), new { id = "ProfessionSubTypeListUrl" })
Then I looked them up in my js.
$(function () {
var actionUrl = $("#ProfessionTypeListUrl").attr('value');
$.getJSON(actionUrl, function (data) {
var items = "<option>---------------------</option>";
$.each(data, function (i, professionType) {
items += "<option value='" + professionType.Value + "'>" + professionType.Text + "</option>";
});
$("#ProfessionTypeId").html(items);
})
});
$("#ProfessionTypeId").change(function ()
{
**var actionUrl = $("#ProfessionSubTypeListUrl").attr('value');**
$.getJSON(actionUrl+"/" + $("#ProfessionTypeId > option:selected").attr("value"), function (data) {
var items = "<option>---------------------</option>";
$.each(data, function (i, subType) {
items += "<option value='" + subType.Value + "'>" + subType.Text + "</option>";
});
$("#ProfessionSubTypeId").html(items);
});
});
</script>

Categories