jquery function runs only once - html

I have this function below. Works great and is from http://caroufredsel.dev7studios.com/ (by far the best and easiet I have found if anyone else is after a carousel)
<script type="text/javascript" language="javascript">
$(function() {
$('#foo1').carouFredSel({
auto: {
pauseOnHover: 'resume',
progress: '#timer1'
}
});
});
</script>
anyway I the carousel loops through a selection of images. Now I have a separate function that reloads the div through an ajax call below. It populates the div with a new set of images based on the users selection of folder.
<script>
function getImages(id)
{
$.ajax({
type: "GET",
url: 'getImage.php',
data: "id=" + id,
success: function(data) {
$('#scrolimg').html(data);
}
});
}
</script>
This too works fine. The problem is when you have clicked a new folder and it reloads refreshes the div the carousel stops completely. Is there anyway based on the success of the ajax call to re fire the jquery function to get the carousel going again?

on the callback function of the AJAX you call, you have to re-apply:
success: function(data) {
$('#foo1').carouFredSel({
auto: {
pauseOnHover: 'resume',
progress: '#timer1'
}
});
...
}
If you are using a .html() function or similar to re-write the foo element, you are erasing any event associated to it too, so you have to call it again.

Add something like this into your callback:
$('#foo1').carouFredSel({
auto: {
pauseOnHover: 'resume',
progress: '#timer1'
}
});
It should work. Respect!

Supposing in your example foo1 == scrolimg, do this:
<script>
function getImages(id)
{
$.ajax({
type: "GET",
url: 'getImage.php',
data: "id=" + id,
success: function(data) {
$('#scrolimg')
.carouFredSel('destroy')
.html(data)
.carouFredSel({
auto: {
pauseOnHover: 'resume',
progress: '#timer1'
}
});
}
});
}
</script>

Related

ASP.NET jQuery reload element on submit (Ajax POST/GET)

Using ASP.NET I'm trying to reload only a part of my webpage using jQuery instead of using "location.reload();". It's a single page application. As the user submits a form the user credits change and the new value should be updated without a full page reload. The value for credits is retrieved through an Ajax Get Call and should be updated after an Ajax Post Call. I tried using "$("#userCredits").load(?);" within the Ajax Post but can't get it right. Do I need to make a partial view to achieve this? Thanks for helping.
HTML _Layout.cshtml
<ul class="nav masthead-nav">
<li id="userCredits">
//Paragraph retrived from Ajax Get Call: "#reloadUserCredits".
</li>
<li>
<p class="user">#User.Identity.GetUserName()</p>
</li>
</ul>
JS
//Ajax POST user pack (buy pack)
$("#postform").submit(function (e) {
e.preventDefault();
var data = {
applicationUserId: $("#userId").val().trim(),
packId: $("input.activeImg").val().trim(),
}
$.ajax({
url: '/api/buypack',
type: 'POST',
dataType: 'json',
data: data,
success: function () {
document.getElementById("postform").reset();
location.reload();
},
error: function () {
}
});
});
// Ajax GET user credits (navbar userCredits)
var $credits = $('#userCredits')
$.ajax({
type: 'GET',
url: '/api/user',
success: function (credits) {
$.each(credits, function (i, user) {
$credits.append('<p id="reloadUserCredits" class="credits">Credits: ' + user.credits + '</p>');
});
}
});
As I understand... You already are getting the user credits via Ajax on page load. So you only need to do it again after he bought some more.
Have the Ajax request to /api/user in a named function. Below, I called it get_credits(). Run it on page load AND on success of the Ajax request to /api/buypack.
//Ajax POST user pack (buy pack)
$("#postform").submit(function (e) {
e.preventDefault();
var data = {
applicationUserId: $("#userId").val().trim(),
packId: $("input.activeImg").val().trim(),
}
$.ajax({
url: '/api/buypack',
type: 'POST',
dataType: 'json',
data: data,
success: function () {
document.getElementById("postform").reset();
//location.reload();
// Refresh the credits displayed on the page
get_credits();
},
error: function () {
}
});
});
// Ajax GET user credits (navbar userCredits)
var $credits = $('#userCredits')
function get_credits(){
$.ajax({
type: 'GET',
url: '/api/user',
success: function (credits) {
$.each(credits, function (i, user) {
$credits.html('<p id="reloadUserCredits" class="credits">Credits: ' + user.credits + '</p>');
});
}
});
}
// Run on page load
get_credits();

Update a Div with a PartialView

I'm trying to update the Div's value with a Partial-View, but I have no idea what to write into the .html().
My Controller-Methode:
public IActionResult UpdateDiv()
{
return View("_PartialView1");
}
My Javascript function:
$.ajax({
url: "/home/UpdateDiv/"
}).done(function () {
$("#UpdateDiv").html();
})
The div:
<div id="UpdateDiv" style="width: 400px; height: 400px;"></div>
My Partial-View:
<h1>Hello</h1>
Have you tried to add a respone param to done callback function? Something like the below code snippet:
$.ajax({
url: "/home/UpdateDiv/"
}).done(function (response) {
$("#UpdateDiv").html(response);
});
$.get("/home/UpdateDiv/", function(data) {
$(".UpdateDiv").html(data);
});
Try this way. It uses GET method to receive HTML from your action. Once it's done loading, it updates your update div element.

jQuery Mobile - AJAX JSON

I am having trouble figuring out why jQuery Mobile will not handle my json return in an AJAX call. It works perfectly fine in any web browser but not on my mobile phone (android). The script just hangs, it will not even choose either of the if statement options in the success function.
$('#loginSubmit').click(function() {
$.mobile.showPageLoadingMsg();
$.ajax({
type: "POST",
url: "/include/login.php",
data: $('#loginForm').serialize(),
cache: false,
dataType: "json",
success: function (json) {
if(json && json.error != '') {
//alert(json.error);
$.mobile.hidePageLoadingMsg();
} else {
$.mobile.changePage('/mobile/cp/', { transition: "slide" });
$.mobile.hidePageLoadingMsg();
}
}
});
return false;
});
I had this problem once with the new beta, when i enabled ajaxLinks. If i then wanted to add code for elements, that were not on my startpage, i could not use
$(document).ready function.
I used the
$('#page').live('pageshow', function() ...
to add my code at pagechange. So my elements i wanted to add the javascript to were currently rendered.
Hope this helps.

$jQuery Tree from json data ---> .live is killing me

I'm trying to build a tree from json data, this data are loaded on demand from php files. My problem is that i can't find a way to get to lvl 3 ;). Here is my code:
$(document).ready(function()
{
//Get the screen height and width
var Height = $(document).height()/2;
var Width = $(window).width()/2;
$("#div1").hide();
$("#div2").hide('slow');
$.ajax(
{
type: 'post',
async: true,
url: "getparents.php",
data: {'id' : 12200},
dataType: "json",
cache: false,
beforeSend: function ()
{
//Show the Loading GIF at centered position
$('#loading').css({'top': Height, 'left': Width}).show();
},
success: function(json_data)
{
$("#div1").empty().show();
$('<ul class="parentContainer"></ul>').appendTo("#div1");
$.each(json_data, function(key, object)
{
$('<li id="node">'+object.name+'</li>').data('id', object.id).appendTo(".parentContainer");
if (object.childbool == true)
{
$('li:last').addClass('childfull')
}
});
},
error: function ()
{
$('#loading').hide();
alert('Something Went Wrong with the Loading please hit back in a minute');
},
complete: function ()
{
$('#loading').hide();
}
});
function getChild(id, node)
{
$.ajax(
{
type: 'post',
async: true,
url: "getchilds.php",
data: {'id' : id},
dataType: "json",
cache: false,
beforeSend: function ()
{
$('#loading').show();
},
success: function(json_data)
{
$('<ul class="childContainer"></ul>').appendTo(node);
$.each(json_data, function(key, object)
{
$('<li id="node">'+object.name+'</li>').data('id', object.id).appendTo(".childContainer");
if (object.childbool == true)
{
$('li:last').addClass('childfull')
}
});
},
error: function ()
{
$('#loading').hide();
alert('Something Went Wrong with the Loading please hit back in a minute');
},
complete: function()
{
$('#loading').hide();
}
});
}
$("li.childfull, li.openchildfull").live('click',function()
{
if ($('li.childfull'))
{
var node = $(this);
var id= $(this).data('id');
$(node).html(getChild(id, node));
$(node).removeClass().addClass('openchildfull');
}
else
{
$(node).removeClass().addClass('childfull');
$(node).children().remove();
}
});
});
I think .live is killing me. I get my parents on load; when I click on one I get its children ALL pretty and well, but when I click on a child to get its children I get a very funny behavior. I get its children correctly indented but with no class="childfull" and I get an other copy of them not properly indented but with correct class.. I don't know what is going wrong... Any ideas/corrections are welcome.
P.S: You don't want me to describe to you what happens when I click on the messed up 3rd lvl childfull :P.
Instead of going through the headache of building your own tree, have a look at the jstree plugin. You can pass different formats to it, including json. It allows for complete customization and allows infinite(possible :p) child levels.

Ajax function not called when included

I have an ajax function that is not run when the ajax script is included in my HTML page like so:
<script type='text/javascript' src='ajax.js'></script>
However, if I place the exact same script in the head portion of the HTML page, then it does run.
Why does this occur, and how can I fix it?
<script type="text/javascript">
$(function() {
$(".a").click(function()
{
$.ajax({
type: "POST",
url: "1.php",
data: dataString,
cache: false,
success: function(html)
{
//stuff
}
});
return false;
});
});
</script>
This might seem trivial but did you remove the <script> tags when using it in an external .js file?
The contents of your ajax.js file should just be:
$(function() {
$(".a").click(function() {
$.ajax({
type: "POST",
url: "1.php",
data: dataString,
cache: false,
success: function(html)
{
//stuff
}
});
return false;
});
});
I have the impression that when you mentioned "exactly", you left the script tags intact in the ajax.js file.
Also if this still doesn't work. try added an alert("hello"); line at the top of ajax.js before everything to see whether it runs at all.
I made a example which worked fine for me. cant see any problems so im guessing its a mistype or something silly.
here is the sample code i used:
HTML:
//double check these paths
<body>
<a class="a" href="#">clicky</a>
</body>
Javascript:
$(function() {
// i noticed you put .a here instead of a, i am assuming you are referring the class
$(".a").click(function()
{
alert("1");
$.ajax({
type: "POST",
url: "1.php",
data: "html",
cache: false,
success: function(data)
{
//stuff
$("body").html(data);
}
});
return false;
});
});
PHP:
echo 'bar';