0

I've looked over a lot of similar questions about this and haven't gotten it to do anything, in spite of 'judiciously imitating' a lot of different implementations, so I figured I'd go ahead and bite the bullet and ask here before I waste any more time.

The page is meant to be a hybrid design, with both AJAX and non-JS functionality in place to send a form to a PHP file. The regular non-AJAX version works fine. With JS enabled, it uses <script> to pull up a script file with the following contents:

window.onload = newButton();

function newButton(){
    var button = document.createElement('button');
    button.innerHTML = 'jButton';
    button.onclick = process();
    document.getElementById('sro').appendChild(button);
    // sro being the id of the form.
  };

function process() {
// php form handling stuff
}

The button is supposed to send data to the PHP file, but instead, it just refreshes the page.

2
  • Do you know how to do an AJAX call? Commented Jun 10, 2018 at 19:29
  • Well, I had managed to hack a couple together before, just not with a button JS created. I actually had made another version of the page that didn't add the button, but rather started with one set up to call process, and that one worked fine. Perhaps I should've stuck with it, I don't know... after not getting this to work for so long, though, it became a matter of principle! Commented Jun 10, 2018 at 19:40

1 Answer 1

1
button.onclick = process;

is what you need. process() is just a regular function call, and happens right there, then onclick would store its result.

However you also mention it refreshes the page: do you add this button to a form? Because in that case the default behavior of buttons is to submit the form, regardless of having an event handler. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#attr-type, and add

button.type="button";
Sign up to request clarification or add additional context in comments.

1 Comment

I'd tried it with just process; before, but the button.type="button"; made all the difference. Thanks so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.