I am making a very simple mistake but couldn't able to find it.
I posted JSON object to CodeIgniter controller using AJAX but was not able to retrieve this value in the controller function.
My code is
AJAX code:
$.ajax({
type: "POST",
contentType: "application/json",
data: "{eventdata:" + JSON.stringify(eventToSave) + "}",
url: "<?php echo $base?>/index.php/welcome/addEvent",
dataType: "json",
success: function (data) {
alert(data);
$('#calendar').fullCalendar('renderEvent', event, true);
$('.qtip').remove();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger;
}
});
In the console, JSON object is shown in following format:
{
eventdata: {
"EventID": 170,
"StartDate": "Thu May 10 2012 00:00:00 GMT+0530 (India Standard Time)",
"EndDate": "Thu May 10 2012 00:00:00 GMT+0530 (India Standard Time)",
"EventName": "sdsfddsf"
}
}
CodeIgniter addEvent function:
$json_output[]=(array)json_decode($this->input->post());
print_r($json_output);
I have tried various other options also but couldn't able to get the value from json object which I need to store in database.Please tell me some way to retrieve this value from json object and then storing it in db
Try this one if it work.
$json = file_get_contents('php://input');
$json = stripslashes($json);
$json = json_decode($json);
convert the object array to array
$array = (array) $json;
This looks wrong.
url: "<?php echo $base?>/index.php/welcome/addEvent",
Are you sure you are actuelly hitting the right controller method? Did you check the source code?
Try doing something like this instead (using the URL Helper):
url: "<?php echo site_url('welcome/addEvent'); ?>",
Related
I'm a Laravel newbie and I'm converting a php/jquery app to Laravel. The original code used a JSON array with an ajax POST, which was retrieved like this:
$json = file_get_contents('php://input');
$data = json_decode($json,true);
I'm doing much the same thing on the POST side, but I don't see any data coming through in my Laravel $request collection. Is there something special that I need to do to retrieve JSON data structured like this:
[
{ "name": "John", "location": "Boston" },
{ "name": "Dave", "location": "Lancaster" }
]
Here is my jQuery ajax POST code (with hard coded data)
$.ajax({
type: "POST",
url: "/people",
data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
dataType: "json",
success:function(data) {
$('#save_message').html(data.message);
}
});
Here is the code in my Controller that receives the POST
public function store(Request $request)
{
dd($request->all());
}
But all I get is:
[]
Any ideas on how I can retreive my data?
You need to change your Ajax call to
$.ajax({
type: "POST",
url: "/people",
data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
contentType: "json",
processData: false,
success:function(data) {
$('#save_message').html(data.message);
}
});
change the dataType to contentType and add the processData option.
To retrieve the JSON payload from your controller, use:
dd(json_decode($request->getContent(), true));
instead of
dd($request->all());
$postbody='';
// Check for presence of a body in the request
if (count($request->json()->all())) {
$postbody = $request->json()->all();
}
This is how it's done in laravel 5.2 now.
Just a mention with jQuery v3.2.1 and Laravel 5.6.
Case 1: The JS object posted directly, like:
$.post("url", {name:'John'}, function( data ) {
});
Corresponding Laravel PHP code should be:
parse_str($request->getContent(),$data); //JSON will be parsed to object $data
Case 2: The JSON string posted, like:
$.post("url", JSON.stringify({name:'John'}), function( data ) {
});
Corresponding Laravel PHP code should be:
$data = json_decode($request->getContent(), true);
You can use getContent() method on Request object.
$request->getContent() //json as a string.
As of Laravel 5.2+, you can fetch it directly with $request->input('item') as well.
Retrieving JSON Input Values
When sending JSON requests to your application, you may access the
JSON data via the input method as long as the Content-Type header of
the request is properly set to application/json. You may even use
"dot" syntax to dig deeper into JSON arrays:
$name = $request->input('user.name');
https://laravel.com/docs/5.2/requests
As noted above, the content-type header must be set to application/json so the jQuery ajax call would need to include contentType: "application/json",
$.ajax({
type: "POST",
url: "/people",
data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
dataType: "json",
contentType: "application/json",
success:function(data) {
$('#save_message').html(data.message);
}
});
By fixing the AJAX call, $request->all() should work.
My jQuery ajax settings:
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: url,
dataType: "json",
type: "post",
data: params,
success: function (resp){
....
},
error: responseFunc
});
And now i am able to get the request via $request->all() in Laravel
dataType: "json"
is the important part in the ajax request to handle the response as an json object and not string.
I have a piece of code which goes as following:
var o_titular = {id:'01',fecha:'2014-01-01'};
var o_dependientes = [
{id:'02',fecha:'2014-02-02'},
{id:'03',fecha:'2014-03-03'}
];
var o_fecha = '2014-05-05';
$("#documento-antiguedad").ajaxSubmit({
dataType: 'json',
data: {
titular: o_titular,
dependientes: o_dependientes,
fecha: o_fecha
},
success: function(r) {
alert("yay success");
}
});
I'm forced to make this ajaxSubmit (this is a simplified code, but the complete case involves file uploading and such) but when I see the data I send in the POST request i got the following:
titular [object Object]
dependientes [object Object],[object Object]
fecha 2014-05-05
of course I want to fiddle with the content of the objects, not the object itself. How can I send this parameters as JSON objects with ajaxSubmit?
Thank you in advance
EDIT:
When I make a regular ajax call:
var o_titular = {id:'01',fecha:'2014-01-01'};
var o_dependientes = [
{id:'02',fecha:'2014-02-02'},
{id:'03',fecha:'2014-03-03'}
];
var o_fecha = '2014-05-05';
$.ajax({
url:'/pendientes/index/creatependienteantiguedad/',
dataType: 'json',
data: {
titular: o_titular,
dependientes: o_dependientes,
fecha: o_fecha
},
success: function(r) {
alert("yay success");
}
});
I get the following:
dependientes[0][fecha] 2014-02-02
dependientes[0][id] 02
dependientes[1][fecha] 2014-03-03
dependientes[1][id] 03
fecha 2014-05-05
titular[fecha] 2014-01-01
titular[id] 01
That's exactly what I want to get, but with ajaxSubmit instead of Ajax.
You could use:
JSON.stringify(o_dependientes);
That will turn the JSON object into a string
I make simple ajax request.
code is like this.
var paramObject = new Object();
paramObject.cd_nm01 = 'farm';
paramObject.cd_nm02 = 'server';
paramObject.cd_nm03 = 'cpu_num';
paramObject.cd_nm04 = 'mem_size';
paramObject.cd_nm05 = 'user_hdd';
paramObject.cd_nm06 = 'net_sprt';
paramObject.cd_nm07 = 'net_type';
var codes = JSON.stringify(paramObject);
$.ajax({
type: 'POST',
async: false,
cache: true,
dataType: 'json',
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type", 'application/x-www-form-urlencoded; charset=UTF-8');
},
url: '/common/getCodes',
data: {
'jParam' : codes
},
success: function(data, status ,xhr) {
console.log(data);
},
error: function(xhr){
}
});
I want send data of this: "'cd_nm':'farm','cd_nm':'server','cd_nm':'cpu_num','cd_nm':'mem_size','cd_nm':'user_hdd','cd_nm':'net_sprt','cd_nm':'net_type'}"
but in controller(Spring 3.1),
if I get those values from request,
they looks like below.
%7B%22cd_nm01%22%3A%22farm%22%2C%22cd_nm02%22%3A%22server%22%2C%22cd_nm03%22%3A%22cpu_num%22%2C%22cd_nm04%22%3A%22mem_size%22%2C%22cd_nm05%22%3A%22user_hdd%22%2C%22cd_nm06%22%3A%22net_sprt%22%2C%22cd_nm07%22%3A%22net_type%22%7D
How can I solve this problem?
Your request is just url encoded, like it should be. If you decode it it looks like this:
{"cd_nm01":"farm","cd_nm02":"server","cd_nm03":"cpu_num","cd_nm04":"mem_size","cd_nm05":"user_hdd","cd_nm06":"net_sprt","cd_nm07":"net_type"}
That looks like valid json to me. The form that you want to send the data in doesn't look right. You want to use single quotes and you don't have a leading bracket. If you don't want the 01, 02, 03 suffixes you probably need to change the JSON.stringify method to accept an array of strings instead of an object.
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.
I am using knockoutjs on an asp.net mvc page. I am using ajax to persist a form back to the server by calling ko.toJSON(viewModel) and then posting the results back to the server using jQuery. All of the properties on the view model are successfully serialized except for the Javascript date which is persisted as an empty object.
Declaration:
var viewModel = {
startTime: ko.observable(),
type: ko.observable(),
durationInMinutes: ko.observable(),
notes: ko.observable()
};
Save Data:
var postData = ko.toJSON(viewModel);
$.ajax({
url: "/data",
type: "POST",
data: postData,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
console.log('success!');
},
error: function () {
console.log('fail!');
}
});
The console.log value of viewModel.startTime() is:
Date {Tue May 10 2011 11:30:00 GMT-0500 (Central Daylight Time)}
After line 1 of Save Data, the value of postData is:
{
"startTime": {},
"type": "1",
"durationInMinutes": "45",
"notes": "asfasdfasdfasdfasdfasdfasdfas",
"displayableStartTime": "10-May 11:30"
}
If I expand line 1 of Save Data to
var jsonEvent = ko.toJS(viewModel);
jsonEvent.startTime = viewModel.startTime();
var postData = JSON.stringify(jsonEvent);
The value of postData is:
{
"startTime": "2011-05-10T16:30:00.000Z",
"type": "1",
"durationInMinutes": "45",
"notes": "asfasdfasdfasdfasdfasdfasdfas",
"displayableStartTime": "10-May 11:30"
}
Can anyone explain what might be going on and how I might be able to get knockoutjs to handle the date object?
Given the current issue with ko.toJS and dates, one option would be to create a dependentObservable containing the real value that you want the server to deal with.
Something like:
var viewModel = {
startTimeForInput: ko.observable(),
type: ko.observable(),
durationInMinutes: ko.observable(),
notes: ko.observable()
};
viewModel.startTime = ko.dependentObservable(function() {
return this.startTimeForInput().toJSON();
}, viewModel);
ko.applyBindings(viewModel);
Now, when you call ko.toJSON you will get the startTime with the correct value that the server could use.
For older browsers, something like json2.js would include the .toJSON for Date objects.
I had a problem with ko.toJSON() giving me a bad date format when the date was DateTime.MinValue.
Though probably not a fix for your problem, this fix worked for my ko.toJSON() date problem:
var postData = JSON.parse(JSON.stringify(ko.toJSON(viewModel)).replace(/\"1-01-01/g, "\"0001-01-01"));
ASP.Net WebMethod fails because ko.toJSON() produces different results for DateTime.MinValue