I am building a form that submits via Ajax. If our database updates successfully, the function in the controller returns numerical ids, and I would like to use these ids to change the view based on the result.
I am having difficulty parsing the ids that are returned from the controller. They are returned from the controller here:
foreach($update_pending as $product){
$success_ids[] = $product['product_id'];
}
if(isset($success_ids)){
echo json_encode($success_ids);
}else{
echo json_encode(array('error'=>'Error!'));
}
The ids are returned like this: [129818,129819,129820]
Now I want to parse this so that I can change the view based on which ids were submitted. I referred to this question JQuery Parsing JSON array but I am still missing something.
When I submit the form I get error "Cannot read property 'length' of null "
Here is the jQuery function (EDIT: I added dataType: 'json', no change in result):
$(function () {
$('form').on('submit', function (event) {
var product = $(this).attr("data-id");
event.preventDefault();
$.ajax({
type: 'POST',
url: 'category_typeahead',
data: $('form').serialize(),
dataType: 'json',
success: function (data) {
if(data.error == undefined){
alert(data);
product_ids = $.parseJSON(data);
for (var i=0, len=product_ids.length; i < len; i++) {
$(product_ids[i]).hide();
}
}else{
if($('.error_true').length==0){
$('#error').append('<div class="alert alert-error error_true">Error text</div>');
}
$('#error').show();
}
}
});
});
});