I want to call a php method using angular service. I do this :
save:function(){
var req = {
method: "GET",
url: "/api/save/",
data: {
nom:"nom"
}
}
var deferred = $q.defer();
$http(req).
success(function(result) {
console.log(req);
deferred.resolve(result);
})
and in my php controller :
public function savePersonnelAction(Request $httpRequest){
$content= $httpRequest->query->get('data');
return $this->render('clientBundle:Default:index.html.twig',array('content'=>$content));
}
But I have an empty object as a result.
Can someone help me to resolve this problem please
Do you only want to send some data in a query string?
For a GET request, you should use params, not data attribute.
data is used for a POST request content.
Try like this:
$content= $httpRequest->query->get('nom');
Cheers
Related
I'm new at Laravel and I'm actively trying to code better, but I'm currently stuck with problems I don't know how to solve.
The controller :
public function sendGiving($contents){
$redirectURL = $contents->redirectURL;
var_dump($redirectURL); // the variable is available, logged in network section
return View::make('giving/giving')->with('redirectURL', $redirectURL);
}
The view (on AJAX) :
function submitForm() {
if (is_personal_data_complete() == true && is_offering_filled() == true && isreCaptchaChecked() == true) {
var base_url = window.location.origin;
//send ajax request
$.post("{{ route('send_giving') }}",
{
_method: 'POST',
_token: '{{ csrf_token() }}',
name: $('#txtName').val(),
email: $('#txtEmail').val(),
phone_number: $('#txtnohp').val(),
thanksgiving_offerings: total_thanksgiving,
tithe_offerings: total_tithe,
firstborn_offerings: total_firstborn,
build_offerings: total_build,
deacon_offerings: total_deacon,
mission_offerings: total_mission,
paud_offerings: total_paud,
dataType: "jsonp",
async : false,
success: function($redirectURL){
alert($redirectURL);
},
});
}
else if (is_personal_data_complete() == false) {
alert("Please fill in your data form");
}
else if (is_offering_filled() == false) {
alert("Please fill in your offerings");
}
else if (isreCaptchaChecked() == false){
alert("Please check the captcha");
}
return false;
}
The alert always returns undefined though, what am I missing?
Please try this:
return response()->json($redirectURL)
When you use Laravel and write API, you need to use this command to reponse JSON for frontend
The view() function just creates an instance of the View class. Not just an HTML string. For that you should call render():
$returnHTML = view('giving/giving')->with('redirectURL', $redirectURL)->render();
return response()->json(array('success' => true, 'html'=>$returnHTML));
When you return in your controller return View::make('giving/giving')->with('redirectURL', $redirectURL);
You are returning a VIEW file, which will be return as the body of the HTTP request.
and you are also passing to Your view file redirectUrl which will be accessible in your view file.
And when you perform your AJAX request, you are getting a response with a body which contain HTML/TEXT Content not JSON.
SO YOU CAN'T HAVE ACCESS TO redirectURL VARIABLE
So what you should do by the way is to return simple a JSON body by returning in your Controller something like
return response()->json([
'redirectURL' => $redirectURL
]);
No need to return a VIEW FILE
You can't return in the same controller JSON data in the body and a VIEW FILE
The main issue is here that you try to send a POST with JSONP data type.
There are a lot of explanations on this on SO, e.g https://stackoverflow.com/a/18934048/8574551
Try to remove it and use smth like the next:
...
contentType: "application/json",
dataType: "json",
...
On another hand, you can omit these 2 parameters (check https://api.jquery.com/jquery.post/)
To return the data from the controller action you can use response()->json(..) (as described in other answers)
the problem is on the ajax request, as after changing the format it works nicely
I want to create an autocomplete with Angular and since this is my first contact with angular, I`m pretty stucked.
Here is my code:
MenuService.getAutocompleteData(term).then(function (response) {
$scope.menuData = response.data;
});
This is how I call a service that is making the following http call:
return $http({
url : autocompletePath,
method : "POST",
data : {
term: term
}
}).success(function (response) {
return response;
});
The problem is that it seems that is syncronously and my browser freezes when I type fast letters. I saw that it is about that ".then" promise, but I`m not sure how to fix it. Any help would be appreciated.
You do a HTTP-request, which is correct, but you try to return the result on success. Instead you should try to do what needs to be done in your success-handler.
So in your service you would do something like this:
return $http({
url : autocompletePath,
method : "POST",
data : {
term: term
}
}); //note that there is no success handler in your service, because what's supposed to happen when the request completes, is the controller's business, not the service's. The service should only know where to get the data
And you would change your controller to this:
MenuService.getAutocompleteData(term).success(function (response) {
$scope.menuData = response.data;
}); //note the success-handler
Why dont you give this a try?
https://angular-ui.github.io/bootstrap/#/typeahead
Below I've got a function that should make a post to the server.
var updateApplicationMetadata = function(appId, editorVersion, previewPubFile){
var deferred = $q.defer();
var result = $http({
method: 'post',
url: '../resource/applications/'+appId,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: {
editorVersion: editorVersion,
previewPubFile: previewPubFile
}
});
result.then(function(data){
deferred.result(data);
console.log('from services: ');
console.log(data);
});
return deferred.promise;
};
I call this function like:
$scope.update = function(){
MessageBus.emitMsg('notification','Application updates successful.');
console.log('from update: ');
console.log($scope.application.appId);
console.log($scope.application.editorVersion);
console.log($scope.application.previewPubFile);
DataContext.updateApplicationMetaData($scope.application.appId,$scope.application.editorVersion ,$scope.application.previewPubFile);
};
All of the values sent to the updateApplicationMetaData are valid. I can use the rest client POST man and I can make the post work. When I do it in angular, however, I get a bad request. The URL and header content type are right, but I'm not sure about the data object. It must be malformed. What am I missing here?
You've got an error in your code. You have:
deferred.result(data);
and it should be:
deferred.resolve(data);
for it to work. Also, you need to pass 'application/json' as your accepts type for your data to work.
Assuming you are using the $q service from https://docs.angularjs.org/api/ng/service/$q I don't see a result method. Perhaps change:
deferred.result(data);
To
deferred.resolve(data);
consider using ngResource for rest style json requests
Angular resource docs
I am building an ASP.NET MVC application It currently has a button that once clicked does an Ajax call to the controller as so:
function getData() {
$.ajax({
url: "/Home/GetData/",
type: "POST",
contentType: 'application/json',
success: function (data){
//need to do stuff here
}
});
}
The controller then initializes a class, converts it to XML and then converts that to the following dictionary (There is a reason for this):
public ActionResult GetData()
{
List<People> peeps = GetPeeps();
string xml = ToXml(peeps);
Dictionary<string,List<string>> stuff = ToDictionary(xml);
return Json(stuff);
}
I would like to be able to 'Do stuff' with this data client side with javascript.
The APIs I have to work with Server side return XML data.
The APIs I have to work with Client side require string arrays. (Hence the conversions)
Is there a way to use the dictionary i've defined above client side? Could someone perhaps expand from this (if possible) to add to the ajax call a small method that prints the contents of the dictionary to a message box? just to give me a starting point from how to use the dictionary in javascript.
Thanks in advance
You can try in the ajax call as follow:
function getData() {
$.ajax({
url: "/Home/GetData/",
type: "POST",
contentType: 'application/json',
success: function (data){
console.log(data.key1); // value for key1
//or to list all values
for(var key in data){
console.log(data[key]);
}
}
});
}
Controller (for explanation purposes):
public ActionResult GetData()
{
//List<People> peeps = GetPeeps();
//string xml = ToXml(peeps);
//Dictionary<string,List<string>> stuff = ToDictionary(xml);
Dictionary<string,List<string>> stuff = new Dictionary<string, List<string>>
{
{"key1", new List<string> {"a", "b", "c"}},
{"key2", new List<string> {"d", "e", "f"}},
};
return Json(stuff);
}
I hope this is clear enough. Let me know how you go :)
I want to pass a javascript array to a php page using ajax POST request .How to achieve this.please help..Thanks in advance
Have a look into JSON encoding.
In PHP you can decode it using json_decode, not quite sure how you'll encode it in Javascript but it is possible
http://en.wikipedia.org/wiki/JSON
using jQuery
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
Edit
if you are creating ajax object and using it then I'll suggest to convert your data in query string send it through ajax object.
like :
var userdetails = [1,2,3,4];
var queryString = "";
for(i=0; i<userdetails.length; i++){
queryString = queryString + 'userdetails[]='+userdetails[i]+'&';
}
connect.send(queryString)
example posting with json
var array = [1,2,3,4,5,6];
$.ajax({
url: "mydomain.com/url",
type: "POST",
dataType: "json",
data: {arrayName: array},
complete: function() {
//called when complete
},
success: function() {
//called when successful
},
error: function() {
//called when there is an error
},
});
Then the json could be parsed server side.
arrays can also be sent using application/x-www-form-urlencoded - this is the default format for submitting.