Can you explain the process of utilizing a JavaScript function that has been fetched via Ajax

When the AJAX function is loaded on the page, I am attempting to execute another function.

The code snippet for the AJAX call:

$.ajax({
type: "POST",
url: "loginpersonal.asp",
data: "id=<%=request("id")%>",
beforeSend: function() {
    $("#personaltab").hide();
},
success: function(msg){
    $("#personaltab").empty().append(msg);
},
complete: function() {
    $("#personaltab").slideDown();
},
error: function() {
    $("#personaltab").append("error").slideDown();
}
});

Below is the JavaScript function:

function GetCount(t){
    if(t>0) {
        total = t
    }
    else {
        total -=1;
    }
    amount=total;
                                            if(amount < 0){
        startpersonalbid();
    }
    else{
        days=0;hours=0;mins=0;secs=0;out="";
        days=Math.floor(amount/86400);//days
        amount=amount%86400;
        hours=Math.floor(amount/3600);//hours
        amount=amount%3600;
        mins=Math.floor(amount/60);//minutes
        amount=amount%60;

        secs=Math.floor(amount);//seconds
        if(days != 0){out += days +":";}
        if(days != 0 || hours != 0){out += hours +":";}
        if(days != 0 || hours != 0 || mins != 0){out += ((mins>=10)?mins:"0"+mins) +":";}
        out += ((secs>=10)?secs:"0"+secs) ;
        document.getElementById('countbox').innerHTML=out;
        setTimeout("GetCount()", 1000);
    }
}
window.onload=function(){
GetCount(<%= DateDiff("s", Now,privatesellstartdate&" "&privatesellstarttime ) %>);

Therefore, after the completion of the AJAX function in loginpersonal.asp, I aim to trigger the GetCount() function again.

Answer №1

In order to maintain security, it is not possible to directly access JavaScript functions included on AJAX-loaded pages. Instead, you must call the external JavaScript file and evaluate its contents within the application. Fortunately, numerous frameworks are designed to handle this process automatically.

Answer №2

In my experience with web development, I often utilize HTML in the following way:

<div>
  Inserting my markup here
</div>

<script type="text/javascript">

(function ($) {
   window.myFunction = function() {
      alert("Executing code from an ajax loaded file");
   }
})(jQuery);

</script>

When using jQuery, I make a call similar to this:

$("div#loadMe").load("/snippets/file.html", function(response, status, xhr){
  if (status == "error") {
    alert ("Error");
    return;
  }
  // perform actions
  window.myFunction();
});

It's important to note that when loading content via ajax with jquery, the entire file needs to be loaded for scripts to run properly. Targeting specific elements within a file may cause issues where scripts are not executed. For example, using

load("/snippets/file.html #container")
may not trigger your scripts.

Additionally, it is crucial to be on the same domain for this method to work effectively, unless you are utilizing jsonp for cross-domain requests.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In the iOS app when the Ionic HTML5 select keypad is opened, a bug causes the view to scroll upwards and create empty space after tapping the tab

I am currently working with Ionic v1 and AngularJS, utilizing ion tabs: <ion-tabs class="tabs-icon-top tabs-color-active-positive"> <!-- Home Tab --> <ion-tab icon-off="ion-home" icon-on="ion-home" href="#/tab/home"> <ion-nav ...

Vows: proceed to the subsequent error handling process

Can you explain how to properly call the next error function using promise chaining? I initially believed that placing a return statement within the error function would automatically trigger the next error function. //This code is executed in a contr ...

Creating a dynamic sidebar based on roles in AngularJS

I'm looking to create a dynamic sidebar based on the user's role, which is stored in $rootScope.login. However, I'm unsure of how to integrate it into template.js. Below is my JavaScript code and I'm still relatively new to AngularJS. ...

Updating the value of a $scope variable located within an included template in AngularJS

My setup is quite simple as outlined below. The issue I'm facing is that out of the two variables I define within the $http success callback, only one is reflected in the UI. In this scenario, I am attempting to display progress when the controller l ...

Scraping the web with cheerio: Should we delete or disregard a child element?

There's a specific website I'm looking to scrape, and its structure is as follows: <p><strong>a certain heading:</strong> some information etc. blabla </p> <p><strong>another heading:</strong> more deta ...

What could be the reason behind jQuery replacing the entire span with .text?

I am dealing with the following HTML code snippet: <p><input id="revenue" type="text" value="100000" /><span id="howmuch"><a href="" class="ka_button small_button small_cherry" target="_self" style="opacity: 1; "><span>How Mu ...

Using Ajax, PHP, and MySQL to implement an autocomplete feature

I created a form that includes two textboxes and a submit button. The second textbox has an autocomplete feature for user input. Upon submission, the page refreshes and displays a table with the contents of both textboxes using ajax. The autocomplete arra ...

Dependency on the selection of items in the Bootstrap dropdown menu

I am currently struggling with a few tasks regarding Bootstrap Dropdown Selection and despite looking for information, I couldn't find anything helpful. Check out my dropdown menu Here are the functions I would like to implement: 1) I want the subm ...

There is a hidden delete button obscured by another element. What steps can be taken to bring that element to the forefront and make it visible?

I'm having trouble positioning a delete button in the top right corner of a collapsible box. Despite setting it to `visibility: visible`, I can't seem to get it to display at the top of the collapsible element. Any suggestions or ideas would be g ...

Facing an issue in React-Native where unable to navigate to the second screen

I hope you don't mind the length of my query, as this happens to be my debut here and I am really eager to unravel the mysteries surrounding my code conundrum. Your assistance in this matter would be greatly appreciated. Could someone please lend me ...

Tips for arranging Intervals in sequence?

I've been developing a customized Pomodoro timer with user-defined work and rest times. In my Timer component, I have the following initial logic: useEffect(() => { start(3); start(timeData.workTime); start(timeData.restTime); }, []) c ...

Comparing Speed: ASP.Net MVC versus Webforms in Ajax Execution

After transitioning my website from Webforms to MVC, I've been relying heavily on AJAX. However, I've noticed that MVC seems to be slower but haven't implemented any benchmarks to confirm this. Can anyone shed light on which framework is fa ...

The Jquery Ajax image loading function will only work successfully when an alert statement is included within the $(window).one function

I'm facing a unique challenge. I am loading a JSON file containing the src, width, and height of multiple images. My goal is to load them into the smooth script jQuery plugin and automatically scroll through the images. The "viewing area" div can ac ...

Is there a way to transfer an array value from ajax to php without relying on the URL for

Currently, I am working on a search functionality that triggers upon the blur event of an input field. The search results are fetched via XML from a PHP page. However, there is an issue with passing values through the URL in a pop-up window due to the la ...

When using phonegap with iOS, HTTP requests consistently return a status of 0 when accessing local files

I've encountered an issue while using Phonegap 3.3.0 on iOS. The HTTP request I'm making always returns 0, regardless of whether the file exists or not! var url = './images/pros/imagefile.png'; var http = new XMLHttpRequest(); http.o ...

The touch event doesn't seem to be functioning properly on the div element, but it works perfectly on the window element

I have a dilemma that's been puzzling me lately. I'm trying to append a touchevent to a div, but my current method doesn't seem to be working. Here's what I've tried: $("#superContainer").bind('touchstart', function(even ...

sending the properties from the menu component to the dish details

Having trouble with a react.js app I'm working on that involves rendering dish cards. The dish object is always null when passed as props from MenuComponent to DishDetail, resulting in nothing being displayed on the screen. Can someone please assist m ...

What is the best way to obtain a unique dynamic id?

This is the unique identifier retrieved from the database. <input type="hidden" name="getID" value="<?php echo $row['ID']; ?>"> <input type="submit" name="getbtn" value="Get ID"> How can I fetch and display the specific dynami ...

Set up AngularJS routing for accessing the Web API endpoint

I have encountered an issue with my AngularJS application and Asp.net Web Api. Both applications are hosted on port 80 of the IIS server. The problem arises when the web api URL cannot be accessed due to angularjs routing redirecting API calls to the root ...

Ajax mysql is malfunctioning

Need help troubleshooting code Here is the code snippet: body.html <div class="container"> <div id="login_form"> <form action="login.php" class="form-signin"> <h3 class="form-signin-heading> ...