1

I am trying to get my HTML form to pass through Javascript that will then pass it to PHP that will send it to MySQL.

However I either get the page to load the JS file in the browser, or the PHP file to load in the browser.

Here is my HTML form:

<div class="form" id="form" onclick="submitForm()">
<form id='contactform' action="js/contactform.js" method="post" onSubmit="submitForm()">
<input type="text" id="name" placeholder="Name" autofocus required><br>
<input type="text" id="email" placeholder="Email" required><br>
<input type="tel" id="telephone" placeholder="Telephone"><br>
Enquiry : <input type="radio" id="subject" value="enquiry" required>
Booking : <input type="radio" id="subject" value="booking" required><br>
<textarea id="message" required rows="20" cols="20" placeholder="Enter your message and I will try to get back to you within 2 days."></textarea><br>

<input type="submit" name="submit" value="Submit" class="submitbutton"/>
<input type="reset" name="clearbutton" value="Clear" class="clearbutton"/>
</form>
<div id="outcome"></div>

I want the outcome of the form submit placed into the "outcome" div

My JS code:

function getOutput() {
  getRequest(
      'php/getinfo.php', 
       drawOutput,
       drawError
  );
  return false;
}



// handles drawing an error message
function drawError () {
    var container = document.getElementById("content");
    container.innerHTML = 'Bummer: there was an error!';
}

// handles the response, adds the html
function drawOutput(responseText) {
    var container = document.getElementById("content");
    container.innerHTML = responseText;
}


// helper function for cross-browser request object
function getRequest(url, success, error) {
    var req = false;
    try{
        // most browsers
        req = new XMLHttpRequest();
    } catch (e){
        // IE
        try{
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            // try an older version
            try{
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                return false;
            }
        }
    }
    if (!req) return false;
    if (typeof success != 'function') success = function () {};
    if (typeof error!= 'function') error = function () {};
    req.onreadystatechange = function(){
        if(req .readyState == 4){
            return req.status === 200 ? 
                success(req.responseText) : error(req.status)
            ;
        }
    }
    req.open("GET", url, true);
    req.send(null);
    return req;
}
        function submitForm(){
            var name = document.getElementById('name').value;
            var booking = document.getElementById('subject').value;
            var enquiry = document.getElementById('subject').value;
            var email = document.getElementById('email').value;
            var telephone = document.getElementById('telephone').value;
            var message = document.getElementById('message').value;
            getRequest(
                'php/form.php?' + params, //URL for the PHP file
                procesOutput,
                processError
            );
            return false;
        }

        function processOutput(){
            var  container = document.getElementById('outcome');
            container.innerHTML = responseText; 
        }

        function processError(){
            alert("There has been an error, please try again"); 
        }

and my PHP code:

    $con=mysqli_connect("DBLocation","Username","Password",'DBName');

    if (mysqli_connect_errno()){
        die("Error: "  . mysqli_connect_error());
    }

    $result = mysqli_query($con,"INSERT INTO `Contact`(`Name`, `Email`, `Telephone`, `Enquiry`, `Booking`, `Message`) VALUES ([value-2],[value-3],[value-4],[value-5],[value-6],[value-7])");

    if ($conn->query($sql) === TRUE){
        echo "Thank you for contacting us, I will replay to you soon!"; 
    } 

    else {
        echo "I'm sorry but an Error has occured. Please try again shortly";
    }

    mysql_close($conn);
?>

I've had a look at w3schools pages and some other questions on here but I can't seem to get my head around it.

4
  • 1
    What's getRequest? Commented Feb 6, 2015 at 20:46
  • 'getRequest' will run either the positive outcome(insert the true echo from php) or negative outcome depending if it works or not. Commented Feb 6, 2015 at 20:48
  • What happens if you remove the return from your onsubmit? Commented Feb 6, 2015 at 20:53
  • It's right you make a get Ajax call? Commented Feb 6, 2015 at 20:54

3 Answers 3

1

A couple of things, first off what is getRequest? Second off, where is responseText defined? Third, I would check your console as I'm pretty sure there is an error in submitForm. I see lots of getElementByIds, but none of your inputs have ids associated with them:

<input type="text" name="name" placeholder="Name" autofocus required>

Should be:

<input type="text" id="name" placeholder="Name" autofocus required>
Sign up to request clarification or add additional context in comments.

1 Comment

getRequest was something that I found in some other code, if it is not needed, I can take it out. responseText is defined further up in the code And thank you for pointing out those ID errors, I have changed those already
0

I believe you want to use Ajax, which you can easily use with jQuery.

I believe the answer for your question is right on this page: https://learn.jquery.com/ajax/ajax-and-forms/

If jQuery is new for you, you might want to read a little about jQuery: https://learn.jquery.com/about-jquery/

If you don't want to use jQuery, you can use directly XMLHttpRequest in javascript instead.

Comments

0

Here is a demo in JSFiddle.

  1. Remove onClick, onSubmit, action="js/contactform.js" method="post" attributes as you don't need them. Capture the form submit in js. How to? - link

  2. Add id's on the form elements so than you can select them like:

var name = document.getElementById('name').value;

  1. Make a $.post request with jQuery (How to? - Link) and handle the success and failure callbacks. (I don't understand why are you making a post request, I would recommend you a $.get request.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.