0

New to programming - Currently working on a project for my Apprenticeship. I have a setup a asp.net application in Visual Studio. I have added a controller and created a 'contact' page. This works fine, user input is sent to the database no problems so far. The next step for me is to improve the UI so I have written the following Jquery code:

$(document).ready(function () {
    $("#show").hide();
    $("#click").click(function () {
        $("#hide").hide();
        $("#show").toggle();
        return false;
    });
});

This hides the div containing the input fields and submit button (for the contact page) and shows a div with a 'thank you' message. This function does hide the div but this stops the user input from being sent to the database.

Here is the C# code from the controller:

    public async Task<IActionResult> Create([Bind("Id,FullName,EmailAddress,Message")] Contact contact)
    {
        if (ModelState.IsValid)
        {
            _context.Add(contact);
            await _context.SaveChangesAsync();            
        }
        return View(contact);
    }

The 'return false' in the JQuery script seems to be the problem but if I 'return true' then the script doesn't work (unless there isn't any input within the fields).

My question is how can I get both the script and the back end to work at the same time?

Hope this makes sense and apologies if I haven't provided enough info

Thanks

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Does this answer your question? [event.preventDefault() vs. return false](https://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false) – freedomn-m Apr 13 '21 at 10:50
  • *return true the [it] doesn't work* - it's probably working fine, but then continuing and *resetting*, so it looks like it's not done anything. Learn some basic debugging, such as adding `console.log` (and turn on "Preserve log" in the browser console settings) - or add `debugger;` as the first line of your event handler - or other debugging techniques such as watching the [Network] tab to see what it's doing. – freedomn-m Apr 13 '21 at 10:53

1 Answers1

0

Assuming that #click is a submit button, then returning false from its handler function will stop the parent form from being submitted to the server. If you want to keep the user on the same page, without redirecting as the form submission occurs, you will need to stop the form submission and use AJAX to send the data to your controller instead.

Thankfully in jQuery this is trivial to do by using the $.ajax() method. However there's a few small tweaks to be made in the process. Try this, noting the comments:

$(document).ready(function() {
  $("#show").hide(); // I'd suggest doing this in CSS, not JS
  
  // hook to the submit of the form, not the click of the button. 
  // This is for web accessibility reasons, ie. users who browse using the keyboard only
  $('#yourForm').on('submit', function(e) { 
    // use preventDefault instead of return false. The latter prevents event bubbling 
    // which can cause unintended consequences.
    e.preventDefault(); 
    
    // send the data to the server via AJAX
    $.ajax({
      url: this.action, // set the URL to action of the form
      method: this.method, // set the HTTP verb to match the form, generally a POST in this case
      data: $(this).serialize(), // serialise the form data in to a querystring to send in the request body
      success: function() {
        // if the request worked, update the UI
        $("#hide").hide();
        $("#show").toggle();
      },
      error: function() {
        console.log('something went wrong, debug the request in devtools');
      }
    });
  });
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Thanks for your reply - could you confirm I have used the ajax request correctly. The jquery works but still not sending data to the server $.ajax({ Url: "Create".action, method: "Create".post, data: $("Create").serialize(), success: function () { $("#hide").hide(); $("#show").toggle(); }, error: function () { console.log('something went wrong'); } }); – Michael Braham Apr 13 '21 at 11:44
  • `"Create".action` and `"Create".post` aren't valid values. The URL needs to be the fully qualified path to the action in your controller, and the method needs to be a string such as `'post'` - or you can just use the `this.action` and `this.method` properties of the form as in my example above.In addition `$('Create')` isn't a valid selector, you've most likely missed out the `#` of `.` for a id or class selector respectively. – Rory McCrossan Apr 13 '21 at 12:09
  • 1
    Thanks I have it working now! used this: $.ajax({ Url: "@Url.Action("ContactsController", "Create")", method: "post", data: $("#hideForm").serialize(), success: function () { $("#hide").hide(); $("#show").toggle(); }, error: function () { console.log('something went wrong'); } – Michael Braham Apr 13 '21 at 12:55
  • No problem, glad to help – Rory McCrossan Apr 13 '21 at 12:57