Joomla 2.5 Ajax saving data to db character encoding - ajax

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

Related

Laravel ajax send multi dimension associative array

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

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!

pass an array to action using ajax YII

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.

CodeIgniter/Ajax - Send post values to controller

I'm working on a simple login form. When the user clicks on the Login button, I want to send the post values to my controller, validate them against my database (using a model) and return a value. Based on that value, I want to either send the user to the member area, or display an error message on my form. This error message has a class 'error' and is hidden by default. I want to use jQuery's show() to show it when the credentials are wrong.
My form has two textfields, one for the email address, other one for the password and a submit button. However, I have never really worked with Ajax except for VERY basic things like a simple loader, so I'm not sure what to do next.
$("#btn_login").click(
function()
{
// get values
var email_address = $("#email_address").val();
var password = $("#password").val();
// post values? and ajax call?
//stop submit btn from submitting
return(false);
}
);
I assume I have to use jQuery's ajax() method here, so I was thinking of working off this example:
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
However, I'm not really sure how to get my post values (those two vars) in the data: thingy.. Or should I take another road here? This seems like something I'll never forget how to do once I learn it, so if someone can help me out I'd be grateful. Thanks a lot.
All you need to do is create a key/value pair with the values and assign it to the data parameter and jQuery will do the rest.
//create a js object with key values for your post data
var postData = {
'email' : email_address,
'password' : password
};
$.ajax({
type: "POST",
url: "some.php",
data: postData , //assign the var here
success: function(msg){
alert( "Data Saved: " + msg );
}
});
With this, you should be able to access the data with Codeigniters input
EDIT
I've set up a test fiddle here : http://jsfiddle.net/WVpwy/2/
$('#dostuff').click(function(){
var email_address = $("#email_address").val();
var password = $("#password").val();
var postData = {
'email' : email_address,
'password' : password,
'html' : 'PASS'
};
$.post('/echo/html/', postData, function(data){
//This should be JSON preferably. but can't get it to work on jsfiddle
//Depending on what your controller returns you can change the action
if (data == 'PASS') {
alert('login pased');
} else {
alert('login failed');
}
});
});
I just prefer .post, but what you used is an equivalent.
Basically your controller should echo out data. Not return. You need to send a string representation of your data back so your script can (evaluate if json) and act on it
Here's a good example as a starting point : http://www.ibm.com/developerworks/opensource/library/os-php-jquery-ajax/index.html
just modifiy a little bit the url of your ajax :
$.ajax({
type: "POST",
url: "some/myfunction",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
Make sure your url point to the function you want inside your controller. For example: "myfunction" inside the controller some (in the file Some.php)
To access to your post variables inside the controller function do not try to put parameters to myfunction but :
class Some extends CI_Controller
{
......
public function myfunction()
{
$name = $this->input->post('name');
$location = $this->input->post('location');
}
......
}
You can definitely use your method, but a shorthand method is this:
$.post("some.php",{name:"John",location:"Boston",email:email_address,password:password},function(data,textStatus) { //response from some.php is now contained in data });

AJAX Return Problem from data sent via jQuery.ajax

I am trying to receive a json object back from php after sending data to the php file from the js file.
All I get is undefined.
Here are the contents of the php and js file.
data.php
<?php
$action = $_GET['user'];
$data = array( "first_name" => "Anthony",
"last_name" => "Garand",
"email" => "anthonygarand#gmail.com",
"password" => "changeme");
switch ($action) {
case 'anthonygarand#gmail.com':
echo $_GET['callback'] . '('. json_encode($data) . ');';
break;
}
?>
core.js
$(document).ready(function(){
$.ajax({ url: "data.php",
data: {"user":"anthonygarand#gmail.com"},
context: document.body,
data: "jsonp",
success: function(data){renderData(data);}
});
});
function renderData(data) {
document.write(data.first_name);
}
It looks like you have two data options set in the Ajax function. Instead of the line
data: "jsonp",
You need
dataType: "jsonp"
As you're not actually passing the PHP file any information.
Another couple of things, make sure you're getting valid JSON (jsonlint.com), we had a similar issue and it turned out we had the wrong kind of quotes.
Lastly: You MAY need to JSON.parse(data) to see convert it to an object at Javascript's end.

Resources