4

I'm having a little trouble with this and can't see what I'm doing wrong. I have this form:

<div class="user">

    <form name="userDetails" id="userDetails" method="post" >
        <input type="text" name="firstName" id="firstName" class="firstName"  placeholder="first name " />
        <input type="text" name="lastName" id="lastName" class="lastName"  placeholder="last name " />
        <input type="text" name="address" id="address" class="address"  placeholder="First line of Address " />
        <input type="text" name="postcode" id="postcode" class="postcode"  placeholder="Postcode " />
        <input type="text" name="email" id="email" class="email"  placeholder="E-Mail " />
        <input type="text" name="phone" id="phone" class="phone"  placeholder="Phone " />

        <input type="button" id="submitDetails" class="submitDetails" name="submitDetails" value="Submit Your Details" />

    </form>

</div>

So when the user clicks the button it should submit the form then have this PHP to act upon the form (I know that the sql isn't a prepared statement and is vulnerable to injections but this will be done later):

 <div class="overallSummary">

  <?php
    $fName = $_POST['firstName'];
    $lName = $_POST['lastName'];
    $address = $_POST['address'];
    $pc = $_POST['postcode'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];

    $userSQL = "INSERT INTO user (forename, surname, address, postcode, email, phone) VALUES ('$fName', '$lName', '$address', '$pc', '$email', '$phone')";


    $result = mysql_query($userSQL) or die(mysql_error());

   ?>
  </div>

However when I check my tables, no information is inserted into the database. Bearing in mind this code is all in the same document hence why I have not used action="file.type" within the form declaration. This is because I'm unsure whether ajax is appropriate here.

Any help is much appreciated, thank you.

EDIT

What I could do is use ajax with jQuery to listen for the button click event:

$(document).ready(function() {
  $(".submitDetails").click(function(e) {
      e.preventDefault();
       var userData = $("#?").val();
       var dataToSend = '?=' + eNameData;

    $.ajax({                
        url: "userDetailTest.php", 
        type: "POST",
        data: dataToSend,     
        cache: false,
        success: function(php_output)
        {
         $(".overallSummary").html(php_output);
           }    
    });
  });
});

The idea here is to use this ajax for when the button is clicked and call the ajax function but i'm unsure what to put as the ID in the variable 'userData' and what to add in the 'dataToSend' variable to make it work with my form.

2
  • No action attribute in your form Commented Mar 14, 2012 at 1:15
  • I have specified this in my question. Commented Mar 14, 2012 at 1:25

7 Answers 7

5

Actually to submit the form your input type needs to be submit, not button.

Using an button tag would also work.

<input type="submit" id="submitDetails" class="submitDetails" name="submitDetails" value="Submit Your Details" />

Unless you have some javascript code thats triggering the form submit.

The action attribute is also required as per the specification, but even without it, most browsers assume the action URL to be the current page.

Edit: If you want to submit the form data without reloading the page, you have to use either ajax, or put the entire form under an iframe. (Please, do it with ajax instead).

Otherwise clicking on the input[type=button] won't really do anything.

The user data is the actual data from your form, you could capture it using:

$(document).ready(function() {
  $(".submitDetails").click(function(e) {
      e.preventDefault();

    // See Teez answer, I wasn't aware of this.
    var dataToSend = $("#userDetails").serializeArray();

    $.ajax({                
        url: "userDetailTest.php", 
        type: "POST",
        data: dataToSend,     
        cache: false,
        success: function(php_output)
        {
         $(".overallSummary").html(php_output);
        }    
    });
  });
});
Sign up to request clarification or add additional context in comments.

3 Comments

Im needing to use 'button' because i'm not wanting the page to refresh.
Then using Ajax is required, not an option. (Yeah, iframes still exists, I know).
Thank you, I thought this might be the case. Are you able to tell me then how to pass the inputted data using the ajax function?
1

There are of of ways:

Just use below if don't want to refresh page:

 var dataToSend = $('userDetails').serializeArray();

Or try to use below code for submit form with jquery:

$("userDetails").submit(function(){
  // do your stuff
  $.post(
    "post.php",
    // add all stuff for inserting data 
  );

});

Below links will help you lot:

http://www.ryancoughlin.com/2008/11/04/use-jquery-to-submit-form/

1 Comment

Brother you forgot to enclose "userDetails" with quotes and to use # on your code sample.
1

Add action on the form and use submit.

<form action="pass_data_here.php" method="post">

<input type="submit" value="Submit"/>

Also to ease the debugging you could just echo first the fields before saving them to the db. That way you can play around with the data without the hazzle of going to the database admin table.

Edit: Since you really want a button then this ajax might be useful

$('.submitDetails').click(function(e) {
            e.preventDefault();

              var dataString =  "";
              //this will get all the data of your form separated by &
              $("form input:text").each(function(index, element) {
                    dataString += $(this).attr("id")+"="+$(this).val()+"&";
                });
            dataString = '?' + dataString; //added the needed ?

            $.ajax({                
                url: "userDetailTest.php", 
                type: "POST",
                data: dataString,     
                cache: false,
                success: function(php_output)
                {
                 $(".overallSummary").html(php_output);
                   } 
                });

            });//end submitDetails

3 Comments

Thanks for your reply, however I'm needing to use 'button', check my edit. Do you know how to apply the correct ajax function?
You can try the one I put on my edit. Note that I used the "id" of each input text as the name of the data.
Also Tezzs' answer seems to be better in passing the data json string
0

You basically answered your own question. You need to put the action in the form pointing to the script that handles the form. Start with that and if you decide to use AJAX later you can always modify the code a bit to do it.

Comments

0

You still need an action. If the PHP is on the same page you can use something like:

action="<?php echo $_SERVER['PHP_SELF']"

Comments

0

The three previous answers need to be combined to give one answer as you have actually two things missing from a workable HTML form, action and submit:

<form action="mytarget.php" method="post"/>
....add input fields...
<input type="submit" value="Submit"/>
</form>

2 Comments

Thanks for your reply. However I'm needing to use 'button'..see my edit.
Ok, well you're not asking "why won't this form submit" but "how do I submit it using Ajax" then. As someone mentioned - you need the ID of the whole form - #userDetails See @Nathan's response - that should do it.
0

You can submit the form using <input type="button"...> with some code of JavaScript

Just follow the steps:

1.Add the eventlistener onclick="functionName('buttonId','formName')" in the input tag

2.In the Script write a function as follows

function functionName(butVal, formVal)
{
document.getElementById(formVal).submit();
}

or if you want to access it in PHP POST Method...follow these steps

1.Add the eventlistener onclick="functionName('buttonId','formName')" in the input tag

2.In the Script write a function as follows

function functionName(butVal, formVal)
{
document.getElementById(butVal).type="submit";
document.getElementById(formVal).submit();
}

here, I changed the input type button to submit.

so, it can be received in the POST method.

if any validation needs to be performed, still it is possible to perform before changing the type in js function

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.