I am trying to post an associative array by an ajax call but the array i send is always empty (chrome network debug)
My ajax call
function getAssurance(passagers)
{
console.log(passagers);
var postdata = JSON.stringify({psg:passagers});
$.ajax({
dataType: "json",
url: rootUrl + "/b2c/searchAssurance",
data: postdata,
type: "POST",
success:function(result) {
console.log(result);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
}
The array is correct in my console.log()
My route
Route::post('/b2c/searchAssurance', 'VolControllerB2C@searchAssurance');
My controller
public function searchAssurance()
{
$search_data = Input::get('psg');
log::error(print_r($search_data,true));
echo "ok";
}
Where i build my array
var valide = true;
var psgDetails = [];
if($("#country").val() == "-1")
{
valide = false;
}
if($("#state").val() == "0")
{
valide = false;
}
if($("#phone_0").val() == "0")
{
valide = false;
}
if(valide)
{
for(var i = 0; i<$("#nb").val(); i++)
{
var onePsg = [];
if(i==0)
{
onePsg['country'] = $("#country").val();
onePsg['state'] = $("#state").val();
onePsg['phone_0'] = $("#phone_0").val();
}
if($("#title_"+i).val() == "0")
{
valide = false;
}
if($("#name_"+i).val().length < 1)
{
valide = false;
}
if($("#lastname_"+i).val().length < 1)
{
valide = false;
}
if($("#dob_day_"+i).val() == "Day")
{
valide = false;
}
if($("#dob_month_"+i).val() == "Month")
{
valide = false;
}
if($("#dob_year_"+i).val() == "Year")
{
valide = false;
}
onePsg["title"] = $("#title_"+i).val();
onePsg['name'] = $("#name_"+i).val();
onePsg['lastname'] = $("#lastname_"+i).val();
onePsg['dob_day'] = $("#dob_day_"+i).val();
onePsg['dob_month'] = $("#dob_month_"+i).val();
onePsg['dob_year'] = $("#dob_year_"+i).val();
psgDetails.push(onePsg);
}
}
if(valide)
{
console.log(psgDetails);
getAssurance(psgDetails);
$("#assurance").show("slow");
$("#assuranceArrow").toggleClass('arrow-down arrow-up');
$("html, body").animate({scrollTop: $('#assurance').offset().top }, 200);
}
Anyone know what i am doing wrong ?
I don't know which framework you are using but... In your backend method seems you are receiving the data using get but you are sending the data with jQuery using post:
public function searchAssurance() { // HERE you should use "post" to receive the data in your framework $search_data = Input::get('psg'); }
Note: if you are using Laravel, my answer is not right, since Input::get is used for all HTTP verbs;
I don't know if this is the only problem, but don't stringify the variable before sending it by ajax:
function getAssurance(passagers)
{
console.log(passagers);
//don't: var postdata = JSON.stringify({psg:passagers});
$.ajax({
dataType: "json",
url: rootUrl + "/b2c/searchAssurance",
data: postdata,
type: "POST",
success:function(result) {
console.log(result);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
}