顯示具有 jquery 標籤的文章。 顯示所有文章
顯示具有 jquery 標籤的文章。 顯示所有文章

2022年5月12日 星期四

JS取得Select選單的值與文字+onchange事件

 下拉選單html sample:

    <select id='fruit' onchange='getInfo(this)'>

            <option value=apple>Apple</option>

            <option value=banana>Banana</option>

            <option value=lemon>Lemon</option>

        </select>


Jquery取得Value:

    $('#fruit').val()

Jquery取得選取的文字:

    $('#fruit').find(':selected').text()


當選單變更選項時觸發事件範例如下:

<html lang="zh-TW">
<head>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
<!--取得Selecet資料Function-->
<script>
function getInfo(){
fruit=$('#fruit').val()
fruitName=$('#fruit').find(':selected').text()
showInfo='Val:'+fruit+'|Name:'+fruitName
$('#info').text(showInfo)
}
</script>
</head>
<body>
<!--Select Sample-->
<select id='fruit' onchange='getInfo()'>
<option value=''>-Choose One-</option>
<option value=apple>Apple</option>
<option value=banana>Banana</option>
<option value=lemon>Lemon</option>
</select>
<div>
<label>Info:</label>
<label id='info'></label>
</div>
</body>
</html>



2020年8月6日 星期四

JQuery ajax post, php接收,回傳資料

花了些時間研究圖片上傳功能。
前端將圖片轉成Base64後,透過ajax post傳到後端php程式,由程式寫入資料庫並產生圖片路徑,再回傳圖片路徑資料給前端。

前端程式:
Head設定語系跟載入jquery
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
</head>

HTML:包含一個編號、一個選擇圖片功能,一個上傳按鈕,還有一個顯示回傳資料的欄位
<html>
    <form>
        <label> 編號
            <input id="pid" type="text"/>
        </label>
        <label> 圖檔:</label>
        <label class="btn_img">請選擇圖片
            <input id="upload_img" type="file">
        </label>
        <div class="edit_form_img">
            <img id="img_preview" />
        </div>
        <input id="sent" class="form_submit" type="button" value="submit" ></input>
    </form>
    <label id="info"></label>
</html>

JS:將選擇的圖片轉成base64並產生預覽
    $("#upload_img").change(function() {
        //readURL(this);//互叫變更預覽圖片的功能
        //取得file選擇的檔案
        pv_img = $("#upload_img").get(0).files[0];
        //新增reader物件轉成base64資料,再onload時寫入圖片的scr
        var reader = new FileReader();
        reader.onload=function(){
            $("#img_preview").attr('src',reader.result);
        }
        reader.readAsDataURL(pv_img);
    });

JS 當上傳按鈕被點擊後,取得資料,並透過ajax Post到php
-這裡偷懶取代base64資料前的資料描述文字,但比較好的作法應該是要另外存檔案格式,之後轉回圖片時再加上附檔名(這動作可以在php端處理,也可以在前端)
-processData這個參數有點神奇,當true時data參數才能正確傳到php端,false就不行了;但網路上有些範例卻說要用false。若有大大知道原理,還忘不吝告知,感恩喔!
-data的傳送方式試過傳送form序列化或json.stringfy,但資料還是送不出去;這邊提供傳送成功的方式跟php接收的程式有關係。
- 取回php回傳的陣列資料,先抓兩個欄位顯示出來。

    $('#sent').click(function(){
        img64=$("#img_preview").attr("src");
        sb64=img64;
        //取代編碼後前面的描述文字
        sb64= sb64.replace("data:image/jpeg;base64,",''); 
        $.ajax({
            url:'jsonPHP.php',
            type: 'POST',
            processData: true, //false時,data參數無法傳到php POST接收端,true時才可以
            dataType: "json",
            //傳送data參數值
            data: { 'pid':$("#pid").val(),     
                    'sb64':sb64
                },
            success: function(data){
                console.log(data);
                //取回php回傳的陣列資料
                    var imgsNum=data.length;
                    for (i=0;i<imgsNum;i++){
                        imgid=data[i]['img_id'];
                        imgurl=data[i]['img_url'];
                        $("#info").append("id:"+imgid+"|url:"+imgurl);
                    }
                },
        });  
    });

PHP程式
- 取得前端傳遞的資料後,呼叫寫入資料的程式,再透過查詢回傳同個編號的圖片資料
- Insert_img 先將base64資料轉成圖片,我去抓一個時間當作檔名(這是另外引入的函式),再將資料存到資料庫
- query_img查詢同個ID的資料,存成陣列後回傳。


<?php
    header('Content-Type: application/json; charset=UTF-8');
    require_once("fundation_func.php");
    $link = new mysqli($dbhost,$dbuser,$dbpass,$db);

    //偵測POST的資料與前端ajax參數有關,要對應才行
    if ($_SERVER['REQUEST_METHOD'] == "POST"){
        @$id=$_POST["pid"];
        //@$name=$_POST["name"];
        @$sb64=$_POST["sb64"];
        $msg="取得pid:".$id;
        echo json_encode(insert_img($link, $id,$sb64));
    }else
    {
        $msg="request錯誤";
        echo json_encode(array(
            'msg'=> $msg
        ));
    }

    function insert_img($link,$product_id,$sb64){
        //產生圖片路徑
        $img_file=base64_decode($sb64);
        $file_name=get_pure_text(get_file_no());
        $file_url="product_imgs/".$product_id."_".$file_name.".jpg";
        file_put_contents($file_url, $img_file);

        //新增產品圖片資料的SQL
            $sql="INSERT INTO product_img(product_id, imgb, img_url) VALUES ('$product_id','$sb64','$file_url')";
            $link->query($sql);
        //查詢產品圖片
        return query_img($link,$product_id);
    }

//查詢同個ID的圖片函式,會回傳一個陣列
    function query_img($link,$product_id){
        $imgs_array=array(
            array('img_id','img_url'),
        );
        $sql="SELECT img_id, img_url FROM product_img WHERE product_id=$product_id";
        $result=$link->query($sql);
            $i=0;
            while($row=$result->fetch_array(MYSQLI_ASSOC)){
                //將查到的產品圖片存到array中
                $imgs_array[$i]=array(
                        'msg'=>"ss",
                        'img_id'=>$row['img_id'],
                        'img_url'=>$row['img_url']
                );
                $i++;
            }
            return $imgs_array;
    }
?>



2020年7月29日 星期三

JQuery/PHP 顯示上傳的圖片、取得php檔案路徑、隱藏圖片區塊、刪除圖片檔案

上傳圖片的功能與三種情境有關,整理作法如下:
1、 該頁面上無圖片,則隱藏圖片區塊,再上傳圖片後顯示預覽
2、該頁面已有圖片,則取得圖片路徑並顯示出來
3、刪除圖片後,隱藏圖片區塊

html:包含一個圖片區塊、一個上傳功能、一張圖片、一個刪除按鈕
<div class="img_col">
    <input id="upload" type="file" name="myfile">
    <img id="img_view" />
    <lable id="btn_del" class="btn_del" >刪除</label>           
</div>


JS:載入頁面時取得php的圖片路徑,若有則顯示圖片,若沒有則隱藏圖片區塊
<script>
    //當網頁載入時
    $(document).ready(function(){ 
        // 將php參數img_url指派給 JS 變數 img_view
        var img_view="<?php echo "$img_url" ?>";
        
        //當img_view有資料-> 圖片資料存在>顯示圖片、反之>隱藏區塊
        if (img_view){
            //以JQuery變更#img_view圖片的SRC參數為img_view
            $("#img_view").attr('src', img_view);
            //以JQuery指定刪除功能按鈕的Click事件,呼叫刪除圖片的函式(見後)
            $("#btn_del").click(function(e){
                del_img(img_view);
            });
        }else{
            //隱藏圖片區塊,及刪除功能按鈕
            $(".img_col").hide();
            $("#btn_del").hide();
        }
    });
</script>


JS:選擇圖片後,將圖片顯示為所選擇的圖 (參考來源資料)
<script>//選擇圖片後產生預覽
    //當input file的的upload變更時,呼叫readURL函式
    $("#upload").change(function() {
            readURL(this);

    function readURL(input) {
        //有可能圖片區塊這時被隱藏,因此先讓區塊顯示出來
        $(".edit_form_img").show();
        $("#btn_del").show();

        if (input.files && input.files[0]) {
            var reader = new FileReader();
                    
            reader.onload = function(e) {
                $('#img_preview').attr('src', e.target.result);
            }
               reader.readAsDataURL(input.files[0]); // convert to base64 string
            }
        }
    });
</script>


JS:刪除圖片函式
function del_img(img)//確認刪除圖片後,刪除圖片
    {
        if (confirm("確認刪除照片?"))
        //這邊將刪除寫在另一支php程式,並取得圖片路徑後將檔案刪除
        location.href="del_product_img.php?img="+img;
    }

PHP:刪除圖片php程式
- 資料庫連線部分就不寫了
- SQL將圖片的欄位update為空值
- 刪除圖片檔案


<?php 
    //取得傳入要刪除的圖片路徑
    $img_url=$_GET["img"];

    //將取得的檔案路徑 update為空值的SQL
    $img_del="UPDATE product set product_img=''  WHERE product_img='$img_url'";

    // 執行SQL (這段的$link是物件>$link = new mysqli($dbhost,$dbuser,$dbpass,$db))
    $result=$link->query($img_del);

    //將檔案自系統中刪除
    unlink($img_url);//將圖片檔案刪除
    
    //刪除後轉址到原頁面
    header("location:o_page.php");
?>



2020年7月28日 星期二

JQuery 滑動checkbox(Switch開關)寫入表單

使用JQuery做一個啟用、停用的切換switch,並將參數傳到表單中;
範例如下:

第一段JS:判斷PHP取自資料庫的參數,並呈現目前的狀態

<script>//檢查產品發佈狀態,顯示對應的publish狀態
        $(document).ready(function(){
           var publish=<?php echo"$is_publish" ?>;
           if (publish==0){
              $("#publish").prop("checked",'');
           }else{
              $("#publish").prop("checked",true);
           }
        });
</script>

HTML:表單中CheckBox的部分
- 由CSS去控制Checkbox樣式,讓他顯示成一個Switch開關
- 實際上是一個Chcekbox判斷是否有勾選
- 用onchange參數呼叫JS來寫入整個表單要傳給另一支php的參數
<!--Switch開關顯示html的部分-->
<label class="col_title">是否發布</lable>
<label class="switch">
    <input id="publish" type="checkbox" name="publish" onchange="check_publish()" >
    <span class="slider round"></span>
</label>


CSS:顯示如Switch開關的CSS
.switch {
    position: relative;
    display: inline-block;
    width: 60px;
    height: 34px;
  }
  
  /* Hide default HTML checkbox */
  .switch input {
    opacity: 0;
    width: 0;
    height: 0;
  }
  
  /* The slider */
  .slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    -webkit-transition: .4s;
    transition: .4s;
  }
  
  .slider:before {
    position: absolute;
    content: "";
    height: 26px;
    width: 26px;
    left: 4px;
    bottom: 4px;
    background-color: white;
    -webkit-transition: .4s;
    transition: .4s;
  }
  
  input:checked + .slider {
    background-color: #2196F3;
  }
  
  input:focus + .slider {
    box-shadow: 0 0 1px #2196F3;
  }
  
  input:checked + .slider:before {
    -webkit-transform: translateX(26px);
    -ms-transform: translateX(26px);
    transform: translateX(26px);
  }
  
  /* Rounded sliders */
  .slider.round {
    border-radius: 34px;
  }
  
  .slider.round:before {
    border-radius: 50%;
  }



第二段JS:根據checkbox狀態,寫入要傳到表單的值(非必要)
*checkbox勾選時預設value為on,否則就是空值
*因此接收表單的程式只要判斷有沒有回傳值,再寫入對應的資料即可
-以下是變更on為a,若後端要特定數值可參考

<script>
//檢查發布CheckBox是否被勾選,寫入特定值
        function check_publish(){  
            if($("#publish").is(':checked'))
                $("#publish").val('a');
        }
 </script>