A. Appleby A. Appleby - 1 month ago 5
Ajax Question

ajax() considering value null jQuery

I am trying to get all input data from a

div
and send it for processing (in PHP). However, even though I am certain, as I have console logged the variable
bookeeDetails
before calling the
ajax()
function, there is a value.

$("#finalsubmit").click(function () {
var bookeeDetails = [];

$("#bookeeDetails :input").each(function () {
bookeeDetails[$(this).attr('name')] = $(this).val();
});

console.log(bookeeDetails);

$.ajax({
url: url,
type: 'post',
data: {
bookee: bookeeDetails
},
success: function (response) {
$("#info").html(response);
}
});
});


Basically, I'm going for having access to
$_POST['bookee']['keyname']
in the PHP script. Unfortunately, when the request is being sent nothing is being received in PHP. I have tested putting in fixed values, and that works, and I am 100% certain
bookeeDetails
contains data.

Is this a case of
bookeeDetails
not being populated yet as the request is being sent before the populating loop completes? If so, how do I stop this from happening?

Answer

Since i see submit in finalsubmit i guess that you've a form there so probably you're looking for serializeArray:

$( '#bookeeDetails' ).serializeArray();

Hope this helps.

var data = $( '#bookeeDetails' ).serializeArray();

var books = {};

$.each(data, function(i, obj){
  books[obj.name] = obj.value;  
})

console.log(books);
console.log(books['title']);
console.log(books['autor']);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form id='bookeeDetails'>
  <input type="text" name="title" value="Biography">
  <br>
  <input type="text" name="autor" value="Jack">
  <br>
  <input type="text" name="edition" value="2016">
</form>

Comments