Snippets Collections
$.ajax({
  url: ajaxurl,
  type: 'get',
  data: {
    action: 'php_function_name',
    search_term: SEARCH_ME
  },
  success: function(res) {
    var json = $.parseJSON(res);
    console.log(json);
    if (json.status === 0) {
      response([{ label: "No data found" }]);
    } else {
      response(json.data);
    }
  }
});
async function turnierplan_mit_helfer_teilen() {
  var url_string = window.location.href;
  var url = new URL(url_string);
  var pw = url.searchParams.get("pw");
  var turnier_id = url.searchParams.get("turnier_id");
  
  let turnier = await read_turnier_details(turnier_id, "*", "*");
  ...
}
  
async function read_turnier_details(turnier_id, runde, gruppe){
    var base_url = window.location.origin;
    if( base_url.includes("https://localhost") ){
        base_url = "https://localhost/mytman-repo";
    }
    return jQuery.ajax({
        type: "POST",
        dataType: "json",
        url: base_url + "/app/api/read_turnier_details",
        data: {
            turnier_id: turnier_id,
            runde: runde,
            gruppe: gruppe
        },
        success: function(response){
        }
    });
}
In terminal excute the following command
1. composer require hardevine/shoppingcart
Then in app.php in config folder write the following code in providers array
Gloudemans\Shoppingcart\ShoppingcartServiceProvider::class,
 and in aliases array
 'Cart' => Gloudemans\Shoppingcart\Facades\Cart::class,
2. Now in terminal execute the following command
php artisan vendor:publish --provider="Gloudemans\Shoppingcart\ShoppingcartServiceProvider" --tag="config"
3. Now in ShopComponent class file at head write the following
use Cart;
then in ShopComponent write the following function
 public function store($product_id, $product_name, $product_price)
    {
        Cart::add($product_id, $product_name, 1, $product_price)->associate('\App\Models\Product');
        session()->flash('success_message', 'Items added in Cart');
        return redirect()->route('cart.index');
    }
4. Now in shopcomponent blade file, in Add To Cart a link add the following code wire code
 
<a aria-label="Add To Cart" class="action-btn hover-up" href="#" wire:click.prevent="store('{{$product->id}}', '{{$product->name}}', '{{$product->regular_price}}')"><i class="fi-rs-shopping-bag-add"></i></a>
5. Now in cart-component blade file 
in the table after <tbody> start write the following code
 @if (Cart::count()>0)
    <tr>
     <td class="image product-thumbnail"><img src="{{asset('assets/imgs/shop/product-1-2.jpg')}}" alt="#">
       </td>
     <td class="product-des product-name">
       <h5 class="product-name"><a href="product-details.html">J.Crew Mercantile Women's Short-Sleeve</a></h5>
       <p class="font-xs">Maboriosam in a tonto nesciung eget<br> distingy magndapibus </p>
      </td>
        <td class="price" data-title="Price"><span>$65.00 </span>
      </td>
      <td class="text-center" data-title="Stock">
        <div class="detail-qty border radius  m-auto">
         <a href="#" class="qty-down"><i class="fi-rs-angle-small-down"></i></a>
          <span class="qty-val">1</span>
         <a href="#" class="qty-up"><i class="fi-rs-angle-small-up"></i></a>
        </div>
      </td>
        
	  <td class="text-right" data-title="Cart">
         <span>$65.00 </span>
           </td>
           <td class="action" data-title="Remove"><a href="#" class="text-muted"><i class="fi-rs-trash"></i></a></td>
           </tr>
          @else
           <p>No Item In Cart</p>
         @endif

6. Now use following items to show cart items
  @foreach (Cart::content() as $item)
	<tr>
     <td class="image product-thumbnail"><img src="{{asset('assets/imgs/shop/product-')}}{{$item->model->id}}-1.jpg" alt="#"></td>
      <td class="product-des product-name">
       <h5 class="product-name"><a href="product-details.html">{{$item->model->name}}</a></h5>
      </td>
       <td class="price" data-title="Price"><span>${{$item->model->regular_price}} </span></td>
         <td class="text-center" data-title="Stock">
           <div class="detail-qty border radius  m-auto">
            <a href="#" class="qty-down"><i class="fi-rs-angle-small-down"></i></a>
            <span class="qty-val">1</span>
           <a href="#" class="qty-up"><i class="fi-rs-angle-small-up"></i></a>
         </div>
         </td>
        <td class="text-right" data-title="Cart">
         <span>${{$item->subtotal}} </span>
        </td>
         <td class="action" data-title="Remove"><a href="#" class="text-muted"><i class="fi-rs-trash"></i></a></td>
          </tr>
@endforeach
7. Now in cart totals
 <div class="table-responsive">
   <table class="table">
   <tbody>
      <tr>
       <td class="cart_total_label">Cart Subtotal</td>
       <td class="cart_total_amount"><span class="font-lg fw-900 text-brand">${{Cart::subtotal()}}</span></td>
      </tr>
      <tr>
       <td class="cart_total_label">Tax</td>
        <td class="cart_total_amount"><span class="font-lg fw-900 text-brand">${{Cart::tax()}}</span></td>
       </tr>
        <tr>
       <td class="cart_total_label">Shipping</td>
       <td class="cart_total_amount"> <i class="ti-gift mr-5"></i> Free Shipping</td>
       </tr>
        <tr>
 <td class="cart_total_label">Total</td>
 <td class="cart_total_amount"><strong><span class="font-xl fw-900 text-brand">${{Cart::total()}}</span></strong></td>
  </tr>
 </tbody>
 </table>
 </div>
after  @foreach ($products as $product)
	@endforeach
use:

{{$products->onEachSide(1)->links('pagination::bootstrap-4')}}
use Livewire\withPagination;
then in component main function write
 use withPagination;
    public function render()
    {
        $products = Product::paginate(12);
        return view('livewire.shop-component', compact('products'));
    }
3. You can pic images from asset folders in blade file by using the following code
<img class="default-img" src="{{asset('assets/imgs/shop/product-')}}{{$product->id}}-1.jpg" alt="">
<img class="hover-img" src="{{asset('assets/imgs/shop/product-')}}{{$product->id}}-2.jpg" alt="">
1. First make a factory by using the following code 
php artisan make:factory CategoryFactory -model=Category
2. Go to the CategogyFatory file in factories folder and write the following code
 $category_name = $this->faker->unique()->words($nb=2, $asText = true);
        $slug = Str::slug($category_name, '-');
        return [
            'name' => $category_name,
            'slug' => $slug
        ];
3. You can use Str class as on top
  use Illuminate\Support\Str;
4. Now go to the DatabaseSeeder and write the following code in the run function
 \App\Models\Category::factory(6)->create();
5. use the following command
php artisan db:seed
6. You can make as many factories and call in the databaseseeder file and use the factories
Thanks!
1. git reset HEAD --hard
2. git clean -fdx
3. git status
4. git pull
rename the app.blade.php file if exists for temporary
1. composer require laravel/breeze --dev
2. php artisan breeze:install
Delete the new built app.blade.php file and change the name of the file file in step 1 to again app.blade.php
Now add the following code in users file migration after password
  $table->string('utype')->default('USR')->comment('ADM for admin and USR for User');
3. now run php artisan migrate
4. npm install
5. npm run build
6. Now we can change or use login/logout/Register routes routes available 

 @auth
    <ul>                                
      <li><i class="fi-rs-key"></i>  {{Auth::user()->name}}  / 
        <form method="POST" action="{{route('logout')}}">
          @csrf
          <a href="{{route('logout')}}" onclick="event.preventDefault(); 			    					this.closest('form').submit();">Logout</a>
        </form>
       </li>
    </ul>
 @else
     <ul>                                
       <li><i class="fi-rs-key"></i>
		  <a href="{{route('login')}}">Log In </a>  / <a href="{{route('register')}}">Sign Up</a>		</li>
     </ul>
 @endif

7. the make middleware for that
php artisan make:middleware AdminMiddleware
8. then open the the middle file in http/middleware
9. now add the following code inhandle function

if (Auth::user()->utype === 'ADM') {
   return $next($request);
 }
 else{
 session()->flush();
 return redirect()->route('login');
 }
10. Use the following code in the header of middleware file to use auth
use Illuminate\Support\Facades\Auth;
11. Now open kernel.php file in http folder and add the following code in routemiddleware
'authadmin' => \App\Http\Middleware\AdminMiddleware::class,
  12. Now open the file routeservice provider in providers folder and delete the dashboard word in the line no 20 HOME
13. Now make two componnts use the following commands
php artisan make:livewire Admin/AdminDashboardComponent
php artisan make:livewire User/UserDashboardComponent
14. Now use the following code in web.php to use middleware in your project
Route::middleware(['auth'])->group(function(){
    Route::get('/user/dashboard', UserDashboardComponent::class)->name('user.dashboard');
});

Route::middleware(['auth', 'authadmin'])->group(function(){
    Route::get('/admin/dashboard', AdminDashboardComponent::class)->name('admin.dashboard');
});
1. first of all install livewire
composer require livewire/livewire
2. make livewire component
php artisan make:livewire HomeComponent
3. Make a folder in views named with layouts
4. then make file app.blade.php
5. Then write {{$slot}} where you want to render your livewire component
6. then write this code right before closing of head tag
  @livewireStyles
6. then write this code right before closing of head tag
  @livewireStyles
7. then write this code right before closing of body tag
  @livewireScripts
In laravel 9:
Command No 1 in controller:
return redirect()->route('category.index')->with('success', 'Record Entered Successfully');

then in blade
 @if (Session::has('success'))
      <div class="alert alert-success">
        {{Session::get('success')}}
      </div>
@endif
1. add the following code in laravel migrations to set foreign key
$table->unsignedBigInteger('customer_id');
$table->foreign('customer_id')->references('id')->on('customers');
or if you want to delete the foreign id data also
$table->foreign('customer_id')->references('id')->on('customers')->onDelete('cascade');
here 'customers' is the table of id here we are considering as foreign id
2. Now in the customer model as the following function
public function orders(){
        return $this->hasMany(Order::class, 'customer_id');
    }
3. In the order model add the following function
public function customer(){
        return $this->belongsTo(Customer::class, 'customer_id', 'id');
    }
1. Go to official link
https://spatie.be/docs/laravel-backup/v8/installation-and-setup
of spatie-backup and copy and run the following command [composer require spatie/laravel-backup]
2. Then copy and run the following command from the same link
[php artisan vendor:publish --provider="Spatie\Backup\BackupServiceProvider"]
3. Now you can include or exclude any file from backup in the config/backup.php file
4. Now in database.php file go to 'mysql' code group and add the following line of code after 'engine' => null,
  the code to add::
   'dump' => [
                'dump_binary_path' => 'C:/xampp/mysql/bin/',
            ],
5. Now in terminal run the following command [php artisan backup:run]
6. Now check the storage folder for your backup zipped file
7. Enjoy backup thanks
1. First install laravel as usual
2. the cd/enter to your project
3. now run the command [npm i vue@next vue-loader@next] to install vue into your project
4. now install vue plugin run the command [npm i @vitejs/plugin-vue]
5. if it came npm errors the youcan install specified version of vitreplugin by typing
e.g[npm i @vitejs/plugin-vue@3.0.x]
6. now open vite.config.js file and add some code as follows
add this line at headings import vue from "@vitejs/plugin-vue";
7. then put a coma after laravel code and add the following code 
vue({
            template: {
                transformAssetUrls: {
                    base: null,
                    includeAbsolute: false,
                }
            }
        })
8. open the blade main or welcome file and make a div in the body with id 'app'
9. now go to the resources/js folder and make a file named welcome.vue and type the follwing code in it and save 
  <template>
    <h1>welcome page frm vue js</h1>
</template>
10. now open app.js file in resources/js folder and remove the existing code. Then type the following code
import {createApp} from "vue";
import welcome from './welcome.vue';

createApp(welcome).mount('#app');
11. No open welcome.blade file and add the following code in head section
@vite(['resources/js/app.js','resources/css/app.css'])
12. Hurrah!! now enjoy laravel with vue..
1. open your laravel application as normal routine in chrome browser
2. Now click on three dots at top right of browser 
3. Then click on more tools option
4. Then click on create shortcut
5. Tick the option here that is open as window.
6. Now change the shortcut image with your own image
7. convert png/jpg etc image to .ico image
8. enjoy the laravel app as your desktop application. Thanks!
1. Make a file named index.php in the parent application folder
2. Point this file to the index.php file exits in the public folder by writing this code in that file 
  <?php
 	require_once __DIR__.'/public/index.php';
3. copy .htaccess file from public folder to parent application folder
4. Now change all links and script libraries in layoutfiles with public at start of the href link and also with script src.
5. Now enjoy you have no need to use php artisan serve
1. Right click on xampp control and click run as administrator
2. click on config button at top right corner of xampp and tick on Apache and mysql then tick on start control panel minimized
3. Then create a short cut of xampp-control exe file in c drive
4. Then type run at task bar the in RUN type shell:startup then paste the short to that startup folder
5. and thats it now you can restart your computer to check the auto ON functionality.
Thanks!
1.go to htdocs folder and open git bash
2. git clone "url taken from remote github link"
3. cd projectName
4. composer update / composer install
5. make database name it with projectname or other
6. you can do npm install if required
7. then make a copy of .env file by using this command
8. cp .env.example .env
9. php artisan key:generate
10. php artisan migrate --seed
--------Include this in seeder file-------
use Illuminate\Support\Facades\Hash;
$user->password = Hash::make('12345');
----------Terminal Command------------------------
php artisan make:seeder BookSeeder
----------BookSeeder Code---------------------------
  use Faker\Factory as Faker;
----------Public function run() code------------------
 $faker = Faker::create();
       for ($i=0; $i < 100; $i++) { 
            $book = new Book;
            $book->book_name = $faker->name;
            $book->book_author = $faker->city;
            $book->save();
        }
----------Database Seeder code public function run()---------------
   $this->call([
            BookSeeder::class
        ]);
------------------php artisan code--------------------------------
php artisan db:seed
---------write it in head section in blade template-----------------
<meta name="csrf-token" content="{{csrf_token()}}"> 
  ----------do not use slim version of J Query---------------
    --------Use this before document ready in script tag--------
    <script>
          $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                });
    </script>
------------------then------------------------------------
 <script>
        $(document).ready(function(){
            $('#country').change(function(){
                var country_id = $(this).val();
                $('#city').html('<option value="">Select City</option>');
                
                $.ajax({
                    url: '/getState/'+country_id,
                    type:'post',
                    success: function(result){
                        $('#state').html(result);
                    }
                });
            });

            $('#state').change(function(){
                var state_id = $(this).val();

              
                
                $.ajax({
                    url: '/getCity/'+state_id,
                    type:'post',
                    success: function(result){
                        $('#city').html(result);
                    }
                });
            });
        });
    </script>
--------------------------web.php code--------------------------
Route::post('/getState/{id}', [PlaceController::class, 'getState']);
Route::post('/getCity/{id}', [PlaceController::class, 'getCity']);
-------------------------Controller Code -----------------------------
  public function getState($country_id){
        $states = State::where('country_id', $country_id)->get();
        $html = '';
        foreach($states as $state){
            $html .='<option value="'.$state->id.'">'.$state->state_name.'</option>';
        }
        echo $html;
    }

    public function getCity($state_id){
        $cities = City::where('state_id', $state_id)->get();
        $html = '';
        foreach($cities as $city){
            $html .='<option value="'.$city->id.'">'.$city->city_name.'</option>';
        }
        echo $html;
    }
function save_test() {
    showloading();
 
    let AssessmentCategorie = []
    $("input[name='AssessmentCategorie[]']:checked").each(function () {
        AssessmentCategorie.push(parseInt($(this).val()));
    });

 $.post("ajax/save_test.php", {
     
        AssessmentCategorie: AssessmentCategorie,

    }, function (data) {

        $("#save_test").html(data);
        get_test();
        hide_loading();

    });
  
  }
<?php 
/*
 ==================
 Ajax Search
======================	 
*/
// add the ajax fetch js
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch(){

    jQuery.ajax({
        url: '<?php echo admin_url('admin-ajax.php'); ?>',
        type: 'post',
        data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
        success: function(data) {
            jQuery('#datafetch').html( data );
        }
    });

}
</script>

add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
	
	function khFunction(){ // on focusout rest inpput field value
	            jQuery('#datafetch').html( " " );
       }
	
    function fetch(){

	//test if there is at least to caracters on the input field 
      if(jQuery('#keyword').val().length > 2){
			
		
    jQuery.ajax({
        url: '<?php echo admin_url('admin-ajax.php'); ?>',
        type: 'post',
        data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
        success: function(data) {
            jQuery('#datafetch').html( data );
        }
    }); }

}
</script>

<?php
}

// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){

    $the_query = new WP_Query( array( 
		'posts_per_page' => -1, 
		's' => esc_attr( $_POST['keyword'] ),
		'category_name' => 'top-apps', 'post_type' => array('post') ) );
	
    if( $the_query->have_posts() ) :
        echo '<ul>';
        while( $the_query->have_posts() ): $the_query->the_post(); ?>

            <li><a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a></li>

        <?php endwhile;
       echo '</ul>';
        wp_reset_postdata();  
    endif;

    die();
}





// ------------------ Cart drawer open/close  ----------------------\\
  $(document).on("click",".site-header__cart-ajax", function(e){
    e.preventDefault();
    $('body').toggleClass('drawer-open');
  });
  $('.cart-drawer__close').click(function(e){
    $('body').toggleClass('drawer-open');
  });
  $('.drawer-overlap').click(function(e){
    $('body').toggleClass('drawer-open');
  }); 

  $('.cart-drawer__continue').click(function(e){
    $('body').toggleClass('drawer-open');
  });





  $(document).on("click",".single-ajax-cart-btn", function(e){
    e.preventDefault()
      $(this).text('Adding...');
      $.ajax({
            type: 'POST', 
            url: '/cart/add.js',
            dataType: 'json', 
            data: $(this).parent().parent().serialize(),
            success: function(data) {
              $('.product-form__cart-submit').text('Add to cart');
              get_cart_details();
            console.log("submitted");
            },
            error: 'addToCartFail'
        });
  });

  
  $(document).on("click",".single-ajax-cart-btn-upsell", function(e){
    e.preventDefault()
    var upsell_form = $(this).parent();
      $(this).text('Adding...');
      $.ajax({
            type: 'POST', 
            url: '/cart/add.js',
            dataType: 'json', 
            data: $(upsell_form).serialize(),
            success: function(data) {
              $('.single-ajax-cart-btn-upsell').text('Add to cart');
              get_cart_details();
            console.log("submitted");
            },
            error: 'addToCartFail'
        });
  });

  $(document).on("click",".new-ajax-btn", function(e){
    e.preventDefault()
      $(this).text('Adding...');
      $.ajax({
            type: 'POST', 
            url: '/cart/add.js',
            dataType: 'json', 
            data: $(this).parent().parent().serialize(),
            success: function(data) {
              $('.product-form__cart-submit').text('Add to cart');
              get_cart_details();
            console.log("submitted");
            },
            error: 'addToCartFail'
        });
  });





var product_total_price = 0;

// ----------------- Get cart details -------------\\
function get_cart_details(){
  $.getJSON('/cart.js', function(cart) {
    // The cart data
    var drawer_item_html = '';              
    var cart_items = cart.items;
    var total_items = cart.item_count;
    product_total_price = cart.items_subtotal_price;
    console.log(product_total_price);
    $('.cart-drawer__total-amount').html('$'+((product_total_price * 0.01).toFixed(2)-20));
    console.log('total_items'+total_items);
    if(total_items == 0){
      $('.cart-drawer__no-item').addClass('cart-drawer__no-item_visible');
    }else{
      $('.cart-drawer__no-item').removeClass('cart-drawer__no-item_visible');
    }
    $('.cart-drawer__count').html(total_items);
    $('.cart-drawer__count--bag').html(total_items);
    $('.nav__cart-count').html(total_items);
    $('body').addClass('drawer-open');
    console.log(cart);
      for(var i=0; i<=cart_items.length; i++){
          var product_image = cart_items[i].image;
          var product_name = cart_items[i].product_title;
          var product_variant_option_name = cart_items[i].options_with_values[0].name;
          var product_variant_option_value = cart_items[i].options_with_values[0].value;
          var product_variant = cart_items[i].variant_title;
          var product_quantity = cart_items[i].quantity;
          var product_price = cart_items[i].line_price;
          var product_variant_id = cart_items[i].variant_id;
          var product_url = cart_items[i].url;
          var product_key = cart_items[i].key;
          
          // ------------- Add HTML item here -------------//
          drawer_item_html += '<div class="cart-drawer__item">';
          drawer_item_html += '<div class="cart-drawer__image">';
          drawer_item_html += '<img src="'+product_image+'" >';
          drawer_item_html += '</div>';
          drawer_item_html += '<div class="cart-drawer__info">';
          drawer_item_html += '<div class="cart-drawer__title"><a class="cart-drawer__url" href="'+product_url+'">'+product_name+'</a></div>';
        if(product_variant_option_value.indexOf("Default Title") != 0 ){
          drawer_item_html += '<div class="cart-drawer__variant">'+/*product_variant_option_name*/"Size/Color"+': '+product_variant_option_value+'</div>';
        }  
          drawer_item_html += '<div class="cart-drawer__price"  data-id="'+product_variant_id+'">$'+((product_price * 0.01).toFixed(2))+'</div>';
          drawer_item_html += '<div class="cart-drawer__qty">';
          drawer_item_html += '<button class="minus-btn cart-drawer__qty-btn" type="button" name="button"><i class="fa fa-minus"></i></button>';
          drawer_item_html += '<input type="number"  class="cart-drawer__qty-input" name="updates['+product_variant_id+']" data-id="'+product_variant_id+'"  id="updates_'+product_key+'" value="'+product_quantity+'" min="1" aria-label="Quantity" />';
          drawer_item_html += '<button class="plus-btn cart-drawer__qty-btn" type="button" name="button"><i class="fa fa-plus"></i></button>';
          drawer_item_html += '</div>';
          drawer_item_html += '</div>';
          drawer_item_html += '<div class="cart-drawer__remove">';
          drawer_item_html += '<a href="#" class="cart-drawer__remove-url" data-id="'+product_variant_id+'"><i class="fa fa-trash-o" aria-hidden="true"></i></a>';
          drawer_item_html += '</div>';
          drawer_item_html += '</div>';
          $('.cart-drawer__content').html(drawer_item_html);
          } 
      });     
}

// var discount_apply = '';
// var discount_status = '';

// $('.cart_discount_button').click(function(){
//     var my_inp = $('.disc_cont').val();
//     var my_discounts = $('.myDiscHolder').attr('data-disc');

//     if (my_discounts.indexOf(my_inp) >= 4){
//         discount_apply = my_inp;
//         discount_status = 'yes';
//         console.log(discount_apply);
//         $('.disc_cont').addClass('border-green');
//         $('.disc_cont').removeClass('border-red');
//     }else{
//         discount_status = 'no';
//         console.log('Bammer!! it did not matched');
//         $('.disc_cont').addClass('border-red');
//         $('.disc_cont').removeClass('border-green');
//     }
// });

// $('.button_checkout').click(function(e){
//     e.preventDefault();
//     if(discount_status == 'yes'){
//         window.location = '/checkout?discount='+ discount_apply;
//     }
//     else{
//         window.location = '/checkout';
//     }
// })



$('.button_checkout').click(function(e){
    window.location = '/checkout?discount=SPRING';
})











// ------------------ Ajax cart functions ----------------------\\
$(document).on("click",".minus-btn", function(e){
  e.preventDefault();
  var $this = $(this);
  var $input = $this.closest('div').find('input');
  var value = parseInt($input.val());  
  if (value > 1) {
    value = value - 1;
  } else {
    value = 0;
    $(this).parent().parent().parent().remove();
  }  
  $input.val(value);
  change_qty($input);
});

$(document).on("click",".plus-btn", function(e){    
  e.preventDefault();
  var $this = $(this);
  var $input = $this.closest('div').find('input');
  var value = parseInt($input.val());  
  if (value < 100) {
    value = value + 1;
  } else {
    value =100;
  }  
  $input.val(value);            
    change_qty($input);
});  

function change_qty($input){
  var variant_id= $($input).attr("data-id");
  var quantity= $($input).val();          
  var data = { updates: {} };
  data.updates[variant_id] = quantity;
  jQuery.ajax({
    type: 'POST',
    url: '/cart/update.js',
    data: data,
    dataType: 'json',
    success: function(res) {               
      console.log(res.items_subtotal_price);
      product_total_price = res.items_subtotal_price;
      var pro_data = res.items;              
      console.log(res);
      var price = res.total_price ;
      price = price/100 - 20;
      var tot_qty = res.item_count;
      if(tot_qty == 0){
        $('.cart-drawer__no-item').addClass('cart-drawer__no-item_visible');
      }else{
        $('.cart-drawer__no-item').removeClass('cart-drawer__no-item_visible');
      }
      $('.cart-drawer__count').html(tot_qty);
      $('.cart-drawer__count--bag').html(tot_qty);
      $('.nav__cart-count').html(tot_qty);
      $('.cart-drawer__total-amount').html('$' + price.toFixed(2));
      if(tot_qty == 0){
        $('.cart-drawer__total-amount').html('$0');
      }else{
        $('.cart-drawer__total-amount').html('$' + price.toFixed(2));
      }
      jQuery.each(pro_data, function(index, item) {
        var spe_price=item.final_line_price;
        spe_price= spe_price/100;
        if(item.id == variant_id){
          $('.cart-drawer__price[data-id='+item.id+']').html('$' + spe_price.toFixed(2));
        }
      });    
      
    }
  });
};

$(document).on("click",".cart-drawer__remove-url", function(event){
  event.preventDefault();
  var variant_id = $(this).attr('data-id');
  console.log("varient: "+variant_id);
  var data = { updates: {} };
  data.updates[variant_id] = '0';
  jQuery.ajax({
  type: 'POST',
  url: '/cart/update.js',
  data: data,
  dataType: 'json',
  success: function(res) {
  console.log(res);
  console.log(res.items_subtotal_price);
  product_total_price = res.items_subtotal_price;      
   var pro_data = res.items;
   var price = res.total_price;
    price = price/100 -20;
    var tot_qty = res.item_count;
    if(tot_qty == 0){
      $('.cart-drawer__no-item').addClass('cart-drawer__no-item_visible');
    }else{
      $('.cart-drawer__no-item').removeClass('cart-drawer__no-item_visible');
    }
    $('.cart-drawer__count').html(tot_qty);
    $('.cart-drawer__count--bag').html(tot_qty);
    $('.nav__cart-count').html(tot_qty);
    $('.cart-drawer__total-amount').html('$' + price.toFixed(2));
          if(tot_qty == 0){
        $('.cart-drawer__total-amount').html('$0');
      }else{
        $('.cart-drawer__total-amount').html('$' + price.toFixed(2));
      }
      if(tot_qty <= 0){
      $('.my__custom_cart_drawer').addClass('no_item');
    }
    
    var drawerDiscount = $(".cart-drawer__price").attr("data-id");
    console.log(drawerDiscount);
    

  
  }
  });
    $(this).parent().parent().remove();
  });


// ------------------ Ajax cart update for cart template ----------------------\\
$(document).on('change', '.cart__quantity-selector', function() {      
var variant_id= $(this).attr("data-id");
var quantity= $(this).val();      
var data = { updates: {} };
data.updates[variant_id] = quantity;
console.log(data);
jQuery.ajax({
type: 'POST',
url: '/cart/update.js',
data: data,
dataType: 'json',
success: function(res) { 
product_total_price = res.items_subtotal_price;
var pro_data = res.items;          
console.log(pro_data);
var price = res.total_price ;
price = price/100;
var tot_qty = res.item_count;
$('.new-cart-sidebar #bk-cart-subtotal-price').html('$' + price.toFixed(2));
$('.the_cart_total_amount').html('$' + price.toFixed(2));
$('.new-cart-sidebar .es-subtotal-text').html('Subtotal ( '+tot_qty+' Products):');
$('.the_cart_title').html(tot_qty+' item in your Cart');

jQuery.each(pro_data, function(index, item) {
  var spe_price=item.final_line_price;
  spe_price= spe_price/100;
  if(item.id == variant_id){
    $('.saso-cart-item-price.desk-price-ajax-change[data-id='+item.id+']').html('$' + spe_price.toFixed(2));
    $('.saso-cart-item-price.mob-price-ajax-change[data-id='+item.id+']').html('$' + spe_price.toFixed(2));
  
  }
});

}
});
//setTimeout(function(){ window.location.href="/cart"; }, 1000);
});




// ------------------ End of Ajax cart functions ----------------------\\
function verificarEmail() {
  let data = $("#email").serialize();
  $("#errorEmail").text("");
  $.ajax({
    method: "POST",
    url: '/verificarEmail',
    data: data
  })
  .done(function(respuesta) {
    if(respuesta == "Existe"){
      $("#errorEmail").text("El email ya se encuentra registrado.")
    }
   })
  .fail(function() {
    alert( "error" );
  })
}
// GET Request.
fetch('https://api.github.com/users/rich-harris')
  // Handle success
  .then(response => response.json())  // convert to json
  .then(json => console.log(json))    // print data to console
  .catch(err => console.log('Request Failed', err)); // Catch errors
star

Wed Sep 06 2023 09:16:54 GMT+0000 (Coordinated Universal Time)

#jquery #ajax
star

Tue Jan 10 2023 10:53:52 GMT+0000 (Coordinated Universal Time)

#ajax #async #await
star

Fri Jan 06 2023 04:29:42 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Wed Jan 04 2023 07:11:52 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Wed Jan 04 2023 06:57:31 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Wed Jan 04 2023 06:51:38 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Tue Jan 03 2023 17:20:28 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Tue Jan 03 2023 07:18:36 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Mon Jan 02 2023 10:15:44 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Fri Dec 30 2022 06:57:11 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Thu Dec 22 2022 12:27:38 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Thu Dec 15 2022 02:43:24 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Tue Dec 13 2022 07:23:56 GMT+0000 (Coordinated Universal Time) Install Vue 3 In Laravel 9 With Vite | Laravel Vite With Vue 3 | Vite Laravel Vue 3 | #1 HINDI

#laravel #ajax
star

Sun Dec 11 2022 16:08:23 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Sun Dec 11 2022 15:59:59 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Sun Dec 11 2022 15:50:54 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Tue Oct 18 2022 10:28:17 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Tue Oct 11 2022 07:41:46 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Sat Oct 08 2022 16:05:01 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Sat Oct 08 2022 10:20:04 GMT+0000 (Coordinated Universal Time)

#laravel #ajax
star

Sun Aug 28 2022 13:15:03 GMT+0000 (Coordinated Universal Time)

#ajax #checkbox
star

Fri Dec 17 2021 13:35:42 GMT+0000 (Coordinated Universal Time) https://code.mukto.info/wordpress-ajax-search-without-plugin/

#php #ajax
star

Thu Oct 28 2021 10:14:17 GMT+0000 (Coordinated Universal Time) pupnaps.com

#javascript #ajax
star

Tue Mar 30 2021 01:18:02 GMT+0000 (Coordinated Universal Time)

#ajax #jquery #javascript
star

Wed Oct 28 2020 08:30:04 GMT+0000 (Coordinated Universal Time) https://medium.com/javascript-in-plain-english/the-ultimate-javascript-fetch-api-cheatsheet-e60b98c8cdbe

#javascript #ajax

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension