Top Questions:

  • 5 years-11 months

    How to create add to cart with AJAX on single and variable products programmatically

    • Category : wordpress
    • Location : Chandigarh, India
    • Posted On :
    • Posted by : Vikas

    default WooCommerce if the user clicks on the add to cart button, that item is added to the cart. if you want to add custom add to cart button please remove default "add to cart" button

    // custom template
    <button type="submit" class="custom_cart_button">add to cart</button>
    <script type="text/javascript">
    jQuery(document).ready(function() {
    var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
        jQuery('.custom_cart_button').submit(function(e) {
            jQuery.ajax({
                url: ajaxurl,
                type: "post",
                data: {				
    		action : 'post_product_variations19'
    	    },
                success: function(data) {   
                	console.log(data);
                }
            });
    	return false;
        });
    });
    </script>
    
    
    // function.php
    add_action( 'wp_ajax_nopriv_post_product_variations19', 'post_product_variations_func19' );
    add_action( 'wp_ajax_post_product_variations19', 'post_product_variations_func19' );
    function post_product_variations_func19() {
    
        global $woocommerce;
    
        $product_id = 364; // your product id
    
        $found = false;
    
        //check if product already in cart
        if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
            foreach ($woocommerce->cart->get_cart() as $cart_item_key => $values ) {
                $_product = $values['data'];
                if ( $_product->id == $product_id ) {
                	//$calc_qty = $values['quantity'] < 1 ? 1 : $values['quantity']+1;
                	//$woocommerce->cart->set_quantity( $cart_item_key, $calc_qty, true );
                    $found = true;
                }
            }
            // if product not found, add it
            //if ( ! $found )
                $woocommerce->cart->add_to_cart( $product_id );
        } else {
            // if no products in cart, add it
            $woocommerce->cart->add_to_cart( $product_id );
        }
    	
    wp_die();
    }
  • 5 years-11 months

    HTML5 Form Validation With the pattern (Regex) Attribute in html

    • Category : html
    • Location : Chandigarh, India
    • Posted On :
    • Posted by : Vikas

    This is another Client Side Validation strategy No JavaScript or jQuery required, Thanks to HTML5 in light of the fact that approvals should now be possible utilizing HTML5 without coding of javascript or any server side dialect, utilizing HTML5 you can approve frames with design, Forms must be approve either utilizing customer side or server side since it causes you to gather redress information or substantial shape esteems from the clients, you can't trust clients aimlessly, how about we see it.

    pattern="[A-Za-z] " accepts only capital or small letters. 
    <label>Name : (letters only)*</label>
    <input type="text" pattern="[A-Za-z] " title="only letters" required />
    
    pattern="[a-z0-9._% -] @[a-z0-9.-] \.[a-z]{2,4}$" accepts valid email address 
    <label>E-mail : (xyz@zyx.com)*</label>
    <input type="email" pattern="[a-z0-9._% -] @[a-z0-9.-] \.[a-z]{2,4}$" title="xyz@something.com" required />
    
    pattern="https?://. " required title="https://dorcode.com" accepts valid web url starting with http://. 
    <label>website : (https://dorcode.com)*</label>
    <input type="url"  pattern="https?://. " title="https://dorcode.com" required />
    
    pattern="[0-9] " accepts only numbers 0, 1, 2.... 
    <label>pin code : (numbers only)</label>
    <input type="text" pattern="[0-9] " title="numbers only" required />
    
    pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" accepts one number one upper and lower case letters with 8 or more chars. 
    <label>password : (at least 6 chars)</label>
    <input type="password" pattern=".{6,}" title="Six or more characters" required />
    
    pattern="^\d{10}$" accepts only numeric values with 10 digit. 
    <label>phone no : (10 chars)</label>
    <input type="tel" pattern="^\d{10}$" title="10 numeric characters only" required />
    
    pattern="^[a-zA-Z][a-zA-Z0-9-_\.]{5,12}$" accepts alphanumeric values letters and digits. 
     
  • 3 years-4 months

    Jquery hide network requests from inspect element

    • Category : jquery
    • Location : Chandigarh
    • Posted On :
    • Posted by : Guley

    Using this module you can hide requested parameters from inspect element

    var http = new XMLHttpRequest();
    var url = "Url Path";
    var params ='Your parameters';
    http.open("GET", url, true);
    
    //Send the proper header information along with the request
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    
    http.onreadystatechange = function() {//Call a function when the state changes.
        if(http.readyState == 4 && http.status == 200) {
            console.log(http.responseText);
        }
    http.send(params);
    }
     
  • 5 years-11 months

    How to Add Pagination in Your WordPress Theme or Core Php

    • Category : php
    • Location : Chandigarh, India
    • Posted On :
    • Posted by : Vikas

    WordPress offers built-in functionality for navigating through posts. Theme developers can use simple default wordpress pagination function or other pagination function for better customize.

    // Create table in mysql
    CREATE TABLE `your_table_name` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `title` varchar(200) NOT NULL,
      `addtime` int(20) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    
    // Insert table data
    INSERT INTO `your_table_name` (`id`, `title`, `addtime`) VALUES
    (1, 'test', 1299446702);	// addtime is timestamp
    
    
    
    <?php
    // insert this code where your want to add pagination
    // ----------- code start -----------
    
    $table_name =  "your_table_name"; 	// enter your table name
    $item_per_page=5;					// enter number 
    
    $all = $wpdb->get_row( "SELECT count(*) as total FROM {$table_name} WHERE 1=1", ARRAY_A );
    $page_number = (get_query_var('page')) ? get_query_var('page') : 1;
    $offset = ($page_number - 1) * $item_per_page;
    $data = $wpdb->get_results( "SELECT * FROM {$table_name} WHERE 1=1 ORDER BY id DESC LIMIT $offset,$item_per_page", ARRAY_A );
    $cou=$page_number*$item_per_page;
    ?>
    
    <h2>Results <?=$page_number ?>-<?=($cou>$all['total'])?$all['total']:$cou ?> of <?=$all['total'] ?></h2>
    <ul class="pagination">
    	<?php echo pagination($all['total'], $item_per_page, $page_number, site_url()."/your-page-name/?page=%d"); ?>
    </ul>
    
    
    <?php
    foreach ($data as $one) {
    ?>
    		<?=$one['id'] ?> <br />
    		<?=$one['title'] ?>
    <?php
    }
    ?>
    // ----------- code end -----------
    
    
    // add function.php in wordpress----------- code start ----
    
    function pagination($item_count, $limit, $cur_page, $link)
    {
           $page_count = ceil($item_count/$limit);
           $current_range = array(($cur_page-2 < 1 ? 1 : $cur_page-2), ($cur_page 2 > $page_count ? $page_count : $cur_page 2));
    
           // First and Last pages
           $first_page = $cur_page > 3 ? '<a href="'.sprintf($link, '1').'">1</a>'.($cur_page < 5 ? ', ' : ' ... ') : null;
           $last_page = $cur_page < $page_count-2 ? ($cur_page > $page_count-4 ? ', ' : ' ... ').'<a href="'.sprintf($link, $page_count).'">'.$page_count.'</a>' : null;
    
           // Previous and next page
           $previous_page = $cur_page > 1 ? '<a href="'.sprintf($link, ($cur_page-1)).'">&lt;&lt;</a>  ' : null;
           $next_page = $cur_page < $page_count ? '  <a href="'.sprintf($link, ($cur_page 1)).'">&gt;&gt;</a>' : null;
    
           // Display pages that are in range
           for ($x=$current_range[0];$x <= $current_range[1];   $x)
                   $pages[] = '<a href="'.sprintf($link, $x).'">'.($x == $cur_page ? '<strong>'.$x.'</strong>' : $x).'</a>';
    
           if ($page_count > 1)
                   return '<p class="pagination">'.$previous_page.$first_page.implode('&nbsp;&nbsp;', $pages).$last_page.$next_page.'</p>';
    }
    
    // add function.php in wordpress----------- code end ----
  • 5 years-11 months

    how to use ajax in wordpress page

    • Category : php
    • Location : Chandigarh, India
    • Posted On :
    • Posted by : Vikas

    This article, aimed at plugin developers, describes how to add Ajax to a plugin or page. Before reading this article, you should be familiar with the following

    // function.php in Wordpress -------- Start Code--------
    add_action('wp_head', 'dorcode_ajaxurl');
    function dorcode_ajaxurl() {
       echo '<script type="text/javascript">
               var ajaxurl = "'.admin_url('admin-ajax.php').'";
            </script>';
    }
    
    
    add_action( 'wp_ajax_your_dorcode', 'my_dorcode' );
    add_action( 'wp_ajax_nopriv_your_dorcode', 'my_dorcode' );
    
    function my_dorcode() {
    	$data_id = intval( $_POST['data_id'] );
        echo $data_id;
        wp_die();
    }
    // function.php in Wordpress -------- End Code--------
    
    
    
    // Anywhere in Wordpress -------- Start Code--------
    
    // if you need
    var ajaxurl = "<?php echo admin_url('admin-ajax.php') ?>";
    jQuery(document).ready(function($) {
    	var data = {
    		'action': 'your_dorcode',
    		'data_id': 1525
    	};
    	jQuery.post(ajaxurl, data, function(response) {
    		alert('Got this from the server:' + response);
    	});
    
    });
    // Anywhere in Wordpress -------- End Code--------
  • 3 years-4 months

    Copy text to clipboard

    • Category : jquery
    • Location : Chandigarh
    • Posted On :
    • Posted by : Guley

    you can copy text to clipboard and paste where you want

    <button class="btn btn-success" id="copyButton" onclick="copyToClipboard('testing')">Copy</button>
    
    <script type="text/javascript">
    function copyToClipboard(elementId) {
    
      // Create a "hidden" input
      var aux = document.createElement("input");
    
      // Assign it the value of the specified element
      aux.setAttribute("value", elementId);
    
      // Append it to the body
      document.body.appendChild(aux);
    
      // Highlight its content
      aux.select();
    
      // Copy the highlighted text
      document.execCommand("copy");
    
      // Remove it from the body
      document.body.removeChild(aux);
    
    }
    </script>
  • 3 years-4 months

    Prevent auto rotation while uploading in php

    • Category : php
    • Location : Chandigarh
    • Posted On :
    • Posted by : Guley

    You can prevent auto image rotation problem using this code

    function correctImageOrientation($filename) {
      if (function_exists('exif_read_data')) {
        $exif = exif_read_data($filename);
        if($exif && isset($exif['Orientation'])) {
          $orientation = $exif['Orientation'];
          if($orientation != 1){
            $img = imagecreatefromjpeg($filename);
            $deg = 0;
            switch ($orientation) {
              case 3:
                $deg = 180;
                break;
              case 6:
                $deg = 270;
                break;
              case 8:
                $deg = 90;
                break;
            }
            if ($deg) {
              $img = imagerotate($img, $deg, 0);        
            }
            // then rewrite the rotated image back to the disk as $filename 
            imagejpeg($img, $filename, 95);
          } // if there is some rotation necessary
        } // if have the exif orientation info
      } // if function exists      
    }
    
    $target_dir = "blog/";
    $target_file = $target_dir . basename($blogimg);
    $imge=correctImageOrientation($target_file);
    move_uploaded_file($_FILES["blogimg"]["tmp_name"], $imge); 
    $query=mysql_query("insert into tablename (`image_name`) values ('$target_file')");
    
  • 3 years-4 months

    Drag Drop multiple divs

    • Category : php
    • Location : Chandigarh
    • Posted On :
    • Posted by : Guley

    you can drag drop all data between multiple divs

     <div id="1" dvSource dvSourceul">
    <ul id="dropul_1">
          <li class="drop"> <img alt="" src="images/Chrysanthemum.jpg" />
    <li class="drop"> <img alt="" src="images/Chrysanthemum.jpg" />
    <li class="drop"> <img alt="" src="images/Chrysanthemum.jpg" />
    <li class="drop"> <img alt="" src="images/Chrysanthemum.jpg" />
    <li class="drop"> <img alt="" src="images/Chrysanthemum.jpg" /> </li>
    </ul>
        </div>
    <div id="2">
    <ul id="dropul_2">
          <li class="drop"> <img alt="" src="images/Chrysanthemum.jpg" />
    <li class="drop"> <img alt="" src="images/Chrysanthemum.jpg" />
    <li class="drop"> <img alt="" src="images/Chrysanthemum.jpg" />
    <li class="drop"> <img alt="" src="images/Chrysanthemum.jpg" />
    <li class="drop"> <img alt="" src="images/Chrysanthemum.jpg" /> </li>
    </ul>
        </div>
    /********Jquery*********
    <script>
     $(function () {
                $("li.drop").draggable({
                    revert: "invalid",
                    refreshPositions: true,
                    drag: function (event, ui) {
                        ui.helper.addClass("draggable");
                       
                    },
                    stop: function (event, ui) {
                        if ($.ui.ddmanager.drop(ui.helper.data("draggable"), event)) {
                             ui.helper.removeClass("ui-draggable-dragging");
                             ui.helper.removeClass("draggable");
                        }
                        else {
                            //alert(" not dropped.");
                        }
                    }
                });
                $(".dvSourceul").droppable({
                    drop: function (event, ui ) {
                      var newId=event.target.id;
                      var aworkid=ui.draggable.attr('data-id');
                        ui.draggable.addClass("dropped");
                        $("#dropul_" newId).append(ui.draggable);
                        $.ajax({
                          type: "POST",
                          url: "update_work.php",
                          data:'id=' aworkid '&wrkid=' newId,
                          success: function(data){
                          // alert(data);
                          }
                          });
                    }
                });
            });
    
    </script>
  • 3 years-4 months

    Drag drop

    • Category : php
    • Location : Chandigarh
    • Posted On :
    • Posted by : Guley

    Drag Drop your table's data using jQuery,Ajax,php and mysql

    /**********HTML PART START**************/
    
    <div class="x_content my-data" id="">
    
                      <table class="table table-bordered">
                        <thead>
                          <tr>
                            <th>#</th>
                            <th>Image</th>
                            <th>Category</th>
                            <th>Edit</th>
                            <th>Delete</th>
                          </tr>
                        </thead>
    <?php
      
      $query = "SELECT * FROM product ORDER BY pos ASC";
      $result = mysql_query($query) or die(mysql_error().': '.$query);
      if(mysql_num_rows($result)) {
    ?>
    <form id="dd-form" action="" method="post">
      <input type="checkbox" value="1" name="autoSubmit" id="autoSubmit" class="autoooo" checked/>
    <tbody id="sortable-list">
      <?php 
        $order = array();
        $i=1;
        while($row = mysql_fetch_assoc($result)) {
            $img=explode(",",$row['product_img']);
                           $img=explode(",",$row['product_img']);
    $catqry=mysql_fetch_array(mysql_query("select * from category where id='".$row['product_cat_id']."'"));
    $scatqry=mysql_fetch_array(mysql_query("select * from subcategory where id='".$row['product_subcat_id']."'"));
    
                           echo '<tr title="',$row['id'],'"><td>',$i,'</td><td><img src="',$img[0],'" height="50" width="50"></td><td>',$catqry['cat_name_eng'].'/'.$catqry['cat_name_china'],'</td><td><a href="?edit=',$row['id'],'"><i class="fa fa-pencil"></i></a></td><td><a href="?delete=',$row['id'],'" onclick="return confirm("Are you sure you want to delete")"><i class="fa fa-trash"></i></a></td></tr>';
          $order[] = $row['id'];
          $i  ;
        }
      ?>
    </tbody>
    <br />
    <input type="hidden" name="sort_order" id="sort_order" value="<?php echo implode(',',$order); ?>" />
    </form>
    <?php } ?>
    
    
                      </table>
    
                    </div>
                  </div>
            
            </div>
    <style type="text/css" media="screen">
    #sortable-list1   { padding:0; }
    #sortable-list1 tr  { padding:4px 8px; color:#000; cursor:move; list-style:none; width:100px; background:#ddd; margin:10px 0; border:1px solid #999; }
    #sortable-list1 tr td { text-align: center; }
    #message-box1   { padding:4px 8px; margin:0 0 14px 0; width:500px; }
    .autoooo{ display : none; }
    </style>
    /**********HTML PART END**************/
    /**********SCRIPT PART START**************/
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
      <script>
    /* when the DOM is ready */
    $(document).ready(function() {
    
      /* grab important elements */
      var sortInput = $('#sort_order');
      var submit = $('#autoSubmit');
      var messageBox = $('#message-box');
      var list = $('#sortable-list');
      /* create requesting function to avoid duplicate code */
      var request = function() {
      $.ajax({
      url: "drop_ajax.php",
      data:'sort_order='   sortInput[0].value   '&ajax='   submit[0].checked   '&do_submit=1&byajax=1',
      type: "POST",
      success: function(data) {
            window.location.reload();
      }
      });
      };
      /* worker function */
      var fnSubmit = function(save) {
       
        var sortOrder = [];
        list.children('tr').each(function(e){
          sortOrder.push($(this).data('id'));
        });
        sortInput.val(sortOrder.join(','));
       // console.log(sortInput.val());
        if(save) {
          request();
        }
      };
      /* store values */
      list.children('tr').each(function(e) {
        var tr = $(this);
        tr.data('id',tr.attr('title')).attr('title','');
      });
      /* sortables */
      list.sortable({
        opacity: 0.7,
        update: function() {
          fnSubmit(true);
        }
      });
      list.disableSelection();
    });
    </script>
    /**********SCRIPT PART END**************/
    /**********AJAX PART START**************/
    <?php
    include('config.php'); /include your db file here
    /* on form submission */
    if(isset($_POST['do_submit']))  {
      /* split the value of the sortation */
      $ids = explode(',',$_POST['sort_order']);
     /* run the update query for each id */
      foreach($ids as $index=>$id) {
       $id = (int) $id;
        if($id != '') {
         $query = 'UPDATE product SET pos = '.($index   1).' WHERE id = '.$id;
         $result = mysql_query($query) or die(mysql_error().': '.$query);
        }
     }
     
      /* now what? */
     if($_POST['byajax']) { die(); } else { $message = 'Sortation has been saved.'; 
     
      echo $message;
      }
    }
    ?>
    
    
    /**********AJAX PART END**************/
  • 3 years-4 months

    5 Star Rating Using php,ajax,jQuery

    • Category : php
    • Location : Chandigarh
    • Posted On :
    • Posted by : Guley

    simple php rating in php

    <?php
    require "user/class.user.php";
    $auth_user = new USER();
    /********PDO Code***********/
    $email='user@gmail.com';
    $user=$auth_user->runQuery("SELECT * FROM login where email=:email");
    $user->execute(array(':email'=>$email));
    $userdatasingle=$user->fetchAll();
    $userdatasingle=$userdatasingle[0];
    ?>
    /*****HTML*******/
    <div class="rating">
                          
     <input type="hidden" name="rating" id="rating" value="<?php echo $userdatasingle["rating"]; ?>" />
           <ul onMouseOut="resetRating(<?php echo $userdatasingle["id"]; ?>);">
                 <?php
                 for($i=1;$i<=5;$i  ) {
                 $selected = "";
                 if(!empty($userdatasingle["rating"]) && $i<=$userdatasingle["rating"]) {
                 $selected = "selecteds";
                 }
         ?>
      <li class='<?php echo $selected; ?>' onmouseover="highlightStar(this,<?php echo $userdatasingle["id"]; ?>);" onmouseout="removeHighlight(<?php echo $userdatasingle["id"]; ?>);" onClick="addRating(this,<?php echo $userdatasingle["id"]; ?>);">&#9733;</li>  
                            <?php }  ?>
                        <ul>
                        <span class="ratings"><a href="#" class="Lgreen-txt font-6 rat-txt"><?php echo $userdatasingle["rating"]; ?> anmeldelser</a>
                       </span>
    </div> 
    /***********Script*************/
    <script>
    function highlightStar(obj,id) {
      removeHighlight(id);    
      $('.rating li').each(function(index) {
        $(this).addClass('highlights');
        if(index == $('.rating li').index(obj)) {
          return false; 
        }
      });
    }
    
    function removeHighlight(id) {
      $('.rating li').removeClass('selecteds');
      $('.rating li').removeClass('highlights');
    }
    
    function addRating(obj,id) {
      $('.rating li').each(function(index) {
        $(this).addClass('selecteds');
        $('#rating').val((index 1));
        if(index == $('.rating li').index(obj)) {
          return false; 
        }
      });
      $.ajax({
      url: "add_rating.php",
      data:'id=' id '&rate=' $('#rating').val(),
      type: "POST",
      success: function(data) {
      $(".rating").load(location.href " .rating>*","");
      }
      });
    }
    
    function resetRating(id) {
      if($('#rating').val() != 0) {
        $('.rating li').each(function(index) {
          $(this).addClass('selecteds');
          if((index 1) == $('#rating').val()) {
            return false; 
          }
        });
      }
    } 
    </script>
    /**********AJAX File*************/
    require "user/class.user.php";
    $auth_user = new USER();
    
    if (isset($_POST['rate']) && !empty($_POST['rate'])) {
     
        $rate = $_POST['rate'];
        $id = $_POST['id'];
    // check if user has already rated
        $sql = $auth_user->runQuery("UPDATE `login` SET rating=:rating WHERE `id`=:id");
       $sql->execute(array(':id'=>$id,':rating'=>$rate));
       
    }