Link to home
Start Free TrialLog in
Avatar of ghj Grandhe
ghj Grandhe

asked on

Button click event in jquery

Actually, Iam new to JQuery. I have a question that when we click the button. it doesn't go to that demo_test.txt file.Actually i had created demo_test.txt file locally.But for button click event the control doesn't went to there.
could you please help in regarding this.


<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $.ajax({
                    url: "demo_test.txt", success: function (result) {
                        $("#div1").html(result);
                    }
                });
            });
        });
    </script>
   
    <meta charset="utf-8" />
    <title></title>
</head>
<body>

    <div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

    <button>Get External Content</button>
</body>
</html>
Avatar of Zakaria Acharki
Zakaria Acharki
Flag of Morocco image

First of all try to use an alert to make sure if the event is fired or not like :

$("button").click(function () {
       alert('Button clicked');
});

Open in new window


And for the ajax sample you could use :

$.get("demo_test.txt", function (result) {
    $("#div1").html(result);
});

Open in new window


Note that you can't test this locally you need some server to use ajax and perform an HTTP request else your request will be blocked by CORS policy: Cross-origin requests are only supported for protocol schemes: HTTP, data, https.
Avatar of ghj Grandhe
ghj Grandhe

ASKER

Actually the event is firing. but,i have a question that is it possible to make Ajax call without usage of server.please let me know about this
To perform an HTTP request you absolutely need a server, but if you want to request a file locally some browsers accept the ajax requests with 'file://' protocol to get the local files, in other browsers you may need to allow requests to the local file system from the browser setting.
You can't use Ajax without a server because the browser has security measures to prevent it.
I would not consider to allow browser to access local file for security reason.

If you want to run your script locally, you can set a local web server using  Wampserver http://www.wampserver.com/en/
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.