AJAX call does not work as expected

I am trying to submit form data using ajax. But there is an error in the ajax operation and only the error callback function is executed. Here is what I tried:

$("#issue_submit").click(function (e) { console.log("clicked on the issue submit"); e.preventDefault(); // Validate the form var procurementForm = $("#it_procuremet_form"); if($(procurementForm).valid()===false){ return false; } // Show ajax loader appendData(); var formData = $(procurementForm).serialize(); // Send request to save the records through ajax var formRequest = $.ajax({ url: app.baseurl("itprocurement/save"), data: formData, type: "POST", dataType: "json" }); formRequest.done(function (res) { console.log(res); }); formRequest.error(function (res, err) { console.log(res); }); formRequest.always(function () { $("#overlay-procurement").remove(); // do somethings that always needs to occur regardless of error or success }); }); 

Routes are defined as:

 $f3->route('POST /itprocurement/save', 'GBD\Internals\Controllers\ITProcurementController->save'); 

I also added:

 $f3->route('POST /itprocurement/save [ajax]', 'GBD\Internals\Controllers\ITProcurementController->save'); 

I tried returning a simple string to an ajax call in the controller class. ITProcurementController.php :

 public function save($f3) { echo 'Problem!'; return; $post = $f3->get('POST'); } 

But only the 'error' callback is executed. I can’t find what is wrong. Please, help.

+5
source share
1 answer

You indicate that you expect json:

 // Send request to save the records through ajax var formRequest = $.ajax({ url: app.baseurl("itprocurement/save"), data: formData, type: "POST", // Here you specify that you expect json back: dataType: "json" }); 

What you send back is not json:

 echo 'Problem!'; return; 

This is an invalid string that is not valid json.

To send valid json back you will need:

 echo json_encode('Problem!'); return; 

You can also remove the dataType attribute, depending on your needs.

+5
source

Source: https://habr.com/ru/post/1272653/


All Articles