How to fetch ajax request data in cakephp 2 controller? - ajax

I'm trying to send some data from my view to my controller via ajax. How do I retrieve this data in my action?
I've tried jQuery's $.ajax and $.post methods, providing the url and data, but using $this->data, $this->request->data, $_POST, $_GET or $_REQUEST doesn't work (all return as empty arrays).
$.ajax({
url: "<?php echo Router::url( array("controller" => "Progression", "action" => "submit", $user['User']['id']) ); ?>",
type: 'post',
data: { name: "John" }
}).done( function(data) {
console.log(data);
});
function submit() {
$this->request->allowMethod('ajax');
$this->autoRender = false;
$data = array();
$data['answer'] = $this->request->data; // or any of $_POST, $_GET, etc.
return json_encode($data);
}
My console always keeps printing {"answer":[]}. I checked the network tab of my devtools and the data is successfully listed under Form data, yet I can't seem to get hold of the data in the action.
EDIT:
Thanks to Greg Schmidt I found out that my request indeed got redirected: first it gives me a 302, then it makes a new request without the post data and returns a 200. I just can't find what the critical difference is between the two requests (URLs look the same, no case difference or anything). Can anybody help me with that?
First request:
Second request:

Related

How Can I Prevent AJAX From Destroying My Session?

I'm currently building a web application using CodeIgniter 4. In one of my forms, I need ajax to send a post request and get the data result to modify the form base on item selected on a combo box.
The first requests were always okay, but it won't work for the next one. When I refresh the page, it redirects me to login page, due to my filter. It turns out that the AJAX request either destroy all my sessions, or update it to the new ones.
this is my ajax :
`
$('#penilaian_jenis').on('change', function() {
$.ajax({
OST type: "P",
url: '<?= base_url('guru/penilaian/get_nilai') ?>',
data: {
'kelas_id': '<?= $kelas->kelas_id ?>',
'kd_id': '<?= $kd->kd_id ?>',
'penilaian_jenis': $('#penilaian_jenis').val(),
},
dataType: 'json',
success: function(data) {
var result = JSON.parse(data);
alert(result);
}
})
})
`
This is my Controller :
`
public function get_nilaii()
{
echo json_encode('success');
}
`
This is how I stored my session at the auth controller:
$data = [
'user' => $user,
'guru' => $model->where('user_id', $user->user_id)->first(),
'guru_logged_in' => 1,
];
session()->set($data);
My Ajax codes I user are the simplest one. Can Anyone help give me the solutions to this problem, or recommend me another way to do HTML request without losing all my sessions?
Sorry for bad grammar, and thank you in advance

ajax request is not returning back to view in laravel 5

I wanted to submit a for using ajax call in laravel 5.
In view i wrote something like
$("#updateSubmit").on('submit',function(e){
e.preventDefault();
var csrfToken = $('meta[name="csrf-token"]').attr("content");
$.ajax({
method:'POST',
url: '/account/updateForm',
//dataType: 'json',
data: {accountId:'1111', _token: '{{csrf_token()}}'},
success: function( data )
{
alert(data)
return false;
}
},
error: function(error ){
alert("There is some error");
}
});
and on controller side
public function update(Request $data )
{
return Response()->json(['success' => true],200);
}
while in route for post method
Route::post('account/updateForm', 'AccountController#update')->name('account/updateForm');
its working till ajax. on Submission of ajax it goes to controller action.
but it does not retrun back as ajax comes back in normal form submisson.
it just go to controller and stops there with {"success":true} line.
I want ajax to come back to view form so that I can perform different dependent actions.
Do you mean that when you submit your form, you just have a white page with {"success": true} ?
If that's the case, maybe the error is on your javascript.
Maybe your jQuery selector is wrong, or maybe your js isn't compiled ?

Ajax POST to MVC Controller always erroring

I have the following Ajax request:
$.ajax({
url: '/Projects/Index',
type: 'POST',
data: data,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: xhr => { swal('From Error!', 'We\'ve saved your hours, thanks for your input!', 'success'); console.log(xhr) },
success: result => swal('From Success!', 'We\'ve saved your hours, thanks for your input!', 'success')
});
Which, even when the status code is 200, always errors. My controller receives the data and does stuff with it, and then returns View().
Here's my controller action in full:
[HttpPost, ActionName("Index")]
public ActionResult SetHours(HourPostRequest[] data)
{
foreach(var item in data)
{
var correctModel = item.ToEngineerHours(db);
db.EngineerHours.Add(correctModel);
db.SaveChanges();
}
var eng = db.Engineers.FirstOrDefault(e => e.DomainUsername == User.Identity.Name).ID;
var test = db.EngineerHours.Where(e => e.EngineerID == eng).ToList();
return View(test);
}
The data is always intact, received fine and View always returns. I've added in a random test collection to return which is the model of my View:
#model IList<Timesheet.Models.EngineerHours>
I've gone into the Chrome Dev-Tools Network view and the payload is correct, response is 200 and the controller has received the data and returned View.
This means that my SweetAlert2 alerts are always erroring regardless of the success status.
Can anybody spot why this might be happening?
You are returning the View(), which is an HTML string at the end of the day. However in your request you specify:
dataType: 'json'
which tells jQuery to expect response as a json formatted string. jQuery sees HTML and is not able to recognize it as a valid json, hence the error.

Retrieve post value in the controller sent by ajax call

I am unable to retrieve value sent as a post through ajax call in cake php controller file
$.ajax({
type: "POST",
url: "share",
data: country,
dataType: "json",
success: function (response) {
if (response.success) {
// Success!
} else {
console.log(response.data, response.code);
}
}
});
I have tried with the below ways of retrieving the data sent in the above code through POST. But none of them worked.
$this->params
$this->data
$_POST[]
$this->request
The url points to the function in the controller page.
Please can any of you let me know how the value can be retrieved.
When submitting data via ajax and you want cake to pick it up in the usual way just use $('whatever').serialize().
if you don't have an actual form to serialize you can fake it by submitting the data as follows:
$.ajax({
...
data: {
data: country
},
...
});
Note how cake generates fields like data[Model][field]. you don't need the Model part but the data part is important.

Jquery redirect not saving codeigniter session

I have a register page in which via ajax request i want to redirect the user to the logged in page. But, this particular ajax request does a redirect but doesn't pass on the session after the POST request
var dataString = 'name='+ name + '&email=' + email1 + '&password=' + password1;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "http://localhost/ci/index.php/login/add/",
data: dataString,
success: function() {
window.location.href = "http://localhost/ci/dashboard";
}
});
The login/add function is taking the values via POST request which then puts these value in session and does a redirect. The same thing is happening perfectly without a ajax request in plain php/CI. But, not happening via ajax request.
Here's the php code if it helps
if ($this->input->post("add") == "Sign up") {
$data_array = array(); //this array contains post data
$output = $this->user_model->add_new($data_array);
if($output == TRUE){
$this->session->set_userdata('logged_in', '1');
}
$data = array(
'name' => form_error('name'),
'email' => form_error('email'),
'password' => form_error('password')
);
echo json_encode($data);
}
The login/add function is taking the values via POST request which then puts these value in session and does a redirect. The same thing is happening perfectly without a ajax request in plain php/CI. But, not happening via ajax request.
It because previously you perform a synchronous request, while with jQuery ajax you are perform asynchronous request(this to say that your javascript is may ignore some part of your PHP script). Try adding async parameter in your ajax and set it to false

Resources