Jeffiec_c
Jeffiec_c

Reputation: 55

ajax call to send post

I have a small function that will eventually save to a database, but um having trouble reading the post into the php, here is the jquery:

$("#loginbtn").click(function() {

        var myData = new Array(
          'emp='+ $("#emp").val(), //build a post data structure
          'sdate='+ $("#sdate").val(),
          'tdate='+ $("#tdate").val(),
          'address='+ $("#address").val(),
          'city='+ $("#city").val(),
          'state='+ $("#state").val(),
          'zip='+ $("#zip").val(),
          'pos='+ $("#pos").val(),
          'sal='+ $("#sal").val(),
          'phone='+ $("#phone").val(),
          'sname='+ $("#sname").val(),
          'duties='+ $("#duties").val(),
          'reason='+ $("#leave").val()
        );
        alert(myData)
        jQuery.ajax({
        type: "POST", // HTTP method POST or GET
        url: "inc/functions.php", //Where to make Ajax calls
        dataType:"Data", // Data type, HTML, json etc.
        data:myData, //Form variables
        success:function(data){
            alert('back')
         },
        error:function (xhr, ajaxOptions, thrownError){
            alert(thrownError);
        }
        });
    });

it will display that it came back but of course the error is that the fields are null. any help appreciated. Jeff

Upvotes: 1

Views: 135

Answers (2)

Jeffiec_c
Jeffiec_c

Reputation: 55

Still really teaching myself ajax, returning the data in the correct format was the original problem, turns out it was working as intended, however i didnt really know how to handle it correctly.

Upvotes: 0

dfsq
dfsq

Reputation: 193261

The way you are sending data to the server is not correct. The better way to do it is to use form serialization:

$("#loginbtn").click(function () {

    //build a post data structure
    var myData = $('#login-form').serialize();
    alert(myData)
    jQuery.ajax({
        type: "POST", // HTTP method POST or GET
        url: "inc/functions.php", //Where to make Ajax calls
        dataType: "Data", // Data type, HTML, json etc.
        data: myData, //Form variables
        success: function (data) {
            alert('back');
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(thrownError);
        }
    });
});

For this to work, make sure all you input fields have name attributes, like emp, sdate, etc. Then on server side you will be able to read POST parameters like this

$_POST['emp']

The problem with your approach is that when you provide just an array there is no keys corresponding to values, and that's why you can't read nothing in PHP.

Upvotes: 2

Related Questions