javascript - jquery-ajax pass html element value from one page to another
Solution:
There are multiple ways of passing data between your pages :
- Use params in routes.
Since you are already using $routeProvider, there's no need to navigate using window.location.href,
you can use $location.path.
app.config(($routeProvider)=>{
$routeProvider
.when("/" , {templateUrl:"main.php"})
.when("/login" , {templateUrl : "login.php"})
.when("/register" , {templateUrl : "register.php"})
.when("/results" , {templateUrl : "showResults.php"})
.when("/purchase/:cost", {templateUrl:"purchase.php"}) //add the cost as the route param.
.when("/cart" ,{templateUrl:"products.php"});
});
Now, when routing to your purchase page:
$location.path('/purchase/'+cost);
In your purchase controller, inject $routeParams and access the cost as:
app.controller('purchaseController', function($scope,$routeParams) {
$scoope.totalCost = $routeParams.cost;
});
You can use services where you can set the value of cost in one controller and access it in another.
var app = angular.module('yourModule',[]); app.service("dataService",function(){ var totalCost = ""; setCost: function(cost){ totalCost = cost; }, getCost: function(){ return totalCost; } });
In your product controller, inject dataService and use the setCost Method.
app.controller('productsController', function($scope, dataService) {
dataService.setCost(totalCost);
});
Next, in your PurchaseController, access the value:
app.controller('purchaseController', function($scope, dataService) {
$scope.totalCost = dataService.getCost();
});
Answer
Solution:
This is what I did to make this work using localstorage and ajax :
//-----Checkout------
$("#checkOut").click(()=>{
//get count of products
var numOfProducts = $('.product-columns').length;
var subtotal = parseInt($('#fullSubTotal').text().replace('$',''));
var shipping = parseInt(localStorage.getItem('shipping').replace('$',''));
localStorage.setItem('subtotal', $('#fullSubTotal').text());
var sum = shipping +subtotal;
var total = `$` + `${sum}`;
if(numOfProducts!=0){
//pass total cost
$.ajax({
type:'POST',
data:{totalPurchase:total},
success:()=>{
window.location.href='../php/index.php#!/purchase';
$("#totalOnPurchase").html(`Total: `+`${total}`);
}
});
}else{
alert("Your cart is empty");
}
});
Source