Angular JSON post only sending one item of json array - javascript

I wrote an angular quiz and I'm trying to send the quiz results to the database for processing. My $http call is as follows:
function saveQuiz() {
quizObj.isSaving = true;
var data = {
id: quiz_id,
action: 'quiz_data',
part: 'save_quiz',
score: quizObj.score,
passed: quizObj.passed,
completed: quizObj.completed,
percentage: quizObj.perc,
time_spent: $filter('formatTimer')(quizObj.counter),
questions: quizObj.quiz.questions
};
console.log(data);
$http({
url: quizapp.ajax_url,
method: "POST",
params: data
})
.then(function(response) {
console.log(response.data);
quizObj.isSaving = false;
},
function(response) { // optional
// failed
console.log(response);
});
}
Notice I am passing an array of json questions as quizObj.quiz.questions.
The problem on the server side is that $_POST['questions'] evaluates to the last item of the quizObj.quiz.questions json object instead of the full list.
Where have I gone wrong?

When using the $http service through Angular, data goes with method: "POST" and params goes with method: "GET"
Change the properties on your config object you are passing to the $http service like so:
$http({
url: quizapp.ajax_url,
method: "POST",
data: data // <-- data here, not params since using POST
}).then(function () { /*...*/ }));

Related

Javascript AngularJS: Inner function cannot the variable value of outer function

I am developing ionic hybrid application. I am using $http to get value from server. Next, I will make a cordova sqlite query, inside the cordova query I want to insert my result from $http call from server and result of cordova query into my sqlite database. However, I can't get the value of $http return value in my cordova query. The following is my code:
$http({
method: "post",
url: "http://localhost/php2/get_channel.php",
data: {
user_name: usernameID
},
headers: { 'Content-Type': 'application/json' }
}).success(function(response) {
for(i=0; i<response.length; i++){
var channelNameQuery = "SELECT * FROM chat_friend WHERE channel_id=?"
var channelNamePromise = $cordovaSQLite.execute(db, channelNameQuery, [response[i].ChannelName]).then(function (result){
var ChannelQuery = "REPLACE INTO chat_channel (last_text, usernameID, chat_channel, chat_channel_name) VALUES (?,?,?,?)";
$cordovaSQLite.execute(db, ChannelQuery, [response[i].LastText, usernameID, response[i].ChannelName, result.rows.item(0).UserName]);
})
}
}).error(function(response) {
console.log(response);
console.log("failed");
});
I can't get response[i].LastText and response[i].ChannelName value inside $cordovaSQLite.execute() function.
Sorry for my poor language.
The data you recive is mapped on response.data. Try looping thru your data by using angular.forEach(). Remember that response is mostly a object so you cant get response.length here. Please take a look at the $http AngularJS documentation.
$http({
method: "post",
url: "http://localhost/php2/get_channel.php",
data: {
user_name: usernameID
},
headers: { 'Content-Type': 'application/json' }
}).success(function(response) {
angular.forEach(response.data, function (data) {
var channelNameQuery = "SELECT * FROM chat_friend WHERE channel_id=?"
var channelNamePromise = $cordovaSQLite.execute(db, channelNameQuery, [data.ChannelName]).then(function (result){
var ChannelQuery = "REPLACE INTO chat_channel (last_text, usernameID, chat_channel, chat_channel_name) VALUES (?,?,?,?)";
$cordovaSQLite.execute(db, ChannelQuery, [data.LastText, usernameID, data.ChannelName, result.rows.item(0).UserName]);
})
});
}).error(function(response) {
console.log(response);
console.log("failed");
});

Request and response with Angular $post and PHP Codeigniter

I have a problem when I am sending data to Codeigniter via Angular $post. I am using this JS code:
$scope.user.first_name = 'first name';
$scope.user.last_name = 'last name';
$http({
method: 'POST',
url: '/registration',
data: {user: $.param($scope.user)},
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}
}).then(function successCallback(response) {
console.log(response)
}, function errorCallback(response) {
console.log(response);
});
My PHP is based from another answer from StackOverflow, but still doesn't work:
echo file_get_contents('php://input');
var_dump($this->input->post());
, but in this way I see response empty array, if I say:
var_dump($this->input->post('user'));
I see response NULL, Same is and with:
var_dump(json_encode($this->input->post()));
with or without key "user". Even if I use:
var_dump($_POST);
for the response I get empty array.
How to send and get data via $post Angular service with Codeigniter ?
If you want to send as form encoded data you need to serialize the whole data object with $.param()
Change:
data: {user: $.param($scope.user)},
To
data: $.param(angular.copy({user: $scope.user})),
Or use $httpParamSerializerJQLike
If you use defaults of $http would just be
$http.post( '/registration',$scope.user).then(...
And in php
$data = json_decode(file_get_contents('php://input'));

Sending JS array via AJAX to laravel not working

I have a javascript array which I want to send to a controller via an ajax get method.
My javascript looks like this:
var requestData = JSON.stringify(commentsArray);
console.log(requestData);
//logs correct json object
var request;
request = $.ajax({
url: "/api/comments",
method: "GET",
dataType: "json",
data: requestData
});
I can tell that my requestData is good because I am logging it and it looks right.
and the controller is being accessed correctly (i know this because I can log info there and I can return a response which I can log in my view after the response is returned).
when trying to access requestData I am getting an empty array.
My controller function that is called looks like:
public function index(Request $request)
{
Log::info($request);
//returns array (
//)
//i.e. an empty array
Log::info($request->input);
//returns ""
Log::info($_GET['data']);
//returns error with message 'Undefined index: data '
Log::info(Input::all());
//returns empty array
return Response::json(\App\Comment::get());
}
And I am getting back the response fine.
How can I access the requestData?
Dave's solution in the comments worked:
Changed ajax request to:
request = $.ajax({
url: "/api/comments",
method: "GET",
dataType: "json",
data: {data : requestData}
});
This is how push item in an array using jQuery:
function ApproveUnapproveVisitors(approveUnapprove){
var arrUserIds = [];
$(".visitors-table>tbody>tr").each(function(index, tr){
arrUserIds.push($(this).find('a').attr('data-user-id'));
});
$.ajax({
type:'POST',
url:'/dashboard/whitelistedusers/' + approveUnapprove,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: {data : arrUserIds},
success:function(data){
alert(data.success);
},
error: function(e){
//alert(e.error);
}
});
}
And this is how I access them in my controller
//Approve all visitors
function ApproveAllWhitelistedUsers(Request $request){
$arrToSend = request('data');
foreach ($arrToSend as $visitor) {
$vsitor = User::findOrFail($visitor);
$vsitor->update(['is_approved'=> '1']);
}
return response()->json(['success'=>'Accounts approved successfully!']);
}

How to read json data from AngularJs (front end) to Grails (server side) through $http

I have to send a json data from Angular to Grails through $http service method. The JSON data has been sent to the server. But in server side it doesn't print the param values. I'm new to Grails.
My Code:
Controller:
$(function(){
gateApp.factory('saveCreateToServer', function($http){
return {
saveDataToServer:function(taskCreateFormData){
console.log(taskCreateFormData);
return $http({
method : 'POST',
url : 'save',
data : taskCreateFormData,
})
}
}
});
gateApp.controller('moveTaskRuleDefCtrl', function($scope, saveCreateToServer){
$scope.saveCreate=function() {
var reqData = angular.toJson($scope.taskCreateForm);
saveCreateToServer.saveDataToServer(reqData).success(function(data) {
});
}
});
})
In Server Side:
def save(params){
println "<<<<<<<<<uu<<<<<<<<<"+params
}
When you post data using $http with data key, the data is not sent as query or form data instead it sent using body parameters. So you can not read it with params, just use request.JSON:
def save() {
Map requestData = request.JSON
println "Data: " + requestData
println "Data: " + requestData.firstName
}
Also, you don't have to convert the object to JSON string, you can just pass the data:
$http({
method: "POST",
url: "/save",
data: {firstName: "John", lastName: "Doe"}
});
Update on passing data as form data
Yes, you can absolutely do it so that you don't have to change the server side code. So basically, Angular by default sends data with Content-Type as application/json so the Grails receives it as request.JSON. So just change it to application/x-www-form-urlencoded:
$http({
method: "POST",
url: "/save",
data: {firstName: "John", lastName: "Doe"},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
Now, the params will be available as params in the Grails controller.

AngularJS $http get to ASP.NET Web Api with object in parameters

I'm trying to get filtered data from server using a filtering object I pass to the server side. I have managed to get this working with a post:
angular:
var filter: { includeDeleted: true, foo: bar };
$http({ method: 'post', url: 'api/stuff', data: filter });
web api:
public IEnumerable<StuffResponse> Post([FromBody]Filter filter)
{
return GetData(filter);
}
But i don't want to use a post for this, I want to use a get. But this does not work:
angular
$http({ method: 'get', url: 'api/stuff', params: filter });
web api
public IEnumerable<StuffResponse> Get([FromUri]Filter filter)
{
return GetData(filter);
}
Also tried specifying params: { filter: filter }.
If i try [FromBody] or nothing, filter is null. With the FromUri i get an object at least - but with no data. Any ideas how to solve this, without creating input parameters for all filter properties?
Yes you can send data with Get method by sending them with params option
var data ={
property1:value1,
property2:value2,
property3:value3
};
$http({ method: 'GET', url: 'api/controller/method', params: data });
and you will receive this by using [FromUri] in your api controller method
public IEnumerable<StuffResponse> Get([FromUri]Filter filter)
{
return GetData(filter);
}
and the request url will be like this
http://localhost/api/controller/method?property1=value1&property2=value2&property3=value3
Solved it this way:
Angular:
$http({
url: '/myApiUrl',
method: 'GET',
params: { param1: angular.toJson(myComplexObject, false) }
})
C#:
[HttpGet]
public string Get(string param1)
{
Type1 obj = new JavaScriptSerializer().Deserialize<Type1>(param1);
...
}
A HTTP GET request can't contain data to be posted to the server. What you want is to a a query string to the request. Fortunately angular.http provides an option for it params.
See : http://docs.angularjs.org/api/ng/service/$http#get
you can send object with Get or Post method .
Script
//1.
var order = {
CustomerName: 'MS' };
//2.
var itemDetails = [
{ ItemName: 'Desktop', Quantity: 10, UnitPrice: 45000 },
{ ItemName: 'Laptop', Quantity: 30, UnitPrice: 80000 },
{ ItemName: 'Router', Quantity: 50, UnitPrice: 5000 }
];
//3.
$.ajax({
url: 'http://localhost:32261/api/HotelBooking/List',
type: 'POST',
data: {order: order,itemDetails: itemDetails},
ContentType: 'application/json;utf-8',
datatype: 'json'
}).done(function (resp) {
alert("Successful " + resp);
}).error(function (err) {
alert("Error " + err.status);});
API Code
[Route("api/HotelBooking/List")]
[HttpPost]
public IHttpActionResult PostList(JObject objData)
{ List<ItemDetails > lstItemDetails = new List<ItemDetails >();
dynamic jsonData = objData;
JObject orderJson = jsonData.itemDetails;
return Ok();}

Categories

Resources