2016-02-06 1 views
2

Я пытаюсь получить данные из формы через AJAX на Laravel 5.Laravel 5 Доступ к АЯКС сообщение данных

JavaScript код:

event.preventDefault();  // Disable normal behaviour of the element (Form) 

var formData = { 
    form: $("#newCustomerForm").serialize()  // Transmit all input data of the form serialized 
} 

console.log(formData);  // Log to the console the Input data 

$.ajax({ 
    type: 'post',   // POST Request 
    url: 'save',   // Url of the Route (in this case user/save not only save) 
    data: formData,   // Serialized Data 
    dataType: 'json',  // Data Type of the Transmit 
    beforeSend: function (xhr) { 
     // Function needed from Laravel because of the CSRF Middleware 
     var token = $('meta[name="csrf_token"]').attr('content'); 

     if (token) { 
      return xhr.setRequestHeader('X-CSRF-TOKEN', token); 
     } 
    }, 
    success: function (data) { 
     // Successfuly called the Controler 

     // Check if the logic was successful or not 
     if (data.status == 'success') { 
      console.log('alles ok'); 
     } else { 
      console.log(data.msg); 
     } 
    }, 
    error: function (data) { 
     // Error while calling the controller (HTTP Response Code different as 200 OK 
     console.log('Error:', data); 
    } 
}); 

Маршрут:

Route::post ('user/save', '[email protected]'); 

контроллер :

public function createNewCustomer (Request $request) 
{ 
    $inputArray = $request->all(); 

    print_r ($inputArray['form']); 

    // Set JSON Response array (status = success | error) 
    $response = array ('status' => 'success', 
         'msg' => 'Setting created successfully',); 
    // Return JSON Response 

    return response()->json ($response); 
} 

В сети Вкладка гк я могу видеть, как параметры выглядеть следующим образом:

radio-inline-left=on&firstname=sdsd&private_lastname=&private_title=&private_birthdate=&private_email=&business_email=&private_phone=&business_phone=&private_mobile=&business_mobile=&brand=&business_job_title=&business_address_street=sdsd&business_address_po_box=&business_address_addon_1=&business_address_addon_2=&private_zip=&private_location=&business_address_street=&business_address_po_box=&business_address_addon_1=&business_address_addon_2=&private_zip=&private_location=&source=social_media&source=&availability=on&additional-info={"status":"success","msg":"Setting created successfully"} 

Я также пытался получить доступ к данным с $request->input('name of the field'), но тогда это всегда пусто.

Есть ли у кого-нибудь идеи, что я делаю неправильно?

ответ

1

Проблема заключается в том, что вы звоните $("#newCustomerForm").serialize(), и этот метод сериализует форма в URL-кодированных параметрах, а не закодированное json тело.

In this question для этого требуется ответ.

0

Вы можете получить доступ, как этот

$request['name of field']; 
0

я думаю, что вы должны получить данные в контроллере, как JSON:

 

    $request->json('field_of_interest') 

0

Проблема заключается в переменной formData. Вместо того, чтобы:

var formData = { 
    form: $("#newCustomerForm").serialize()  
} 

должно быть

var formData=$("#newCustomerForm").serialize(); 

 Смежные вопросы

  • Нет связанных вопросов^_^