简体   繁体   中英

Saving data with jQuery/Ajax

I would like to have an alert whenever people start typing in the text box. It will return "Data Saved: " + my msg that's in the test.php folder.

$("#textbox").on('change keyup paste', function() {

           $.ajax({
                  method: "POST",
                  url: "test.php",
                  data: { content: $("#textbox").val() }
                })
                  .done(function( msg ) {
                    alert( "Data Saved: " + msg );
                  });
    });

I've tried changing "method" to "type". Using .serialize(). Using success: function

I'm not sure what the problem is. Thank you!

Edit: Added an error code. So far no error messages on console for this.

             $.ajax({
                  method: "POST",
                  url: "test.php",
                  data: { content: $("#textbox").val() }
                })

              error: function (request, error) {
                alert("An error occurred");
               },

                success: function (response) {
              if (response == 'OK') {
                $("#diary").val()
               } else {
                alert("An error occurred");


                  }

From your comment you are getting the following error:

$.ajax is not a function at HTMLTextAreaElement. (loggedinpage.php:92) at HTMLTextAreaElement.dispatch (jquery-3.1.1.slim.min.js:3) at HTMLTextAreaElement.q.handle (jquery-3.1.1.slim.min.js:3)

The error is telling you that the code cannot find the $.ajax() function anywhere in order to execute it.

At the same time, the message gives away the fact that you are using jQuery Slim. This cut-down version of the library does not include the $.ajax() function, among other things. You need to use the full version of jQuery.

Details in the latest (or any recent) release notes (in the "Slim build" section): https://blog.jquery.com/2017/03/20/jquery-3-2-1-now-available/

As a side note, I'm surprised that you want to show an alert every single time a user types a character into the textbox. I predict that this will quickly get very annoying for users. Maybe just showing a message inside a div nearby (which doesn't steal the focus and stop them typing) would be better. I'd also question whether it's really necessary to save the data to to the server every time a character is entered? If the user types quite a lot it will trigger off dozens of ajax requests. Your inclusion of the "keyup" is the reason for this. Perhaps have a rethink of exactly how you want this to work, and why.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM