53

I'm trying to send a form's data using jQuery. However, data does not reach the server. Can you please tell me what I'm doing wrong?

My HTML form:

<form id="contactForm" name="contactForm" method="post">
    <input type="text" name="nume" size="40" placeholder="Nume">
    <input type="text" name="telefon" size="40" placeholder="Telefon">
    <input type="text" name="email" size="40" placeholder="Email">
    <textarea name="comentarii" cols="36" rows="5" placeholder="Message"></textarea> 
    <input id="submitBtn" type="submit" name="submit" value="Trimite">
</form>


JavaScript (in the same file as the above form):

<script type="text/javascript">
    $(document).ready(function(e) {

        $("#contactForm").submit(function() {
            $.post("getcontact.php", $("#contactForm").serialize())
            // Serialization looks good: name=textInNameInput&&telefon=textInPhoneInput etc
            .done(function(data) {
                if (data.trim().length > 0) {
                    $("#sent").text("Error");   
                } else {
                    $("#sent").text("Success");
                }
            });

            return false;
        })
    });
</script>


Server side PHP (/getcontact.php):

$nume = $_REQUEST["nume"]; // $nume contains no data. Also tried $_POST
$email = $_REQUEST["email"];
$telefon = $_REQUEST["telefon"];
$comentarii = $_REQUEST["comentarii"];


Can you please tell me what I am doing wrong?


UPDATE

Checked var_dump($_POST) and it returned an empty array.

The weird thing is that the same code tested on my local machine works fine. If I upload the files on my hosting space it stops working. I tried doing an old-fashioned form without using jQuery and all data was correct.

I don't see how this would be a server configuration problem. Any ideas?

Thank you!

4
  • is your form getting submitted? or it just calls the ajax function?
    – zamil
    Commented Mar 2, 2013 at 12:00
  • @zamil it is submitted/ i can get data from severside back to jquery.
    – Dan Dinu
    Commented Mar 2, 2013 at 12:03
  • @Dan_Dinu: i have posted a code which i generally use for ajax calls. if you want you can use that
    – zamil
    Commented Mar 2, 2013 at 12:11
  • do u have a web-link of your hosting space? Commented May 31, 2014 at 6:18

8 Answers 8

110

You can use this function

var datastring = $("#contactForm").serialize();
$.ajax({
    type: "POST",
    url: "your url.php",
    data: datastring,
    dataType: "json",
    success: function(data) {
        //var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
        // do what ever you want with the server response
    },
    error: function() {
        alert('error handling here');
    }
});

return type is json

EDIT: I use event.preventDefault to prevent the browser getting submitted in such scenarios.

Adding more data to the answer.

dataType: "jsonp" if it is a cross-domain call.

beforeSend: // this is a pre-request call back function

complete: // a function to be called after the request ends.so code that has to be executed regardless of success or error can go here

async: // by default, all requests are sent asynchronously

cache: // by default true. If set to false, it will force requested pages not to be cached by the browser.

Find the official page here

39

You can add extra data with form data

use serializeArray and add the additional data:

var data = $('#myForm').serializeArray();
    data.push({name: 'tienn2t', value: 'love'});
    $.ajax({
      type: "POST",
      url: "your url.php",
      data: data,
      dataType: "json",
      success: function(data) {
          //var obj = jQuery.parseJSON(data); if the dataType is not     specified as json uncomment this
        // do what ever you want with the server response
     },
    error: function() {
        alert('error handing here');
    }
});
1
  • Perfect, exactly what I needed. A string is too rough to use when lots of data manipulation is involved! Thank you kindly! Commented Nov 6, 2019 at 4:04
1
 $("#contactForm").submit(function() {

    $.post(url, $.param($(this).serializeArray()), function(data) {

    });
 });
1
  • 4
    an explanation would be great in helping the OP. Commented Apr 11, 2016 at 8:43
0

Have you checked in console if data from form is properly serialized? Is ajax request successful? Also you didn't close placeholder quote in, which can cause some problems:

 <textarea name="comentarii" cols="36" rows="5" placeholder="Message>  
3
  • yes, serialized data looks good reuqest is succesful Placeholder was a copy paste typo.
    – Dan Dinu
    Commented Mar 2, 2013 at 11:43
  • Have you tried to var_dump($_POST);. And you could also check if when you change $.post url to getcontact.php?test=1 you actually receive it in $_GET['test'] on server side.
    – Jan.J
    Commented Mar 2, 2013 at 11:47
  • This seems to be server side issue.
    – Jan.J
    Commented Mar 2, 2013 at 12:15
0

Have you looked in firebug if POST or GET?.

check the console display.

Put in the test script:

console.log(data);

You can see the response from the server, if it shows something.

0

The problem can be PHP configuration:

Please check the setting max_input_vars in the php.ini file.

Try to increase the value of this setting to 5000 as example.

max_input_vars = 5000

Then restart your web-server and try.

0

Two End Registration or Users Automatically Registered to "Shouttoday" by ajax when they Complete Registration by form submission.

var deffered = $.ajax({
     url:"code.shouttoday.com/ajax_registration",
     type:"POST",
     data: $('form').serialize()
    }); 

        $(function(){ 
            var form;
            $('form').submit( function(event) {
                var formId = $(this).attr("id");
                    form = this;
                event.preventDefault();
                deffered.done(function(response){
                    alert($('form').serializeArray());alert(response);
                    alert("success");
                    alert('Submitting');
                    form.submit();
                })
                .error(function(){
                    alert(JSON.stringify($('form').serializeArray()).toString());
                    alert("error");
                    form.submit();
                });
            });
         });
0

Here is a more detailed and explained version of @rahulbhondave answer

$('#my-button').click(function () {
    $.post(this.form.action, $(this.form).serializeArray(),
            function (successMessage) {
                console.log(
                    successMessage
                );
            },
            "json"
        )
        .done(function () {
            alert("second success");
        })
        .fail(function () {
            alert("error");
        })
        .always(function () {
            alert("finished");
        });
});

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