skip to Main Content

I am a beginner in coding and am learning ajax but my code is not working can anyone tell me what is wrong in my code.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $.ajax({url: "demo.txt", success: function(result){
      $("#div1").html(result);
    }});
  });
});
</script>
</head>
<body>

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

<button>Get External Content</button>

</body>
</html>

this is demo.txt

<h2>jQuery and AJAX is FUN!!!</h2>
<p id="p1">This is some text in a paragraph.</p>

this is my console error

4

Answers


  1. Pls follow the documentation provided at
    jQuery.ajax() | jQuery API Documentation

    It should work fine when you include in the same order.

    Login or Signup to reply.
  2. Your URL may need to start with localhost, for example: http://localhost :8080

    Login or Signup to reply.
  3. enter image description here

    This is how your URL can use ajax, because Ajax has cross domain restrictions

    If you are using vscode editor, you can download the "live server" plug-in and right-click in HTML to open the web page

    Login or Signup to reply.
  4. Little information about Ajax. Why do we use ajax, Ajax is mostly used for sending data from Javascript to the Back-end server. Lets say if you want to get the user input from front-end and you want to store the data in your database. Ajax comes to help.

    Example of a simple ajax function with passing user data (namely data1 and data2):

    $.ajax({
        type: "post",
        data: { 
            user_data1   : data1,
            user_data2   : data2,
        },
        url: YOUR_FUNCTION_PATH,
        success: function(data){
            // After success passing data to YOUR_FUNCTION
            // Handle what you do next
        },  
        error: function (request, status, error) {
            // Error of passing data to YOUR_FUNCTION
            // Debug to see what is wrong
        }
    });
    

    Then in your YOUR_FUNCTION and if you sending data to PHP function,

    $user_data1 = $_POST['user_data1'];
    $user_data2 = $_POST['user_data2'];
    

    If you are using the old one, CodeIgniter, it is pretty simple to get the data.

    $user_data1 = $this->input->post('user_data1');
    $user_data2 = $this->input->post('user_data2');
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search