POST parameters not accessible with AJAX post request - Printable Version +- CodeIgniter Forums (https://forum.codeigniter.com) +-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5) +--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24) +--- Thread: POST parameters not accessible with AJAX post request (/showthread.php?tid=84197) |
POST parameters not accessible with AJAX post request - discolo - 10-21-2022 Hello everyone! I am currently facing an issue which I have no idea how to solve... this is quite infuriating. I have a contact form that sends its content to a controller with the fetch javascript function and then I try to access the ajax body parameters from within the controller with $this->request->getPost('email') but to no avail. What works, however, is using: $this->request->getJsonVar('email'); What is weird is that I have the CSRF protection enabled and that the system manages to detect the csrf parameter. Here is my HTML form : Code: <form action="<?php echo site_url('send-mail'); ?>" method="post" onsubmit="return post_contact_form(this);"> function post_contact_form(form){ let email_input = form.querySelector("[name=contact-form-email]"); let phone_input = form.querySelector("[name=contact-form-phone-number]"); let details_input = form.querySelector("[name=contact-form-details]"); let csrf = form.querySelector("[name=jeton_csrf]"); let post_url = form.getAttribute("action"); // let my_form_data = new FormData(form); let my_form_data = { "email": email_input.value, "phone_number": phone_input.value, "details": details_input.value, "jeton_csrf": csrf.value }; fetch(post_url, { method: "POST", headers: { "Content-Type": "application/json", "X-Requested-With": "XMLHttpRequest" }, body: JSON.stringify(my_form_data) }) Here is my route : $routes->post('send-mail', 'MailController::sendMail'); Here is my controller class MailController extends \App\Controllers\BaseController { public function sendMail(){ if (strtolower($this->request->getMethod()) !== 'post') { return $this->response->setStatusCode(405)->setBody('Method Not Allowed'); } if(!$this->request->isAJAX()){ return $this->response->setStatusCode(405)->setBody('Method Not Allowed'); } // $post_data = json_decode($this->request->getBody(), true); $v_email = $this->request->getJsonVar('email'); $v_phone_number = $this->request->getJsonVar('phone_number'); $v_details = $this->request->getJsonVar('details'); $my_post_data = [$v_email, $v_phone_number, $v_details]; var_dump($this->request->getPost('email')); // null // return json_encode($post_data); return json_encode($my_post_data); // ["[email protected]","+330102030405","Lorem"] } } RE: POST parameters not accessible with AJAX post request - kenjis - 10-21-2022 You post as JSON: Code: fetch(post_url, { |