How can I trigger the execution of the script when an asp button is clicked?

Instead of using the script within a div element by default, I am interested in triggering the script on button click.

 <div class="fb-login-button" data-show-faces="true" data-width="400" data-max-rows="1">
        </div>
        <script language="javascript" type="text/javascript">
            window.fbAsyncInit = function() {
                FB.init({
                    appId: 'xxxxxxxxxxx',
                    status: true,
                    cookie: true,
                    xfbml: true
                });
            };

            (function(d) {
                var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
                if (d.getElementById(id)) {
                    return;
                }
                js = d.createElement('script');
                js.id = id;
                js.async = true;
                js.src = "//connect.facebook.net/en_US/all.js";
                ref.parentNode.insertBefore(js, ref);
            }(document));
        </script>

Can someone guide me on how to call or run this script on an asp button click event?

Answer №1

Revise

The code provided is not fully complete. I have made some updates to it, and it has been tested on my domain successfully. Therefore, it should work smoothly on your domain as well. Place the following JavaScript code in a file named a.js. This code will be executed when a button is clicked:

window.fbAsyncInit = function() {
  FB.init({
    appId      : 'your_app_id', // App ID
    channelUrl : 'your_app_domain', // Channel File
    status     : true, // check login status
    cookie     : true, // enable cookies to allow the server to access the session
    xfbml      : true  // parse XFBML
  });

  // Subscribe to the auth.authResponseChange event
  FB.Event.subscribe('auth.authResponseChange', function(response) {
    if (response.status === 'connected') {
      alert('logged');
    } else if (response.status === 'not_authorized') {
      alert('non logged');
      FB.login();
    } else {
      alert('non logged everywhere');
      FB.login();
    }
  });
};

(function(d){
   var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
   if (d.getElementById(id)) {return;}
   js = d.createElement('script'); js.id = id; js.async = true;
   js.src = "//connect.facebook.net/en_US/all.js";
   ref.parentNode.insertBefore(js, ref);
}(document));

Next, add this code snippet to the desired page. Remember to include the fb-root div and other necessary elements Facebook requires:

<div id="fb-root"></div>
<div class="fb-login-button" data-show-faces="true" data-width="400" data-max-rows="1">
        </div>
<button onClick="loadit()">ZzZzz</button>

<script type="text/javascript">
function loadit(){
var head= document.getElementsByTagName('head')[0];
   var script= document.createElement('script');
   script.type= 'text/javascript';
   script.src= 'a.js';
   head.appendChild(script);

}
</script>

Update Complete

If you need to load a script dynamically using JavaScript, follow these steps after placing the relevant code in a file named a.js. Test the functionality to ensure it works correctly.

<button onClick="loadit()">ZzZzz</button>

<script type="text/javascript">
function loadit(){
var head= document.getElementsByTagName('head')[0];
   var script= document.createElement('script');
   script.type= 'text/javascript';
   script.src= 'a.js';
   head.appendChild(script);
}
</script>

(It's not necessary to hide the app id as it can only be accessed within the specified domain.)

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

Navigating within an ng-if or ng-show in AngularJS

Currently, I am developing a web application using AngularJS and there are times when I need to verify if the element inside the ng-if or ng-show directive belongs to a specific list. The approach I am using right now is shown below: <div ng-if="object ...

Unable to fetch the session variable using express-session

In my development work, I have been utilizing express-session for persistently storing sessions on a MongoDB database. While the project functioned flawlessly in a test environment, an issue arose when deploying to a production setting where the session v ...

Using the code `$("img").one('load'` can trigger only a single load event without repetition

I have implemented the following function: function CheckImage(url, index) { $("<img/>").one('load', function () { $("div.photos").append(this); }).attr('src', url).attr('data-photo', '0' + ind ...

Incorporate a JavaScript variable into an HTML href link for dynamic web content

This is a snippet from my code: <p id="demo">{$value.file_name}</p> <script type="text/javascript"> var str = document.getElementById("demo").innerHTML; var res = str.replace("/var/www/html/biology/demo", ""); document.getElementById(& ...

Replicating JavaScript functions with the power of Ajax

I'm facing an issue with Bootstrap modal windows on my page. The modals are opening and closing successfully, but the content inside them is fetched through AJAX as HTML. For example, there's a button in the modal: <button id="myBtn"> and ...

Sharing controller methods in Angular.js is a key aspect of enhancing

In my current project, I originally used Knockout for the CMS functionality, but decided to switch to Angular because I preferred its features. One of the key sections in the CMS is dedicated to 'Users', featuring a table where headers can be cli ...

JavaScript embedded in an HTML document, which in turn is embedded within JavaScript

Is it possible to nest tags within other tags to control the functionality of a download button in a chat bot? Unfortunately, nesting tags is not allowed, so I'm looking for an alternative solution. Below is the complete HTML file I'm working wit ...

Managing the creation of a fresh VueJs object with checkboxes enabled for CRUD operations

Hello fellow developers! I am currently working on a shop card project and I'm looking to add a new product to the collection of sale elements. Let's consider the JSON structure retrieved from the backend: "products": [ { "product_prov ...

What is the process of incorporating externally managed components in Vue.js?

After exploring various libraries that integrate an external library and their DOM elements with Vue.js, I noticed that most of them only add child elements to the Vue-managed DOM node. To simplify the use of the new Stripe V3 API, I developed Vue-Stripe- ...

A problem encountered in specific JavaScript code

As a newcomer to JavaScript, I have encountered an issue while trying to run this script: <html> <head> <title>Exploring javascript functionalities</title> </head> <body> <p id="demo">I ...

Implement ajax functionality to update an object within a JSP page

On my JSP page, I have implemented an accordion list (utilizing Bootstrap 3) with text and a Delete button within each node. When the user clicks on the delete button, that specific list item is removed. To construct the accordion list, I bring in an Array ...

vue.js libs requiring "new ..." are being scolded by eslint for their misspelling

When working with Vue libraries, such as Swiper, that require the use of 'new …' in the script section, I encounter ESlint errors no matter how I try to write it. Even though 'new ...' works perfectly fine in the frontend, ESlint cont ...

During the for loop, a string variable with the prefix "undefined" is

I'm currently working with a drop-down menu where I use the .Change() function to trigger a specific action. This action involves obtaining data using the getJSON method and then creating an array string for an mp3 file based on that data. The code b ...

Does Highchart offer support for drilling down into sub-categories?

I want to implement a sub-sub drill down feature in my Chart using the following code snippet. // Create the chart Highcharts.chart('container', { chart: { type: 'column' }, title: { text: 'Highcharts m ...

Creating unique robots.txt files for each sub-domain in IIS

I am managing a website on www.example.com, along with two staging platforms on beta.example.com and preview.example.com. I am looking for a way to configure different robots.txt files for each domain using IIS or a similar platform. The main purpose of t ...

The delete function is not functioning

I need help with implementing a custom Angular directive that includes a delete button to remove itself. When I click the button removeMe, it is not deleting an item from the array. Any suggestions on what might be causing this issue? HTML: <button t ...

Mocking a function from within the method under test

I need to run tests on a method in my code that runs a series of functions, one of which sends an email. Is there a way to prevent this function from sending emails during testing? I want to avoid using conditional statements like the one below in my cod ...

What is the process for combining two geometries or meshes in three.js?

I am working with two types of geometries: a line-based square 2D geometry and an icon image. My goal is to center and place the icons inside the designated region of the 2D rectangle. Here is the code snippet I have written: var combined = new THREE.Ge ...

Adding array elements to a JavaScript object

I find myself in a rather unique predicament that I'm struggling to navigate. I have come across some data structured as follows. Please bear with me if I use any incorrect terminology, as I am relatively new to this. usersByName: { "tester&q ...

Exploring the concept of upserting records using the MongoDB $

I am working with two collections in my database: Regions and Registrations. var RegionSchema = new Mongoose.Schema({ name: {type: String}, registrations: [{type: Mongoose.Schema.Types.ObjectId, ref: 'registrations'}], ... }); The Registr ...