Laravel - add to cart ajax issue - ajax

guys when I try to add item to EMPTY(empty session) cart asynchronously it doesn't work. But if I refresh the item appears in cart and from there I can add items asynchronously. What am I missing?
controller function:
public function addToBasket(Request $request, $id)
{
$newBasket = new Basket($previousBasket);
$newBasket->addProduct($product, $product->id);
Session::put('basket', $newBasket);
return response()->json(['added' => Session::get('basket')->quantity], 200);
}
ajax:
var id = $(this).data('id');
var url = "/product/add-to-basket/"
$.ajax({
type: "GET",
url: url+id,
dataType: "json",
data: { id: id },
success: function(data) {
if(data) {
$('#counter').html(data['added']);
console.log(data);
}
It's because the session[basket] variable isn't initialised for the first request. but how do I resolve it?

Related

Passing ID to Controller using Ajax - Error 404 in Laravel

I am new to Laravel.
Trying to Pass ID from View to Controller but getting Error
POST http://127.0.0.1:8000/getbuffaloidformonitor 404 (Not Found)
This is my View BuffaloMonitor :
$(document).on('click', '.viewmonitormodal', function() {
var modal_data = $(this).data('info').split(',');
$('#viewbuffaloID').val(modal_data[1]);
var buffaloid = document.getElementById('viewbuffaloID').value// get buffalo id from textbox to get data for that ID
alert(buffaloid);
//alert(data);
$(function() {
$.ajax({
method : "POST",
url: "/getbuffaloidformonitor",
data: {
'_token': $('input[name=_token]').val(),
'id': buffaloid,
},
success : function(response) {
alert(response);
}
});
});
}
This is BuffalomonitorCOntroller :
public function getbuffaloidformonitor(Request $req) {
$data = buffalodata::find($req->id);
alert(data);
$id = $req('data');
return $id;
}
This Is Route
Route::post('/getbuffaloidformonitor/{id}','App\Http\Controllers\BuffalomonitorController#getbuffaloidformonitor')->name('getbuffaloidformonitor');
Your post route has {id} but it's not necessary. This is what you need Route::post('/getbuffaloidformonitor','App\Http\Controllers\BuffalomonitorController#getbuffaloidformonitor')->name('getbuffaloidformonitor');
pass id to the link http://127.0.0.1:8000/getbuffaloidformonitor
as you write the route
Route::post('/getbuffaloidformonitor/{id}','App\Http\Controllers\BuffalomonitorController#getbuffaloidformonitor')->name('getbuffaloidformonitor');
You are just pass id by routes Params, so the URL must like this
http://127.0.0.1:8000/getbuffaloidformonitor/yourbuffaloid
You need to change URL.
$.ajax({
method : "POST",
url: "/getbuffaloidformonitor/" + buffaloid,
data: {
'_token': $('input[name=_token]').val(),
//'id': buffaloid, remove this line
},
success : function(response) {
alert(response);
}
});
If you use this script in you blade template just use
const url = '{{ route("getbuffaloidformonitor",":id") }}'
$.ajax({
method : "POST",
url: url.replace(':id',buffaloid),
data: {
'_token': $('input[name=_token]').val(),
//'id': buffaloid, remove this line
},
success : function(response) {
alert(response);
}
});
If your routes {id} is optional just
Route::post('/getbuffaloidformonitor/{id?}','App\Http\Controllers\BuffalomonitorController#getbuffaloidformonitor')->name('getbuffaloidformonitor');
with question on your id route you can use both by pass id by route params or you can pass id by data post.
In controller
public function getbuffaloidformonitor(Request $req, $id = null)
{
// id is get from route params
$getId = $req->get('id') // this one get from data post.
}

Duplicate entires into database while using ajax to insert

I am trying to user ajax to insert into the database for my laravel project but each time i insert i see duplicates of every item with a unique id.
Inserting normally with the form itself, this behavior doesn't repeat.
My ajax code s below.
`$('#saveCat').on('click', function (e) {
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var url = '/admin/storecat';
var type = "post";
var data = {spec: $('#cat').val() };
$.ajax({
type: type,
url: url,
data: data,
dataType: 'json',
success: function (data) {
console.log(data);
$('#catform').trigger('reset');
//show success alert msg
$('#alert-suc').html(data);
$('#ac-alert').show('slow', function () {
setTimeout(function () {
$('#ac-alert').hide('slow');
}, 3000);
});
},
error: function (data) {
console.log('Error:', data);
}
});
});
My controller action here
public function storeCat(Request $request) {
$Category = new Category;
$Category->name = $request->spec;
$Category->save();
return response()->json('New service category ' . $request->spec . ' has been added.');
}
try to use:
e.stopImmediatePropagation();
stopImmediatePropagation will prevent any parent handlers and also any other handlers from executing.

Render partial view with AJAX-call to MVC-action

I have this AJAX in my code:
$(".dogname").click(function () {
var id = $(this).attr("data-id");
alert(id);
$.ajax({
url: '/Home/GetSingleDog',
dataType: 'html',
data: {
dogid: id,
},
success: function (data) {
$('#hidden').html(data);
}
});
});
The alert gets triggered with the correct value but the AJAX-call does not start(the method does not get called).
Here is the method that im trying to hit:
public ActionResult GetSingleDog(int dogid)
{
var model = _ef.SingleDog(dogid);
if (Request.IsAjaxRequest())
{
return PartialView("_dogpartial", model);
}
else
{
return null;
}
}
Can someone see what i am missing? Thanks!
do you know what error does this ajax call throws?
Use fiddler or some other tool to verify response from the server.
try modifying your ajax call as following
$.ajax({
url: '/Home/GetSingleDog',
dataType: 'string',
data: {
dogid: id,
},
success: function (data) {
$('#hidden').html(data);
}
error: function(x,h,r)
{
//Verify error
}
});
Also try
$.get("Home/GetSingleDog",{dogid : id},function(data){
$('#hidden').html(data);
});
Make sure, URL is correct and parameter dogid(case sensitive) is same as in controller's action method

Unable to receive json data in controller with knockout

I am new with knockout and mvc, so I need some help, my question is
my dropdown list is populating successfully from server, and on clicking save button calls Save method in controller. But problem is that in controller I am unable to receive json data i.e it is null. here is my code in view
var initialData = #Html.Raw( new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model));
var viewModel = function(){
var self = this;
self.HomeAgencies = ko.observableArray(initialData.HomeAgencies);
self.selectedOrgUnit = ko.observable();
self.Save = function () {
$.ajax({
url: "#Url.Action("Save")",
type: "POST",
data: ko.toJSON(this),
contentType: "application/json; charset=utf-8",
dataType:"json",
success: function(result) {alert(result.message)}
});
}
}
var vm = new viewModel();
ko.applyBindings(vm);
Where in controller i have following code
public JsonResult Save(string someData)
{
var message = string.Format("Saved {0} ", "successfully");
return Json(new { message });
}
string someData is always null, where I am expecting some json data.
Try to replace this to self in data and introduce field name and remove contentType.
$.ajax({
url: '#Url.Action("Save")',
type: 'POST',
data: { someData: ko.toJSON(self) },
dataType: 'json',
success: function (result) { alert(result.message); }
});
In your case context of the method can be changed from your object to html element that invoked them method or to window.
issue resolved. Problem was at controller side, in Action of controller pass the same model class instead parsing json manually.

Use Ajax and JsonResult in ASP.NET MVC 3

I need to get string array or list with ajax and Action, this is my Implementation:
This is my html Dom of view of Index action in AccessMenuController:
<div class="RoleAccess">
<select name="RoleDropDown">
<option value="0">Select Role</option>
<option value="61AD3FD9-C080-4BB1-8012-2A25309B0AAF">AdminRole</option>
<option value="8A330699-57E1-4FDB-8C8E-99FFDE299AC5">Role2</option>
<option value="004E39C2-4FFC-4353-A06E-30AC887619EF">Role3</option>
</select>
</div>
My Controller:
namespace MyProject.Areas.GlobalAccess.Controllers {
public class AccessMenuController : Controller {
public ActionResult Index() { return View();}
[HttpPost]
public JsonResult RoleDropDownChanged(string roleId) {
Guid RoleId = new Guid(roleId);
//Some implement
List<string> actions = new List<string>();
for(int i = 0; i <= 10; i++)
actions.Add(i.ToString());
return Json(actions.ToArray(), JsonRequestBehavior.AllowGet);
}
}
}
and the script:
$(document).ready(function () {
//Handle Checks of Actions by RoleName Changed
$('div.RoleAccess select').change(function () {
RoleChangeHandler();
});
function RoleChangeHandler() {
$.ajax({
url: '#Url.Action("RoleDropDownChanged")',
type: 'POST',
data: { 'roleId': '61AD3FD9-C080-4BB1-8012-2A25309B0AAF' },
dataType: 'json',
processData: false,
contentType: 'application/json; charset=utf-8',
success: function (data) { SuccessRoleChangeHandler(data); },
error: OnFailRoleChangeHandler
});
return false;
}
function SuccessRoleChangeHandler(data) {
alert("in success role change");
}
function OnFailRoleChangeHandler(result) {
alert('in OnFailRoleChangeHandler');
}
And the problem is with all change of dropdown just Onfail function run and alert me "in OnFailRoleChangeHandler", also I check the RoleDropDownChanged Action with breakpoint and that never run, where is the problem?
UPDATE
when I load the page by chrome there is an error in console window:
http://MyProject/GlobalAccess/AccessMenu/#Url.Action(%22RoleDropDownChanged%22) 404 (Not Found) jquery-1.7.1.js:8102
Remove this setting:
contentType: 'application/json; charset=utf-8',
You are not sending any JSON to the server.
If you want to keep this setting then make sure that you are sending a valid JSON to your server:
data: JSON.stringify({ 'roleId': '61AD3FD9-C080-4BB1-8012-2A25309B0AAF' })
So:
$.ajax({
url: '#Url.Action("RoleDropDownChanged")',
type: 'POST',
data: { 'roleId': '61AD3FD9-C080-4BB1-8012-2A25309B0AAF' },
success: SuccessRoleChangeHandler,
error: OnFailRoleChangeHandler
});
should work (at least it does for me) with the following action:
[HttpPost]
public ActionResult RoleDropDownChanged(Guid roleId)
{
var actions = Enumerable.Range(1, 10).Select(x => x.ToString()).ToList();
return Json(actions);
}
UPDATE:
According to your comments it looks like you are trying to use server side helpers in a separate javascript which is not possible. Here's what I would suggest you. Start by providing the url when generating your dropdown:
<div class="RoleAccess">
#Html.DropDownListFor(
x => x.RoleDropDown,
Model.Roles,
"-- Select role --",
new {
data_url = Url.Action("RoleDropDownChanged")
}
)
</div>
and then in your separate javascript file:
$(document).ready(function() {
$('div.RoleAccess select').change(function () {
var url = $(this).data('url');
$.ajax({
url: url,
type: 'POST',
data: { 'roleId': '61AD3FD9-C080-4BB1-8012-2A25309B0AAF' },
success: function(result) {
alert('success');
},
error: function() {
alert('error');
}
});
});
});
and then of course you could replace the hardcoded roleId with the currently selected value:
data: { 'roleId': $(this).val() }
Move your $(document).ready function to your View like this:
<script type="text/javascript">
$(document).ready(function () {
//Handle Checks of Actions by RoleName Changed
$('div.RoleAccess select').change(function () {
RoleChangeHandler('#Url.Action("RoleDropDownChanged")');
});
});
</script>
Then in your JS file add url parameter to your function and change ajax call:
function RoleChangeHandler(pageUrl) {
$.ajax({
url: pageUrl,
type: 'POST',
data: { 'roleId': '61AD3FD9-C080-4BB1-8012-2A25309B0AAF' },
dataType: 'json',
processData: false,
contentType: 'application/json; charset=utf-8',
success: function (data) { SuccessRoleChangeHandler(data); },
error: OnFailRoleChangeHandler
});
return false;
}
This should work as you expected.
If your script resides in a .JS file then this is not going to work as it'll be treated as plain text. You can either move entire script to the view or you can re-factor script so that majority of the script remains in the .JS and you then pass relevant values from the view.

Resources