I would like to do something very simple but I can't make it work, I only want to send via jquery ajax a multi dimensional array to laravel and get the data back.
For example:
var info = JSON.stringify([{'key':'val1'},{'key':'val2'},{'key':'val3'}]);
$.ajax({
type: "POST",
url: "{!! route('ajaxactivityperemployee') !!}",
data: {"mydata":info},
success: function(msg){
console.log(msg);
}
On the other side, on my controller, I try this:
public function postActivityPerEmployee(Request $request)
{
$input = $request->all();
return $input['mydata'][0]['key'];
}
I ve tried various combinations but I always end up with a 500 page error or in the console, I only get [ and nothing else.
Don't stringify your info because you will send a string.
use this instead :
var info = [{'key':'val1'},{'key':'val2'},{'key':'val3'}];
which mean that you want to send an array of Objects
Related
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:
I send text message like this
html markup
<textarea id="request" cols="20" rows="4"></textarea>
javascript code
var data = {request : $('#request').val()};
$.ajax({
type: "POST",
url: "{{ path('acme_member_msgPost') }}",
data: data,
success: function (data, dataType) {
alert(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Error : ' + errorThrown);
}
});
symfony2 controller code
$request = $this->container->get('request');
$text = $request->request->get('data');
but $text is null ...
I have tried normal post request (not Ajax) by firefox http request tester.
/app_dev.php/member/msgPost
Controller works and $text has a value.
So I think the php code is OK, there is the problem on Ajax side, however
'success:function' is called as if succeeded.
How can you get the contents of javascript data structure?
First, you don't need to access the container in your controller as it already implements ContainerAware
So basically your code should look like this in your Controller.php
public function ajaxAction(Request $request)
{
$data = $request->request->get('request');
}
Also, make sure by the data you are sending is not null by using console.log(data) in the JS of your application.
And finally the answer of your question : you are not using the right variable, you need to access the value of $('#request').val() but you stored it in a request variable and you used a data variable name in your controller.
Consider changing the name of the variable, because it's confusing.
If you're sending the data as JSON — not as form urlencoded — you need to access the request body directly:
$data = json_decode($request->getContent());
You are doing it wrong when obtaining the value, you must use:
$data = $request->request->get('request');
'cause request is the name of your parameter.
I'm trying to send a Backbone collection to Laravel with an Ajax Request.
I don't need to save it or update the database I just need to process the data with the Omnypay php Api. Unfortunately the Laravel Controller variable $input=Input::all() contain an empty string.
var url = 'index.php/pay';
var items = this.collection.toJSON;
$.ajax({
url:url,
type:'POST',
dataType:"json",
data: items,
success:function (data) {
if(data.error) { // If there is an error, show the error messages
$('.alert-error').text(data.error.text).show();
}
}
});
This is the Laravel Route:
Route::post('pay','PaypalController#doPay');
And finally the Laravel Controller:
class PaypalController extends BaseController {
public function doPay() {
$input=Input::all();
}
}
Your route doesn't match, it's
Route::post('pay','PaypalController#doPay');
So the url should be
var url = 'pay';
instead of
var url = 'index.php/pay';
BTW, not sure if anything else (backnone) is wrong.
Update : toJSON is a method, so it should be (you missed ())
var items = this.collection.toJSON();
The hack solution I found to transfer a backbone collection to Laravel was to convert the collection to JSON and then wrapping it in a plain object, suitable for the jQuery Ajax POST. Here is the Code:
var url = 'index.php/pay';
var items = this.collection.toJSON();
var plainObject= {'obj': items};
$.ajax({
url:url,
type:'POST',
dataType:"json",
data: plainObject,
success:function (data) {
if(data.error) { // If there is an error, show the error messages
$('.alert-error').text(data.error.text).show();
}
}
});
Now the $input variable of my "doPay" controller function contain an array of Backbone models.
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.
I try to send a datetime ( 2013-03-12 09:43:09 ) string from a form via ajax to the db. I used follwoing JS
$.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data: {
end: $('#endtime').val()
},
url: 'index.php?option=com_sprojectfree&view=checkin&task=saveSlot&format=raw',
success: function(data) {
console.log(data);
}
});
The url points to the method saveSlot in my controller.php
public function saveSlot ()
{
$input = JFactory::getApplication()->input;
$data = new stdClass();
$data->end = $input->get('end');
db = JFactory::getDBO();
$result = $db->insertObject( '#__spf_chunks', $data, 'id' );
...
}
The data objects look like this:
stdClass Object
(
[end] => 2013-03-12095730
)
and the POST source like this:
end=2013-03-12+09%3A57%3A30
I tried all combinations of charactersets, urldecode() and encodeURIComponent() in JS but nothing gives me the correct string with : back to save it in the db. What could I do? Thanks in advance.
Try this
echo urldecode("2013-03-12+09%3A57%3A30");
the decoding in php side.
Also normally when you call ajax the content type is no need mention.
Instead of passing data as object you can pass like this
var data = "end="+$('#endtime').val();
data: encodeURIComponent (data)
In controller you can access via JRequest::getVar('end');
Hope it helps