Duplicate entires into database while using ajax to insert - laravel

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.

Related

Laravel/Ajax delete function not refreshing my table after success

when I add my function fetchcategory(); in my delete ajax, my table is not refreshing:
$(document).on('click', '.delete_category_btn', function (e) {
e.preventDefault();
var cat_id = $('#delete_cat_id').val();
alert('Category Deleted!');
// location.reload();
$('#deleteCategoryModal').modal('hide');
fetchcategory();
//token taken from laravel documentation
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "DELETE",
url: "/clinical/bbr-category-configuration-delete/"+cat_id,
dataType: "dataType",
});
});
for a reference, my screenshot shows the alert, showing that the delete function follows through:
another reference is that my add function here reloads the page after a new table is added:
$.ajax({
type: "POST",
url: "/clinical/bbr-category-configuration",
data: category_data,
dataType: "json",
success: function (response){
console.log(response);
if(response.status == 400) {
$('#category_formCheck').html("");
$('#category_formCheck').addClass('alert alert-danger');
$.each(response.errors, function (key, err_values) {
$('#category_formCheck').append('<li>'+err_values+'</li>');
});
}
else
{
$('#category_notif').html("");
$('#category_notif').addClass('alert alert-success');
$('#category_notif').text(response.message);
$('#createCategory').modal('hide');
fetchcategory();
}
}
});
another problem of mine is that I tried to add the alert and refresh function inside:
$.ajax({
type: "DELETE",
but they do not show up, so I placed them inside on(click
why is my delete ajax not refreshing my table?
UPDATE:
I am aware of location.reload(); but adding this defeats the purpose.
the data does get deleted, I have to manually refresh the whole page to see the changes though.
You can do it in ajax success. I believe fetchcategory() method is populating data to table
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).on('click', '.delete_category_btn', function (e) {
e.preventDefault();
var cat_id = $('#delete_cat_id').val();
// location.reload();
$('#deleteCategoryModal').modal('hide');
$.ajax({
type: "DELETE",
url: "/clinical/bbr-category-configuration-delete/"+cat_id,
dataType: "dataType",
success: function(data) {
alert('Category Deleted!');
fetchcategory();
},
error: function() {
alert('Error occured');
}
});
});
</script>

Laravel - add to cart ajax issue

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?

when i send data with ajax(jquery) i don't find the values in controller without form in laravel 5.1

This is my blade code:
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function(){
$(window).load(function(){
var topic_id = $("#topic").text();
var post = $("#post").text();
var url_id = "/posts/"+post+"/readStatus";
$("#topic").hide();
var users_id = $("#user").text();
$("#user").hide();
$.ajax({
async:true,
method:"post",
url:url_id,
topic_id:topic_id,
users_id:users_id,
processData: false,
contentType: false,
success:function(response){
console.log(response);
$("#message").html(response);
}
},"json");
});
});
Route::post('/posts/{post_id}/readStatus',function(){
if(Request::ajax()){
//In routes.php
$post = App\Post::find($post_id);
if(auth()->guest())
return "Not user Not read";
else{
$user = App\User::find(auth()->user()->id);
$post->attach($user);
return "Read";
}
//return Response::json(Request::all());
}
});
I get an 500 Internal server error .I found that $post_id in url doesn't hold any value inside.If I give any constant value in $post_id like 1,2... I get the answer.I don't want to use forms to achieve.I gave an ajax call as page loads.
You have to define $post_idas your function argument.
Route::post('/posts/{post_id}/readStatus',function($post_id){
...
});

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

Bind event after login

I have made a filter called auth that check if user is logged. If is not logged it redirect on the main page but if is a call ajax? I just checked if is it. If it is i just send an json status "no-log". Now i received my json response "no-log" on my client and i would like open a modal for ask login and password. The solution that i thougth was put easily for each ajax request an if statement to check if the response status is "no-log" and show the function of modal. BUT OF COURSE is not good for future update, I'm looking for a good solution where i can bind this event and if i want on the future add other status. Any suggest?
Route::filter('auth', function()
{
if (Auth::guest()) {
if ( !Request::ajax() ) {
Session::put('loginRedirect', Request::url());
return Redirect::to('/');
} else {
$status = "no-log";
return json_encode(array('status' => $status));
}
}
});
A example of call ajax
$(document).on("click", ".delete", function() { // delete POST shared
var id_post = $(this);
bootbox.confirm("Are you sure do want delete?", function(result) {
if (result) {
$.ajax({
type: "POST",
url: '/delete_post/' + USER,
data: { id_post: id_post.attr('id') },
beforeSend: function(request) {
return request.setRequestHeader("X-CSRF-Token", $("meta[name='token']").attr('content'));
},
success: function(response) {
if (response.status == "success") {
id_post.parents('div.shared_box').fadeOut();
}
},
error: function(){
alert('error ajax');
}
});
} else {
console.log("close");
}
});
});
After 10 days of exploring an idea I found a way to override ajax comportment:
It just need you replace every $.ajax() by a custom one.
If I re-use your code:
$(document).on("click", ".delete", function() { // delete POST shared
var id_post = $(this);
bootbox.confirm("Are you sure do want delete?", function(result) {
if (result) {
myCustomAjax({ // In place of $.ajax({
type: "POST",
...
Then this custom function allow you to add some action before or after each ajax callback:
For instance checking the JSON return value in order to decide if I trigger the success callback or I show a warning:
function myCustomAjax(options) {
var temporaryVariable = options.success;
options.success = function (data, textStatus, jqXHR) {
// Here you can check jqXHR.responseText which contain your JSON reponse.
// And do whatever you want
// If everithing is OK you can also decide to continue with the previous succeed callback
if (typeof temporaryVariable === 'function')
temporaryVariable(data, textStatus, jqXHR);
};
return $.ajax(options);
}
If you return a 401 for all not loggedin requests, you can use $.ajaxSetup to handle all ajax errors in your application.
$.ajaxSetup({
error: function(jqXHR, exception) {
if (jqXHR.status == 401) {
window.location = 'your-login-page';
}
}
});

Resources