Ajax function is not recognized although it is defined in the script

jquery ajax
asynchronous ajax call jquery example
ajax datatype
$.ajax is not a function
ajax jquery post
jquery ajax example
jquery ajax get example
ajax success: function

I'm trying to submit two separate forms while using one button. After days of research I came to the conclusion, that I can't do this without using AJAX.

The 1st form submits to a Mikrotik router (so a user gets HotSpot Access), which checks the username and password. Mikrotik login page requires this "path": $(link-login-only).

The 2nd form has to send the email the user entered, but it has to send it after cca. 0.5sec, since it takes about that long for the user to gain internet access.

So far I've encountered two errors which I can't resolve:

1st: on this line: <input type="button" value="Submit" id="submit" onclick="SendAjax()"> <br /> - Uncought ReferenceError: SendAjax is not defined

2cnd: on this line url: "$(link-login-only)", - Uncought SyntaxError: Unexpected Identifier

Full code:

!DOCTYPE html>
<html>
<head>
<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous">
 </script>
<title>Post with delay</title>

</head>
<body>

    <form name="hotspot" action="$(link-login-only)" method="post" id="hotspot"
        $(if chap-id) onSubmit="return doLogin(); return false;" $(endif)>
        <input type="hidden" name="dst" value="$(link-orig)" />
        <input type="hidden" name="popup" value="true" />
        <input type="hidden" name="username" type="text" value="username" />
        <input type="hidden" name="password" type="password" value="password" />
    </form>

    <form name="mail" action="http://myserveraddress/verifysanitize.php" method="post" id="mail">
        <h1>Hotspot</h1>
        <h2>To gain internet access, enter your email.</h2>
        <br />
        <input type="text" name="email" autofocus="autofocus">
        <br />
        <input type="button" value="Submit" id="submit" onclick="SendAjax()"> <br />
    </form>


</body>
<script rel="javascript"  type="text/javascript">


    function SendAjax() {
        var email = $("#email").val();
        // Check if fields are empty 
        if (email=="") {
            alert("Please enter your email.");
        }
        // AJAX code to submit form
        else {$.ajax({
                type: "POST"
                url: "$(link-login-only)",                
                data: $("#hotspot").serialize(),
            });

            function callback(){
            $.ajax ({
                    url: $("#mail").attr('action'),
                }

            });
            }
            setTimeout(callback(), 1000);
        }
    }
</script>
</html>

After looking at the code before posting, would it be a solution to add a hidden button on the 1st form, and using ajax to send the 1st form before having a 0.5sec delay and then executing the 2nd form?

Your code seems fine to me you have syntax error check this bellow for the first error, you need to call the function on the button event.

$(document).on('click', '#submit', function(event) {
        event.preventDefault();         
        var email = $("#email").val();
        // Check if fields are empty 
        if (email=="") {
            alert("Please enter your email.");
        }else {
            $.ajax({
                type: "POST"
                url: "$(link-login-only)",                
                data: $("#hotspot").serialize(),
            })
            .always(function() {
                console.log("first call completed");
            });
            function callback(){
             $.ajax ({
              url: $("#mail").attr('action'),
          // } you need to remove this parenthesis
      });
         }
         setTimeout(callback(), 1000);
     }
});

The second error is due to the fact that you have one extra closing parenthesis }

Ajax : function is not working, U have error in your console: $ is not defined. Which mean u did not include jquery, so u should add this code after ajax include: <script� In FireBug, see if there are any loading errors that would indicate that your script is badly formatted and the functions do not get registered. You can also try typing "proceedToSecond" into the FireBug console to see if the function gets defined

Please try this:

!DOCTYPE html>
<html>
<head>
<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous">
 </script>
<title>Post with delay</title>

</head>
<body>

    <form name="hotspot" action="$(link-login-only)" method="post" id="hotspot"
        $(if chap-id) onSubmit="return doLogin(); return false;" $(endif)>
        <input type="hidden" id="dst" name="dst" value="$(link-orig)" />
        <input type="hidden" id="popup" name="popup" value="true" />
        <input type="hidden" id="username" name="username" type="text" value="username" />
        <input type="hidden" id="password" name="password" type="password" value="password" />
    </form>

    <form name="mail" action="http://myserveraddress/verifysanitize.php" method="post" id="mail">
        <h1>Hotspot</h1>
        <h2>To gain internet access, enter your email.</h2>
        <br />
        <input type="text" id="email" name="email" autofocus="autofocus">
        <br />
        <input type="button" value="Submit" id="submit" onclick="SendAjax()"> <br />
    </form>


</body>
<script rel="javascript"  type="text/javascript">

    $(document).on('click', '#submit', function(event) {

        if (!$("#email").val()) {
            alert("Please enter your email.");
            return false;
        }

        // AJAX code to submit form #hotspot
        $.ajax({

            type: "POST"
            url: "$(link-login-only)",                
            data: $("#hotspot").serialize(),
            success: (data => {
                console.log(data)

                // After getting response of #hotspot, Subbmitting the second form #mail
                $.ajax ({
                    url: $("#mail").attr('action'),
                    data: $("#mail").serialize(),
                    success: (dataMail => {
                        console.log(dataMail);
                    }),
                    error: (errorMail => {
                        console.log(`#hotspot successfuly submitted but #mail getting error: ${errorMail}`)
                    })
                })
            }),
            error: (error => {
                console.log(`#hotspot not submitted because #mail getting error: ${error}`);
            })
        });
    });
</script>
</html>

jQuery.ajax(), See jQuery.ajax( settings ) below for a complete list of all settings. recognized as "local," (e.g. the filesystem), even if jQuery does not recognize it as such Defines an object with additional attributes to be used in a "script" or "jsonp" request. Function not defined. firefox does not recognize the function name when it inside the jquery document.ready function. what i did was wrap it inside although it seems unconventional. I just removed the document ready and it works perfectly. seems chrome and FF dont recognize function names within this?

The reason for SendAjax not defined is because your script may not be in the same file as your code. SendAjax works in the following:

<html>
<head>
<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous">
 </script>
<title>Post with delay</title>

</head>
<body>

    <form name="hotspot" action="$(link-login-only)" method="post" id="hotspot"
        $(if chap-id) onSubmit="return doLogin(); return false;" $(endif)>
        <input type="hidden" name="dst" value="$(link-orig)" />
        <input type="hidden" name="popup" value="true" />
        <input type="hidden" name="username" type="text" value="username" />
        <input type="hidden" name="password" type="password" value="password" />
    </form>

    <form name="mail" action="http://myserveraddress/verifysanitize.php" method="post" id="mail">
        <h1>Hotspot</h1>
        <h2>To gain internet access, enter your email.</h2>
        <br />
        <input type="text" name="email" autofocus="autofocus">
        <br />
        <input type="button" value="Submit" id="submit" onclick="SendAjax()"> <br />
    </form>


</body>
<script rel="javascript"  type="text/javascript">


    function SendAjax() {
        alert('OK');
    }
</script>
</html>

jQuery.post(), Required if dataType is provided, but can be null in that case. dataType. Type: String. The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). This is a shorthand Ajax function, which is equivalent to: most "Ajax" requests are subject to the same origin policy; the request can not� We got an error: setAttValue() is not defined! What's going on here? Why Do We Get This Error? When the functions are declared at Type 1 above, the JavaScript interpreter moves the function declarations to the top of the JavaScript scope. This concept is also known as hoisting. Therefore the whole function body is lifted by the interpreter.

Can't get a JSON object in response to an Ajax request with wp_ajax , The script gets the Ajax response from admin-ajax. BODA82's answer helped, but eventually I realized that I should have replaced responseText with I didn't know there was a specific method to get the response in JSON. In a such way the object/array with get_posts() results is returned correctly and not as a string: Stack Exchange network consists of 177 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Simple ajax call not working in wordpress plugin, You have to put the name of your wp ajax action in your data when you do the ajax call. I assume the ajax url is correct. jQuery( document ).ready(function(){� However, a function can access all variables and functions defined inside the scope in which it is defined. In other words, a function defined in the global scope can access all variables defined in the global scope. var num1 = 2, num2 = 3; function numbers() { return num1 + num2; } console.log(numbers()); // 5 See also. Scope

jQuery Ajax Function: How to Make Asynchronous HTTP Requests, Learn how to use $.ajax(), the most powerful jQuery Ajax function, true if you want to force jQuery to recognize the current environment as “local”. scriptAttrs : Defines an object with additional attributes to be used in a “script” or stopped reading this list at the fifth or sixth element I guess, but that's fine. This technique is used on many popular sites, including jquery.com, and solves most #jQuery is not defined errors. If the CDN jQuery fails load, it will almost certainly load fine from your own domain, but you’ll also see the benefits of using a CDN-hosted jQuery for most of your users.

Comments
  • setTimeout(callback(), 1000); <--- bug. That code is wrong, it is not waiting 1 second to do the callback
  • I imagine I made quite a few mistakes, and i'll get to them in time. But 1st I would like to get the major problems out of the way. Thanks for pointing it out though =)
  • Thanks for hte anwser, but SendAjax is still not defined. =(
  • replace my code with entire sendAjax() function bellow it do the same.
  • I did a complete swap. didn't work. still got the SendAjax not defined.
  • $(document).on('click', '#submit', function(event) means clicking on the button id=submit run the code inside it.
  • remove the onclick="SendAjax()" from the button submit
  • Sorry for retracting the accepted anwser, but SendAjax is still not defined. :/
  • JS/JQuery is in the same file, below the forms. I don't know why it's not defined though...