pass an array to action using ajax YII - ajax

Hi i'm really new with YII, please help me to solve a simple problem.
I'm trying to pass some values from js to action and then to put them into database.
Most of this code i got from tutorial
public function actionInsert(){
$post = file_get_contents("php://input");
$data = CJSON::decode($post, true);
$read = new Read();
$read->attributes = $data;
$response = array();
$read->save();
}
Then i send:
$.ajax({
type: "POST",
url: "/read/insert/",
data: "name=imja&short_desc=korotkoe&author=avtor&image=photo",
error: function (){
alert('Error');
},
success: function(data){
alert('success');
}
});
But i get an 'error' alert and nothing goes to DB.

The values from .ajax don't get submitted as a JSON array, the values should simply be in the $_POST array. Also I like to return something like 'complete'. Try changing your code to this:
public function actionInsert(){
$read = new Read();
$read->attributes = $_POST;
$response = array();
$read->save();
echo 'complete';
die();
}
Or you can send it as a JSON array from the javascript side:
var data = {
name: 'imja',
short_desc: 'korotkoe',
author: 'avtor',
image: 'photo'
};
$.ajax({
type: "POST",
url: "/read/insert/",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
error: function (){
alert('Error');
},
success: function(data){
alert('success');
}
});
However even if you do this apache will see the header type and still populate the $_POST array correctly. So it really isn't needed.
Also if you haven't already install Firebug onto Chrome or Firefox so you can see that actual ajax calls in the console. See what error you are getting from your action function in your controller.

Related

Vuejs post returns json data but wont assign to vues data object

Hey guys I am using vuejs and ajax to send formData and return a json response. There's a json response comes though however I cant assign it to the vue data object. Any ideas as to why? Heres my method. I know the function is firing as it hits the other page and returns json data in the console. Message, nameExists, and error wont assign even though all our in the vue data property and is spelled correctly.
addTemplate: function() {
this.sub = true;
this.itemName = this.itemName.trim();
var addTemplateForm = document.getElementById("addTemplateForm");
var fd = new FormData(addTemplateForm);
if (this.validItemName == true /* etc...*/) {
$.ajax({
url:'addTemplateBackend.php',
type:'POST',
dataType: 'json',
data: fd,
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
error: function(data){
this.message = data.message;
alert('error');
},
success: function(data){
alert('success');
this.error = data.error;
this.message = data.message;
console.log(data);
this.nameExists = data.nameExists;
if(data.success == true){
$('#successModal').modal('show');
}
}
});
}
}
You need to either bind this:
success: function (data) {
this.message = data.message;
}.bind(this)
or use ES6 "fat arrow" syntax:
success: data => {
this.message = data.message;
}
See How does the "this" keyword work?.

Send POST Data with Ajax, withtout form, to a Symfony2 Controller, in JSON format

Good evening everybody!
I would like to send JSON Post Data to a Symfony Controller without form, but it doesn't work. I build a JSON data line and it is well built, it is NOT the problem. When I send my data with AJAX, the request is not filled.
Here is my Javascript code:
function validerSession()
{
//I don't describe the composition of the dataline.
var dataObject = JSON.stringify(obj); //My dataline JSONified
$.ajax({
type: "POST",
url: Routing.generate('cloud_money_drop_validerSession', { id: {{ partie.id }}, idSession: sessionId }),
data: dataObject,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (donnees) {
alert("Hello");
}
});
}
The AJAX call work.
Here is the PHP Symfony Controller method which received data:
public function validerSessionAction(Partie $partie, Session $session)
{
$request = $this->get('request');
$data = json_decode($request->getContent());
$serializer = $this->container->get('jms_serializer');
$response = $serializer->serialize($data, 'json');
return new Response($response);
}
But there is not any data in $data.
EDIT : An example of the dataline JSONified
{"trappes":{"1":{"id":"134","montant":"5000"},"2":{"id":"135","montant":"15000"},"3":{"id":"136","montant":"20000"},"4":{"id":"137","montant":"0"}}}
Do you have any idea ? I'm sure this is a common issue.
Thank you for your participation !
CloudCompany
I found the solution.
It's not really difficult.
It is not necessary to JSonify data. The controller has the capability to understand the original datatype.
So here is my simplified AJAX call:
function validerSession()
{
obj = new Object();
obj["title"] = "Title for example";
$.ajax({
type: "POST",
url: Routing.generate('cloud_money_drop_validerSession', { id: {{ partie.id }}, idSession: sessionId }),
data: obj,
success: function (donnees) {
data = Parse.JSON(donnees);
alert(data.title); //Show "Title for example"
}
});
}
And here is my Controller. It can recover data as an array of values.
public function validerSessionAction(Partie $partie, Session $session)
{
$request = $this->get('request');
$data = $request->request->all();
$serializer = $this->container->get('jms_serializer');
$response = $serializer->serialize($data["title"], 'json');
return new Response($response);
}
Thanks for the help!

Joomla 2.5 Ajax saving data to db character encoding

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

Getting 500 error with CI 2.0.x, ajax and CSRF enabled

I keep getting a 500 error when submitting an ajax request. If I turn off the CSRF in config then the posting works. Once I turn it on, though, then I get the 500 error again.
In config.php I have the following values set:
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
I do have jquery cookie being loaded and in my jquery file I have the following code:
$('#reorder').sortable({
opacity: '0.5',
update: function(e, ui){
newOrder = $( "#reorder" ).sortable('serialize');
csrf_cookie_name = $.cookie('csrf_cookie_name')
console.log(newOrder);
console.log(csrf_cookie_name);
$.ajax({
csrf_cookie_name: $.cookie('csrf_cookie_name'),
url: "/client/saveOrder",
type: "POST",
data: newOrder,
// complete: function(){},
success: function(feedback){
console.log('success');
$("#feedback").html(feedback);
//$.jGrowl(feedback, { theme: 'success' });
}
});
}
});
console.log of csrf_cookie_name right now is: cd660b153522bef89dc53f7f95cd6b1d so I am getting the value it seems?
And finally a really simple function in client that does the data handling. Normally I would separate some of this out into the model but I was trying to keep it simple until I got it working.
function saveOrder()
{
$items = $this->input->post('item');
echo '<br/>Items2:' . var_dump($items);
$total_items = count($this->input->post('item'));
for($item = 0; $item < $total_items; $item++ )
{
$data = array(
'pageid' => $items[$item],
'rank' => $item
);
$this->db->where('pageid', $data['pageid']);
$this->db->update('pages', $data);
// echo '<br />'.$this->db->last_query();
}
There's no form being used in the view. It's just an UL with a collection of LI's that I'm dragging around to sort.
There are two solutions. Both work. Check these posts - has ALL the information you need
a-simple-solution-to-codeigniter-csrf-protection-and-ajax
ajax-csrf-protection-codeigniter-2.0
I've had problems in the past when inadvertently using a <form> tag instead of using CI's native form helper form_open(). This needs to be present in order to create the hidden token field. There are also some good suggestions here: csrf-token-problem.
I had this problem few days ago, the solution is simple(at least for me).
change:
$.ajax({
csrf_cookie_name: $.cookie('csrf_cookie_name')
to
$.ajax({
csrf_test_name: $.cookie('csrf_cookie_name')
I got it to work finally. Here's the jquery I used to make it happen:
You have to use both the name of the token and the name of the cookie and make it part of the post object. So token name = cookie name and be sure to add a & at the end.
$('#reorder').sortable({
opacity: '0.5',
update: function(e, ui){
newOrder = 'csrf_test_name=' + $.cookie('csrf_cookie_name') + '&';
newOrder += $( "#reorder" ).sortable('serialize');
console.log(newOrder);
$.ajax({
url: "/client/saveOrder",
type: "POST",
data: newOrder,
csrf_test_name: $.cookie('csrf_cookie_name'),
// complete: function(){},
success: function(feedback){
console.log('success');
$("#feedback").html(feedback);
//$.jGrowl(feedback, { theme: 'success' });
}
});
}
});

Ajax Response from CakePHP Controller returning null

I'm tryin to validate an input field with an ajax call to a cakephp controller
My Ajax is:
$("#UserAlphaCode").change(function () {
$.ajax({
type: "post",
url: '<?php echo $this->webroot ?>' + "/alpha_users/checkCode",
data: ({code : $(this).val()}),
dataType: "json",
success: function(data){
alert (data);
},
error: function(data){
alert("epic fail");
}
});
});
My controller code
function checkCode() {
Configure::write('debug', 0);
$this->autoRender = false;
$codePassed = $this->params['form']['code'];
$isCodeValid = $this->find('count',array('conditions'=> array('AlphaUser.code' => $codePassed)));
if ($isCodeValid == 0){
$codeResponse = false;
} else {
$codeResponse = true;
}
echo json_encode ($codeResponse);
}
I'm pretty sure I'm using $this->params wrong here to access the data sent from the ajax request. What should I be doing instead?
Try something like:
$codePassed = $_POST['code']
you might also try putting:
$this->log($codePassed,LOG_DEBUG);
somewhere in there and examine the output in tmp/logs/debug.log
Using firebug will help debug the transport.
Don't know why it would be returning null, but I normally use $this->data to fetch form data.
And did you try debug($this->params)? If you don't have a non-AJAX form to test the request from, use Firebug or Wireshark to see what is being return by the server for the debug() call—since it will break jQuery's AJAX handler by not being in JSON.

Resources