-2

i find this thread here and works perfect for me but i want to evolve a little and to old.. and idk if i will receive any anwsers.. so i need a quick help. i use this code and works perfect:

HTML:

<form action="mail.php" method="POST" onsubmit="return foo(this);">
    <input type="text" name="full_name" value="" required>
    <button type="submit">submit form</button>
</form>

JavaScript:

function foo(form){
    $.ajax({
        url: $(form).attr('action'),
        type: 'POST',
        data: $(form).serialize(),
        success: (res)=>{
            // success...
            console.log(res);
        },
        error: (err)=>{
            // error...
            console.error(err);
        },
        complete: ()=>{
            // something here...
        }
    });

    return false;
}

but i want to integrate also this:

<script>
            $(document).ready(function(){
                //alert("b");
                jQuery("#a").css("background-color", "#ffebed");
                jQuery("#a").css("border", "2px solid #ff3f4c");
                setTimeout(function(){
                    //alert("hello");
                    jQuery("#a").css("background-color", "#fff");
                jQuery("#a").css("border", "1px solid #f4f4f4");
                $("#invalidmsg").hide();
                
                    $("a").val('');
                    $("a").val('');
                    $("a").val('');
                  document.getElementById("a").reset();
                }, 2000);
            });
            </script>

after i submit the button i want your help guys to extract/integrate from this javascript after i submit the button to make the input red and reset after 2 sec like here. and also bellow the input a text like "12345"

and sorry for my bad english. im not expert..

showdev
  • 28,454
  • 37
  • 55
  • 73
rguEBony
  • 3
  • 1
  • 2
    You might consider making an attempt and letting us know what specifically goes wrong. – showdev Aug 31 '21 at 02:22
  • i add the code with red box but appear when i access the page first time.. not after i submit the button.. – rguEBony Aug 31 '21 at 09:47
  • It seems you could put your code into the "success" callback. Better yet, put your code into a function and call that function upon "success". – showdev Aug 31 '21 at 19:10
  • i dont know how to do this correctly. i try but only fails.. so if you are kind .. – rguEBony Aug 31 '21 at 19:28
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Sep 02 '21 at 08:06

1 Answers1

0

You can add the button-changing code to the "success" or "complete" callback of the AJAX call. Depending on when you want the button to change, you could also start the changes as soon as the form is submitted, rather than waiting for a response from the AJAX call.

Your HTML has no #a or #invalidmsg element, as referenced in your JavaScript. Also, I'm not sure what $("a").val('') or document.getElementById("a").reset() are intended to do, since there are no <a> elements on the page, so I've removed them.

I recommend binding a submit handler rather than using inline events like onclick; see addEventListener vs onclick. I also suggest using a CSS class rather than directly changing the button's style attribute with css().

const $nameForm = jQuery('#nameForm');
const $submitButton = jQuery('#submitButton');

// bind the submit handler to the form
$nameForm.on('submit', formSubmit);

// submit handler
function formSubmit(e) {

  e.preventDefault();
  console.log('Form submitted.');
  let form = this;

  // Change the button here if you don't want to wait for the AJAX response.
  // changeButton();

  $.ajax({

    url: form.action,
    type: 'POST',
    data: $(form).serialize(),

    success: (res) => {
      console.log('Submission done.');
      //console.log(res);
    },

    error: (err) => {
      console.log('Submission failed.');
      console.error(err);
    },

    complete: changeButton

  });

}

// button changer
function changeButton() {

  console.log('Change button.');
  $submitButton.addClass('submitted');

  setTimeout(function() {
    console.log('Change button back.');
    $submitButton.removeClass('submitted');
  }, 2000);

}
#submitButton {
  background-color: white;
  border: 1px solid #f4f4f4;
}

#submitButton.submitted {
  background-color: #ffebed;
  border: 2px solid #ff3f4c;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="nameForm" action="https://reqres.in/api/users" method="POST">
  <input type="text" name="full_name" value="" required>
  <button id="submitButton" type="submit">submit form</button>
</form>

I'm not sure of your intention but, if you want to discourage multiple rapid submissions, you might consider temporarily disabling the button.

Here's an example that disables the button when the form is submitted and enables it again after AJAX response is received.

const $nameForm = jQuery('#nameForm');
const $nameInput = jQuery('#nameInput');
const $submitButton = jQuery('#submitButton');

// bind the submit handler to the form
$nameForm.on('submit', formSubmit);

// submit handler
function formSubmit(e) {

  e.preventDefault();
  console.log('Form submitted.');
  let form = this;

  // Disable button until response is received
  disableButton(true);

  $.ajax({

    url: form.action,
    type: 'POST',
    data: $(form).serialize(),

    success: (res) => {
      console.log('Submission done.');
      //console.log(res);
    },

    error: (err) => {
      console.log('Submission failed.');
      console.error(err);
    },

    complete: () => {
      // enable button again
      disableButton(false);
      // remove the input's value
      $nameInput.val('');
    }

  });

}

// button disable/enable
function disableButton(state) {
  console.log('Button ' + (state ? 'disabled' : 'enabled') + '.');
  $submitButton.prop('disabled', state);
}
#submitButton {
  background-color: white;
  border: 1px solid #f4f4f4;
}

#submitButton:disabled {
  background-color: #ffebed;
  border: 2px solid #ff3f4c;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="nameForm" action="https://reqres.in/api/users" method="POST">
  <input id="nameInput" type="text" name="full_name" value="" required>
  <button id="submitButton" type="submit">submit form</button>
</form>
showdev
  • 28,454
  • 37
  • 55
  • 73
  • works perfect and ty so much for doing this.. but i want the red appear on input and remain red input for 2 second and also with simple text like success bottom and after 2 sec to be a full refresh. but what you do is very professional and sorry for misleaded from button red.. but i need to be the red on input where i add the text. respect for your work. – rguEBony Sep 02 '21 at 08:13
  • but to explain better with a photo i want after i add some random text and submit to appear like in photo https://prnt.sc/1r0rrxm and after 2 sec to be normal. (also with a text red bottom will be nice) – rguEBony Sep 02 '21 at 08:20
  • That seems like a different issue. I hope my answer offers some ideas to get started. My advice is to make an attempt at what you want, even if you're not sure what to do. Break things into small parts and try to do the first part. If you get stuck and are not sure how to do something, search around online for examples. If you have specific trouble with your code, [post another question](https://stackoverflow.com/help/how-to-ask). – showdev Sep 02 '21 at 08:26
  • i will try to take your code after submit and move to input to be red after i submit. thanks again sir and have a good day. respect. – rguEBony Sep 02 '21 at 13:01