How to execute Laravel controler method by Angular - javascript

Let's say I have an laravel controller that contains one method that parsing value from other sites. On client side I'm using Angular. When user presses button it have to execute this Laravel controller method and value that parsed by this method have to fill an input field in form. Im completely new in angular. So is it possible to execute this laravel method from angular? If it is possible can you give some examples how can I achieve this?

this is just a little example to show how to use $http to transport data. I'm not worked with laravel much.
view.html
<html ng-app = 'myAPP'>
<head>
//include required css or js files
</head>
<body>
<div ng-controller = 'MainCtrl'>
<button ng-click = 'sendData()'>Click me</button>
</div>
</body>
</html>
main.js
angular.module('myAPP').controller('MainCtrl',['$scope','$http','$log',function($scope,$http){
$scope.sendData = function(){
$http.post('url',data).success(function(returnData){});
}
}]);
after http post, from laravel controller it must be catch those data in jason format you either can use it in that format or you can decode it and then use it.

Related

Pass Javascript variable to another page via PHP Post

I am having two php pages:
page 1:
<form class="form-horizontal" role="form" method="post" action="Page2.php">
<button id="place-order" class="btn btn-lg btn-success">Place Order</button>
<div id="ajax-loader" style="display:none;"><img src="images/ajax-loader.gif" /></div>
</form>
<script>
var id = Math.random();
$(document).ready(function() {
$('#place-order').on('click', function() {
$(this).hide();
$('#ajax-loader').show();
});
});
</script>
As on form, it redirects to Page2.php, I want to pass the Javascript variable "id" from Page1 to receive it in Page2.
I have tried using cookies, but need an alternative approach.
I am not understanding the transistion from PHP to JS and vice-versa. Help is appreciated.
Thanks in advance
Dear you can do it very easily with ajax. Ajax has data attribute which helps you pass your data from javascript to another page.
This link will help you a lot
https://api.jquery.com/jquery.ajax/
You can use session storage or cookies.
Example for session storage:
// First web page:
sessionStorage.setItem("myVariable", "myValue");
// Second web page:
var favoriteMovie = sessionStorage.getItem('myVariable');
You could use a query string to pass the value to the next page.
Add an ID to the form
<form class="form-horizontal" role="form" method="post" action="Page2.php" id="order-form">
Update the action of the form to add this query string from our JS variable
var id = Math.random();
$('#order-form').attr('action', 'Page2.php?id=' + id);
Get this variable in PHP (obviously you might wanna do more checks on it)
<? $id = $_GET['id'] ?>
We can now use $id anywhere in our PHP and we'll be using the ID generated from JS. Neat, right? What if we want it in JS again though? Simply add another script tag and echo it there!
<script type="text/javascript">
var id = <? echo $id ?>;
</script>
EDIT: Updated to add a little about how it works as you said you're not too sure about the transition between PHP and JS.
PHP runs on the server. It doesn't know much about the browser, and certainly doesn't know about JS. It runs everything and finishes executing before the web page is displayed. We can pass PHP variables to JS by creating script tags and creating a new javascript variable, echoing the PHP value.
JS (JavaScript) runs in the browser. It doesn't know about anything that happens on the server; all it knows about is the HTML file it is running in (hit CTRL+U to see raw HTML). As JS runs at a completely separate time to PHP there is no easy way to transfer variables (e.g. $phpVar = myJSVar). So, we have to use server methods like POST or GET.
We can create a GET or POST request in 2 main ways:
Using a form
Using an AJAX request
Forms work in the way I've outlined, or you can create a hidden field, set the value you want and then check for that. This involves redirecting to another page.
AJAX (Asynchronous Javascript And Xml) works slightly differently in that the user doesn't have to leave the page for the request to take place. I'll leave it to you to research how to actually program it (jQuery has a nice easy API for it!), but it basically works as a background request - an example would be displaying a loading spinner whilst loading order details from another page.
Hope this helps, let me know if something's not clear!

Angularjs Does not work with Jquery load function

I am creating an web application using ASP.Net MVC5 and AngularJS 1.5, I have a page were data is display from MVC ActionResult and further Edit and Delete operation is perform using AngularJS.
But as I perform edit operation an jsonresult in call from ASP.net MVC controller and perform perfect edit operation with success result, but I also want to refresh the data that is display from MVC ActionResult so I created an partial view and use Jquery load function and pass the URL(MVC ActionResult Url).
The load function refresh the data with current changes in the database but after that AngularJS does not work even AngularJS {{Expressions}} are not working
$http.post('myactionName',{param:param}).success(function (data){
$('#DiV').load("mypartialActionName");
}
<div id="DiV">
#Html.Partial("_PartialViewName")
</div>
first add your jQuery and Angular files, then create the 'app' module
Html
<body configs>
<div id="DiV"> #Html.Partial("_PartialViewName") </div>
</body>
Directive
app.directive("configs", function($http){
return {
link: function(){
$http.post('myactionName',{param:param}).success(function (data){
$('#DiV').load("mypartialActionName");
}
}
}
});
First of all i want to say something if you are using completely AngularJs then do not use #Html.Partial()..use ng-include built in directive instead to inject external template..as of now you are totally depend on MVC that is the bad practice..you have to use MVC for only for server side not Front-end Part and AngularJs uses $http asynchronously you do not have to refresh to to retrieve your data and do not rely on JQUERY..AngularJs can tackle all the things whatever JQUERY did..

Display alert message after page reload

I have to call $route.reload(); in controller 2 addData API call so that I can get the added data in my UI. But then the text 'Data added successfully' goes away due to page refresh.
controller 1:
$rootScope.$on('reloaded', function(event, data) {
$scope.$parent.alerts.length=0;
$scope.$parent.alerts.push({type: 'success',msg: 'Data added successfully'});
});
controller 2:
$scope.add = function() {
someAPIService.addData(JSON.stringify($scope.rows)).success(function(response) {
ngDialog.close('ngdialog1');
$route.reload();
$rootScope.$emit('reloaded', "true");
});
}
HTML Part:
<section>
<div ng-controller="controller3">
<alert ng-repeat="alert in alerts" type="{{alert.type}}" close="closeAlert($index)">{{alert.msg}}</alert>
</div>
<div class="row form-inline" ng-controller="controller2 as vm">
<!-- Table data with text fields-->
</div>
<script type="text/ng-template" id="addDataDialog">
<div id="frm" ng-controller="controller1" class="col-xm-6">
<div class="form-group">
<!-- Labels with text fields-->
</div>
<button class="ngdialog-button" ng-click="add()">Save</button>
</div>
</script>
</section>
NOTE: Both controllers are in the same JS file and they are used for the same HTML file.
As you want to only load the latest record list which is on server side. Then there is not need to use $route.reload(); after making post call. You need to only make ajax call to get the latest records list that will solve your problem. For making ajax you need to refer $http
$route.reload() is getting used only when you need to load
controller again with specified template in your $routeProvider when
condition
just a simple hint of an answer:
add a (specific) cookie (with javascript) before calling reload (use e.g Cookies lib),
read it on reload,
and then delete it
Also you may use local storage if it is available instead of a cookie using same steps:
add a specific entry in local storage, before calling reload
read it on reload
and then delete it
Another option to maintain state client-side is to use url parameters but these will not do for page reload

How to submit AJAX form in grails w/out using a submit button

I have this g:formRemote which submits a form using ajax.
<g:formRemote name="listAll" update="menuItemAJAX" url="[controller: 'superWaiter', action:'menuItem']" onSuccess="additionalContent()">
All
</g:formRemote>
I dont want to use a button since it is easier to style links. It does not work with
<script type="text/javascript">
function myFunction(){
$('#listAll').submit();
};
</script>
Btw, the id of the form is listAll since it gets it from the name attr
Here's a link to a blog post I wrote a couple years ago that contains a sample of each of the Grails Ajax invocations you can make and here's the link to the code on GitHub. There is also an updated version written for Grails 2.x.

How to load a url in html div and post data through http post method?

I have written a html page, and I wrote following code where I am using Jquery to load a specific url inside a html div :
<html>
<head>
<title>forms</title>
<%
String outputLink = ServerSupportUtil.getAttributeStringValue(request,"outputlink");
String secParam = ServerSupportUtil.getAttributeStringValue(request,"secparam");
%>
<script src="../common/jquery-1.6.2.min.js"></script>
<script>
$(document).ready(function(){
$("#menu").html('<object data="<%=outputlink%>">').appendTo('body');;
});
</script>
</head>
<body>
<div id="menu" style="position:relative; bottom: 0; overflow:hidden;">
</div>
</body>
</html>
Above code is working good.
Now I also want to send a specific parameter named as secParam(which I get from request object) through http post along with this url so that server can do authentication.
So how should I load the same url in the div by doing http post request?
Is this possible using Jquery ?
First create an simple container to display whats retuned. Then use jquery $.post() method :
//Empty container div
<div id="container"></div>
$.post('ajax/test.html', { secParam: "<%=secParam%>" }, function(data) {
$('#container').html(data);
});
I would recommend you not to use jsp scriptlets if that's what i see here.
String outputLink = ServerSupportUtil.getAttributeStringValue(request,"outputlink");
You have used a request method to request data(page) from server, so if you want to post the parameter to server used post method,you should change request to post, maybe cannot use the code above, you should create a html form and save your parameter in a hidden, and set the form action as the outputlink you request, you can get the parameter from the httpRequest.

Categories