Angularjs $http.post, passing array to PHP - php

I am using a service to update a DB table.
myApp.factory('createGal', function ($http, $q)
{
return {
createGal: function ()
{
var deferred = $q.defer();
var newGalleryArray = {};
newGalleryArray.galleryName = 'New Image Gallery';
newGalleryArray.client = 245;
$http.post('/beta/images/create', {newGalleryArray: newGalleryArray}).success(function(data)
{
console.log(data);
deferred.resolve(data);
});
return deferred.promise;
}
};
});
PHP
public function create()
{
print_r($_POST);
}
The array is returning empty. Am i passing the array incorrectly?
Chrome Dev
Thanks

It's been a while since I've used PHP, but doesn't $_POST just contain request paramaters? $http.post sends data through a JSON payload, not request parameters. So, you'll need to use something like json_decode

Related

How can I send multiple parameter in json response? (Laravel)

I want take multiple values from the database using Ajax, for which I'm using the following code:
public function getParty($party_id){
$party_info = Credits::where('party_id',$party_id)->get();
foreach($party_info as $row)
{
$tariff_type=$row['vehicle_type'];
}
$tariff = Tariff::where('nozzel_type',$tariff_type)->get();
$Party_info=compact($party_info);
$Tariff =compact($tariff);
$data =[$party_info,$tariff];
return response()->json($data);
}
In this code, I'm taking $party_info and $tariff and sending them in response, I found a solution to put both in a new object like I did into $data, to get these values in my view file I use the following code:
if(data){
$.each(data, function(key, value){
var p_amount = value.pending_amount;
var new_tariff = value.price;
document.getElementById('current_amount').value=new_tariff;
document.getElementById('pending_amount').value=p_amount;
});
}
If I send a single parameter through this method, it works, but with multiple parameters, it is notworking
return response()->json(['Party_info'=>$Party_info,'Tariff'=>$Tariff]);

Trying to pass the array data using ajax to php function

Trying to pass the array data using ajax to the PHP function. but getting null value. I am using post method to pass the data.
$(document).on('change','#accordion',function(){
filter = [];
$('input[name^=\'filter\']:checked').each(function(element) {
filter.push(this.value);
});
var params = new window.URLSearchParams(window.location.search);
var search = params.get('search');
$.ajax({
url:"index.php?route=product/search/filtered_data",
method:"POST",
data:{filter:filter},
success:function(data){
console.log("Hitesh"+data);
}
});
});
PHP Code
public function filtered_data(){
$filter = isset($_POST["filter"]);
echo json_encode($filter);
}

store php response in angularjs service, then get them in controller

So, I am new to angularjs. I want to use MVC structure. So, I was thinking that storing the response from php in my service, then use them in my controller.
Service:
(function () {
angular.module('dataService').service("incidentService", function ($http) {
var Data = [];
return ({
getData: __getData
});
function __getData() {
return Data;
}
function __setData($http, $q) {
var defer = $q.defer();
$http.get('PHP/NAME.php',{cache : 'true'}).
success(function(data){
Data = data;
console.log(Data);
defer.resolve(data);
defer.promise.then(function(data){
Data = data;
console.log(Data);
});
});
}
})})();
Controller:
(function () {
angular.module('app')
.controller('Ctrl', Ctrl);
/** #ngInject */
function Ctrl($scope, $http, $q,baConfig, incidentService) {
incidentService.setData($http,$q)
var DataSet = incidentService.getData();
console.log(DataSet);
}
})();
By doing this way, the problem is my dataSet does not get updated when the data array in my service is updated. I know that we can return a defer promise to controller to get the data, but can we set the data first in service, then use get method to use them?
OK, I think the biggest issue with why this doesn't work is because you're assigned the data returned by the $http call to nData rather than just Data.
The next issue is that there's not a getMonthlyData method defined on the service.
That being said, this looks overly complicated.
Your service should look more like this:
(function () {
angular.module('dataService').service("incidentService", function ($http,$q) {
var service
service.getData = __getData()
return service
function __getData() {
if (!service.Data) {
return $http.get('PHP/NAME.php',{cache : 'true'}).then( function(data) {
service.Data = data
return $q.when(service.Data)
})}
else {
return $q.when(service.Data)
}
}
})})();
Then in your controller you just get the data via incidentService.getData()

Save API response to server as JSON file with AngularJS

I'm trying to create an app in AngularJS that aggregates data from multiple APIs. With some public APIs there are request limits and much of the data I want to pull is not updated very frequently, so only one request a month for a particular ID is necessary. To get past this, I've set up a Factory that first checks for a local file on the server, if it is not present, it then goes to the API and performs a GET request.
From there, once the request is complete, I want to save that file to the server with a name set by a field in the response.
I've found some examples using PHP with AngularJS but I'm not sure on how to save the JSON file with the dynamic name...or if this is even the best thing to do in order to avoid the request limits.
var apiUrl = 'https://example.com/api?userID=';
$http.get(apiUrl + $stateParams.userID).
success(function(data) {
$scope.content = data;
$scope.userID = data.userID
function(){
$http.post('saveJson.php', $scope.content).then(function() {
// log success
});
};
}).
error(function() {
// log error
});
PHP
<?php
$json = file_get_contents("php://input");
$file = fopen('/var/www/USERID.json','w+');
fwrite($file, $json);
fclose($file);
?>
If you do this in a service, and just call a method from a view button click, it would be more like this:
angular.module('app.services', [
])
.service('MyService', function ($http) {
var MyService = this;
this.aggregatedData = { content: [], filename: null };
this.apiUrl = 'https://example.com/api?userID=';
this.saveUrl = 'saveJson.php';
this.getData = function (url) {
return $http.get(url + $stateParams.userID).then(function (response) {
MyService.aggregatedData.content.push(response.data);
});
};
this.saveData = function (url, fileName) {
this.aggregatedData.filename = fileName;
return $http.post('saveJson.php', this.aggregatedData).then(function () {
// do something with the post response if desired
});
};
})
Then wire up buttons in your view to fetch and save by having the controller call the service methods.

How to solve error Undefined index in php (laravel)

I am sending arrays from View to Controller using Post Method. This is my code.
Controller: Session::put('isCheck', $isCheck);
this is how i am assigning value to isChecked array.
var isChecked = [
<?php
$isCheck = "";
if (Session::has('isCheck')) {
$isCheck = Session::get('isCheck');
}
foreach ($isCheck as $isCheck) {
$status = $isCheck;
?>
<?php echo $status; ?>,
<?php } ?>
];
View:
$("#target").click(function () {
var postTo = '<?php echo action('sample#postView'); ?>';
var data = {
isChecked: isChecked,
duplicateIsChecked: duplicateIsChecked
};
jQuery.post(postTo, data,
function (data) {
alert(data);
});
});
isChecked and DuplicateIsChecked are my 2arrays.
In controller I am writing this code:
$duplicateIsChecked = $_POST['duplicateIsChecked'];
$isCheck = $_POST['isChecked'];
But i am getting Undefined index duplicateIsChecked error. Help me
Have you checked the header of your Ajax call to make sure its sending any data? In the code you posted, you're assigning variables to the two values in data but you didn't show where you are declaring those variable values.
You can't pass a javascript array to php like that, you have to convert the array into JSON and send it.
so it should be
var data = JSON.stringify({
isChecked: isChecked,
duplicateIsChecked: duplicateIsChecked
});
To get the JSON payload in controller, you can use
$payload = Input::json()->all();
then to access the attribute, you can reference it as
$payload['duplicateIsChecked'] & $payload['isChecked']

Categories