0

I'm going crazy! I'm trying to submit a form from jquery to php and insert a record in my database. I'm getting no error, but no record is being submitted. All works fine when I just go to the php page and put variables in the URL. But it doesn't work when I submit the variables via the jquery page. Can anyone help me out, please?

HTML:

<form id="tellusForm" >
      <div class="formHead">Tell us your story</div>
      <div id="thank">Thank you.</div>
      <table cellpadding="5">
      <tr><td>Name:</td><td><input id="tellName" type="text"/></td></tr>
      <tr><td>Country of origin:</td><td><select id="tellCountry"></select></td></tr>
      <tr><td>Age:</td><td><input type="text" id="tellAge"/></td></tr>
      <tr><td>Occupation:</td><td><input type="text" id="tellOccupation"/></td></tr>
      <tr><td>Email address:</td><td><input type="text" id="tellEmail"/></td></tr>
      <tr><td>Phone number:</td><td><input type="text" id="tellPhone"/></td></tr>
      <tr><td>A bit about you:</td><td><textarea  id="tellAbout" style="width: 100%;"></textarea></td></tr>
      <tr><td></td><td><input type="submit" value="Send" class="submit"/></td></tr>
      </table>
      </form>

jquery:

$('.submit').click(function(){

        $.get('tellus.php', { name: "laura"}, function(data){
                 eval(data);
        });


});

tellus.php:

<?php
require_once ('../constants_test.php'); 

    $name = $_GET['name'];

    $db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
                if (mysqli_connect_errno()) {
                        printf("Connect failed: %s", mysqli_connect_error());
                        exit;
                }

    $q = "Insert into tellus(`Name`) values ('" . $name . "')";
    if ($db->query($q)) {
        echo "console.log('you got it')";
    };
    $db->close();

?>
LauraNMS
  • 2,720
  • 7
  • 39
  • 73
  • At least try to prevent default behaviour of submit click: `$('.submit').click(function(e){ e.preventDefault(); $.get(...);});` – A. Wolff Mar 19 '14 at 16:44
  • Don't use `eval()` on the returned data. You shouuld also STRONGLY consider use of POST rather than GET when you are modifying values in your database. Have you done any debugging on the query itself to see if you are getting errors (as you are not handling error cases here at all)? – Mike Brant Mar 19 '14 at 16:44
  • Debug it? ;-) In e.g. Google Chrome you can view the XHR (Ajax) being submitted (press `F12` and view console - enable the "Log XMLHttpRequests" in the settings) and you can output various stuff in your `tellus.php` file to see if the variables are as expected. – Beauvais Mar 19 '14 at 16:46
  • @Mike Brant: I'm using GET just so I can figure out what's going on. I was using POST at first. – LauraNMS Mar 19 '14 at 16:48
  • Either get or post, you are not serializing your form correctly, and PHP are catching the unexpected. See my answer for solution. – rolodex Mar 20 '14 at 01:51

5 Answers5

1

Thanks everyone who tried to help me! I ended up having to do it this way:

$.post("./tellus.php", {tellName:name}, function(data){
alert(data)
}); 

The ajax call must have had something that wasn't working.

LauraNMS
  • 2,720
  • 7
  • 39
  • 73
0

Use serialize():

$("#tellusForm").on("submit", function() {

    event.preventDefault();

    $.ajax({
      url: 'tellus.php',
      data: $(this).serialize()
    }).done(function(data) {
      $(html).append(data);
    });

});

Also make sure to have names on your form elements:

<input type="text" name="tellAge" id="tellAge" />

This topic is very common here so try searching for other posts - e.g. Submit form using AJAX and jQuery could work too.

Community
  • 1
  • 1
Beauvais
  • 2,149
  • 4
  • 28
  • 63
0

The ajax call wasn't working because you are using $.serialize to serialize your form objects, which will return ;

{key:'tellName', value='name'} // <input name="tellName" value="name" />

whereas you are expecting a key:value pair. In order to get the data to send what you expecting, you should modify the object using this jQuery function:

$.fn.serializeObject = function(){
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
                o[this.name].push(this.value || '');
            } else  {
                o[this.name] = this.value || '';
            }
        });
    return o;
}

And call it whenever you're submitting form. It will structure your form to have the key:value pair.

<form id="register">
    <input type="text name="username" />
    <input type="text" name="email" />
    <input type="submit value="Register!" />
</form>

and the javascript (remember to include the serializeObject function)

$('#register').on('submit', function(){
    var data = $(this).serializeObject()
    // data will return {username: value, email:value}
    $.post('process.php', data, function(response){
        try{
            var r = JSON.parse(response) // Check if the response is an object
            console.log(JSON.stringify(r))
        }
        catch(e){
            console.log(response) // The response is a string
        }

    })
})

Cheers!

rolodex
  • 558
  • 1
  • 7
  • 19
-1
I suggest you should use POST for actions which include insert/delete/update of data in database.  It keeps the data safe.

If you want to still use GET and test out something.  I suggest do not use jquery in the middle to handle the get.  Submit button on click submits the form anyway, so the jquery $.get is unnecessary.

To your form element add 
<form name='' action='tellus.php'>...</form>

This should fix the problem.
akr
  • 739
  • 4
  • 15
-1

How about this one

jquery

$("#submit").click(function() {
    formData = {
        name: "abc"
    }
    $.ajax({
        type: 'GET',
        contentType: 'application/json',
        url: "http://yourpage/tellus.php",
        dataType: "json",
        data: formData,
        success: function(data) {
            console.log(data.message);
        },
        error: function(data) {
            console.log(data.message);
        }
    });
});

php

  <?php

// array for JSON response
$response = array();

// check for required fields
if (isset($_GET['name'])) {

    $name = $_GET['name'];

    // include db connect class
    require_once ('../constants_test.php'); 

    // connecting to db
    $db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
                    if (mysqli_connect_errno()) {
                            printf("Connect failed: %s", mysqli_connect_error());
                            exit;
                    }

    // mysqli inserting a new row
    $q = "INSERT INTO tellus('Name') values ('" . $name . "')";

    // check if row inserted or not
    if ($db->query($q)) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "you got it";

        // echoing JSON response
        echo json_encode($response);
        $db->close();
    } else {
        // failed to insert row
        $response["success"] = 0;
        $response["message"] = "Oops! An error occurred.";

        // echoing JSON response
        echo json_encode($response);
        $db->close();
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}
?>
Nurdin
  • 23,382
  • 43
  • 130
  • 308
  • I see it's submitting, but something is going wrong on the tellus.php page. How can I troubleshoot that page? – LauraNMS Mar 19 '14 at 17:17
  • Or, how can I figure out what error message that page is throwing? – LauraNMS Mar 19 '14 at 17:17
  • what error message my friend? can you show it to me? – Nurdin Mar 19 '14 at 17:17
  • @LauraNMS - call that page directly in the browser and add the URL paramters, `http://yourpage/tellus.php?name=abc` – Beauvais Mar 19 '14 at 17:18
  • @JohnMalli: It works when I do that, but not when I submit the form. – LauraNMS Mar 19 '14 at 17:24
  • @LauraNMS - specify names on your form elements, `` – Beauvais Mar 19 '14 at 17:29
  • @Dato: I just meant, if it's throwing an error message, I'd like to see it. I just don't know how to capture it. – LauraNMS Mar 19 '14 at 17:30
  • @JohnMalli: How can I make the php page tell me what the post variables are? – LauraNMS Mar 19 '14 at 17:36
  • try this one my friend, you can trace using request and response through JSON – Nurdin Mar 19 '14 at 17:37
  • @JohnMalli: I added names to the form inputs. But something is still wrong on the php page. It's somehow not getting the post variables. – LauraNMS Mar 19 '14 at 17:37
  • @Dato: I'm writing this in the code, but the response just comes back as object [Object]: $.ajax({ type: 'POST', contentType: 'application/json', url: "tellus.php", dataType: "json", data: $(this).serialize(), success: function(response) { alert('great'); }, error: function(response) { alert(response); } }); – LauraNMS Mar 19 '14 at 17:42
  • @Dato: The php seems to indicate that the form isn't posting: if (isset($_POST)) { ... } else { $response["message"] = $_POST; echo json_encode($response); } – LauraNMS Mar 19 '14 at 18:06
  • The message comes back as 'undefined'. So $_POST is undefined. – LauraNMS Mar 19 '14 at 18:06
  • $_GET is also undefined. – LauraNMS Mar 19 '14 at 18:12
  • Please do not submit an answer that still includes the SQL injection hole. If it did work, `$q = "INSERT INTO tellus('Name') values ('" . $name . "')";` is a problem. – Bill Turner Mar 19 '14 at 18:31
  • php will not find the ['name'] object because @LauraNMS is using $.serialize to the form. See my answer. – rolodex Mar 20 '14 at 01:52