I have big problems understanding and implementing the WP-way of AJAX. I have a setup that is "working", only that the page duplicates itself with an extra header/footer when form is submitted and this probably has to do that I have not done this in every aspect of the wp-way of doing it. Sigh! I was really glad to just get it going, and now I have to redo it in a different approach.

Well, I know that I should enqueue and localize my js and I have done it in my functions.php - is this okay? At least it is loaded but Im not able to use it in fully later on. I also know that the localize lets me use the admin-ajax.php which should be used doing this. Yep, so far so good. I can see that its loaded correctly and have the correct path to the admin-ajax.php when inspecting my page.

This is where I get lost. I dont know exactly where to put what code. Ive tried to rearrange code for hours now and Im not getting much closer.

This is what I currently have - what should I do?



if ( isset($_POST['name']) && isset($_POST['mail']) && isset($_POST['message']) ) {
    $name = $_POST['name'];
    $mail = $_POST['mail'];
    $message = nl2br($_POST['message']);
    $to = "[email protected]";
    $from = $mail;
    $subject = 'Kontaktformulär från emcolsson.se ifyllt';
    $message = '<b>Name:</b> '.$name.' <br><b>Email:</b> '.$mail.' <p>'.$message.'</p>';
    $headers = "From: $from\n";
    $headers .= "MIME-version: 1.0\n";
    $headers .= "Content-Type: text/html; charset=utf-8\n"; //Fixes ÅÄÖ in Sender name and Message

    if( mail($to, '=?UTF-8?B?'.base64_encode($subject).'?=', $message, $headers) ) { //Fixes ÅÄÖ in subject
        echo "success";
    } else {
        echo "The server failed to send the message. Please try again later.";


function _(id) {
    return document.getElementById(id); //makes _ a shortcode for document.getElementById(id)

function submitForm() {
        _("submitButton").disabled = true; //User cant click submit many times and resend form data, after first click its disabled.
        _("status").innerHTML = 'please wait...'; //Gives span value and the user an indication of that data is being processed.
        var formdata = new FormData(); // Creates variable that fetches they key value pair of id and value of  the form inputs.
        formdata.append( "name", _("name").value );
        formdata.append( "mail", _("mail").value );
        formdata.append( "message", _("message").value );
        var ajax = new XMLHttpRequest(); // creating an ajax variable which is a XMLHttpRequest, opens it/fires it by posting the formdata to parser.php
        ajax.open( "POST", "parser.php" );
        ajax.onreadystatechange = function() { //when ready do this function
            if(ajax.readyState == 4 && ajax.status == 200) { //when data is finished processing by php and data is returned by php to this ajax object(XMLHttpRequest)
                if(ajax.responseText == "success") {
                _("contact-form").innerHTML = '<h2>Thanks for contacting me '+_("name").value+' I will get back to you as soon as possible.</h2>';
                _("status").innerHTML = ajax.responseText;
            } else {
            _("status").innerHTML = ajax.responseText;
            _("submitButton").disabled = false; 
    ajax.send( formdata );



wp_enqueue_script( 'contactform', get_template_directory_uri() . '/js/contactform.js', array( 'jquery' ), 1.1, true );
include_once( get_template_directory() . '/includes/parser.php' );

1 Answer 1



Your page is refreshing because you tell the form to load a new page (the page specified under action).

Longer answer
The reason the page refreshes is because your form has an action associated with it. When I viewed your page yesterday, I saw the AJAX routine complete, and then the page refreshed. Why? Because after the AJAX finished (or even before it finished), the form was sent to the file specified under action. If you don't want the page to refresh, don't use the HTML form. Simply have input fields and tie the button click to the AJAX function. Does that make sense?


First, I would try to understand how Wordpress suggests AJAX is done. https://codex.wordpress.org/AJAX_in_Plugins

Second, I am wondering if you need AJAX. AJAX is used for accessing a database without having to reload the page. For example, in a Google search bar, you get suggestions as you type. This is AJAX.

However, submitting forms that reload a page with a "thanks" message is not what you should use AJAX for. Forms are handled differently with regular CGI (in Wordpress, you can do this in straight PHP). There is no need to create additional complexity if you use AJAX in this context.

Does that make sense? Just have the form action be a php file that collects the form data, stores it in the database, and writes a new page with the desired message.

  • Hi, this is what I originally had - but I dont want the user to be taken to a thankyou-page, I would like them to be able to send a mail, and the form to be cleared and remain on the same page, as it were when they first entered it and without the possibility of an additional submit or refresh of the page will send the same formdata again - another mail that is.
    – emcolsson
    Mar 22, 2017 at 18:30
  • Im following [link]solislab.com/blog/5-tips-for-using-ajax-in-wordpress and trying to use that to my code but so far im not getting it.
    – emcolsson
    Mar 22, 2017 at 18:34
  • I think the link you provided in the second comment is aimed more at people that can do AJAX and want to do it right, like if you're at the optimization stage. I'd suggest you try some tutorials first.
    – scott
    Mar 22, 2017 at 19:03
  • Regarding your first comment, I would suggest you rethink this intent. Users expect a webform to go to a new page. If you violate that expectation, some will think the submission didn't work and will therefore fill out the form again -- and you'll get another mail.
    – scott
    Mar 22, 2017 at 19:04
  • Not if I echo a "success" or similar response to if it was successfully or not. Also, I have done it AJAX but I want to make it correct, the way WP suggests.
    – emcolsson
    Mar 22, 2017 at 19:23

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.