简体   繁体   English

用ajax和php更新mysql(使用jquery)

[英]update mysql with ajax and php (using jquery)

The code below is responsible for updating a column of a MySQL database with the selected status. 下面的代码负责使用所选状态更新MySQL数据库的列。 After selecting the status, the user clicks the submit button and the query is executed. 选择状态后,用户单击提交按钮,然后执行查询。 However, to display the new status on the screen, it is necessary to refresh the page. 但是,要在屏幕上显示新状态,必须刷新页面。

I read a bit about AJAX and I think it's possible to put the PHP script aside and send the information with AJAX so that the new status changes after the user clicks the "Change" button, without refresh the page. 我了解了一些有关AJAX的知识,并且认为可以将PHP脚本放在一边,并使用AJAX发送信息,以便用户单击“更改”按钮后新状态发生更改,而无需刷新页面。

I learned how to send text variables through AJAX, but I also need to send the checkbox selection. 我学习了如何通过AJAX发送文本变量,但是我还需要发送复选框选择。

Would anyone know how to write AJAX code? 有谁知道如何编写AJAX代码?

//the select where the user set the status

    <label>Selecione o status:</label>
    <select name="changePed">
        <option value="separacao">Em Separação</option>
        <option value="separado">Separado</option>
        <option value="faturado">Faturado</option>
        <option value="exp">Expedido</option>
        <option value="entrg">Mercadoria Entregue</option>
        <option value="cancelado">Cancelado</option>            
    </select>
    <button type="submit" >Alterar</button>
<?php
    echo "<table id='pedidos' class='table table-hover table-responsive'>
            <thead>
              <tr>
                <th><input type='checkbox' name='select-all' id='select-all' /></th>
                <th>Data</th>
                <th>EMS</th>
                <th>Pedido do  cliente</th>
                <th>Cliente</th>
                <th>Valor</th>
                <th>Aut. Comercial</th>
                <th>Status</th>
                <th>Nota Fiscal</th>
              </tr>
            </thead>";
            while($row = mysqli_fetch_array($resultFIL))
            {
            $dataped = $row['emissaoPed'];
              $valorped = $row['vlr'];
              echo "<tbody><tr>";
              echo "<td><input name='checkbox[]' type='checkbox' value=" . $row['id'] . "></td>";
              echo "<td>" . date('d/m/Y', strtotime($dataped)) . "</td>";
              echo "<td><a id='ver_pedido' data-ref=".$row['nPedido']." data-toggle='modal' id='abremodal' href='#myModal'>" . $row['nPedido'] . "</a></td>";
              echo "<td>" . $row['NrPedido'] . "</td>";
              echo "<td>" . $row['nomeAbrev'] . "</td>";
              echo "<td>" . number_format($valorped, 2, ',', '.') . "</td>";
              echo "<td><input type='button' value='Autorizado' name='autCom' ></td>";
              echo "<td>" . $row['status'] . "</td>";
              echo "<td><input type='text' placeholder='0012345' style='width: 70px;'>&nbsp<button type='submit' class='btn'><i class='fa fa-check' aria-hidden='true'></i></button></td> ";
              echo "</tr></tbody>";


}
 echo "</table>";
?>
 <?php 
 //The current php script that executes the query to update the database

        switch($_POST['changePed']){
            case 'separacao':
            function filter( $dados ){
                $arr = Array();
                foreach( $dados AS $dado ) $arr[] = (int)$dado;
                return $arr;
            }     
            if(isset($_POST['checkbox'])){
                $arr = filter( $_POST['checkbox'] );
                $sql = 'UPDATE pedidos SET status="Em separação" WHERE id IN('.implode( ',', $arr ).')';
                $result = mysqli_query($connect,$sql);
            }
            break;
            case 'cancelado':
            function filter( $dados ){
                $arr = Array();
                foreach( $dados AS $dado ) $arr[] = (int)$dado;
                return $arr;
            }     
            if(isset($_POST['checkbox'])){
                $arr = filter( $_POST['checkbox'] );
                $sql = 'UPDATE pedidos SET status="Cancelado" WHERE id IN('.implode( ',', $arr ).')';
                $result = mysqli_query($connect,$sql);
            }
            break;
            case 'faturado':
            function filter( $dados ){
                $arr = Array();
                foreach( $dados AS $dado ) $arr[] = (int)$dado;
                return $arr;
            }     
            if(isset($_POST['checkbox'])){
                $arr = filter( $_POST['checkbox'] );
                $sql = 'UPDATE pedidos SET status="Faturado" WHERE id IN('.implode( ',', $arr ).')';
                $result = mysqli_query($connect,$sql);
            }
            break;
            case 'exp':
            function filter( $dados ){
                $arr = Array();
                foreach( $dados AS $dado ) $arr[] = (int)$dado;
                return $arr;
            }     
            if(isset($_POST['checkbox'])){
                $arr = filter( $_POST['checkbox'] );
                $sql = 'UPDATE pedidos SET status="Expedido" WHERE id IN('.implode( ',', $arr ).')';
                $result = mysqli_query($connect,$sql);
            }
            break;
            case 'exc':
            function filter( $dados ){
                $arr = Array();
                foreach( $dados AS $dado ) $arr[] = (int)$dado;
                return $arr;
            }     
            if(isset($_POST['checkbox'])){
                $arr = filter( $_POST['checkbox'] );
                $sql = 'DELETE FROM pedidos WHERE id IN('.implode( ',', $arr ).')';
                $result = mysqli_query($connect,$sql);
            }
            break;
            case 'entrg':
            function filter( $dados ){
                $arr = Array();
                foreach( $dados AS $dado ) $arr[] = (int)$dado;
                return $arr;
            }     
            if(isset($_POST['checkbox'])){
                $arr = filter( $_POST['checkbox'] );
                $sql = 'UPDATE pedidos SET status="Mercadoria Entregue" WHERE id IN('.implode( ',', $arr ).')';
                $result = mysqli_query($connect,$sql);
            }
            break;
            case 'separado':
            function filter( $dados ){
                $arr = Array();
                foreach( $dados AS $dado ) $arr[] = (int)$dado;
                return $arr;
            }     
            if(isset($_POST['checkbox'])){
                $arr = filter( $_POST['checkbox'] );
                $sql = 'UPDATE pedidos SET status="Separado" WHERE id IN('.implode( ',', $arr ).')';
                $result = mysqli_query($connect,$sql);
            }
            break;
        };
        ?>

I tried this code but it did not work: 我尝试了这段代码,但是没有用:

function altera_status()
{

//get the datas on respective fields
var dadosajax = {
    'changePedi' : $("#changePed").val(),
    'checkbox' : $(".checkped").val(),
};
pageurl = 'status.php';
//page where is the php script

$.ajax({

    //url of actual page
    url: pageurl,
    data: dadosajax,
    type: 'POST',
    //cache
    cache: false,
    //if get an error on call
    error: function(){
        alert('Erro: Inserir Registo!!');
    },
    //response of data sended
    success: function(response)
    { 

    }
});

} }

And the status.php is this 而status.php是这个

  <?php  
               //Conexão à base de dados
             $connect = mysqli_connect("localhost","root","", "table_orders") or die ("Forninho fall"); 

               //recebe os parâmetros

             $change = $_REQUEST['changePedi'];
             $checki = $_REQUEST['checki'];
             print_r($change );
             switch($change){
                case 'separacao':
                function filter( $dados ){
                    $arr = Array();
                    foreach( $dados AS $dado ) $arr[] = (int)$dado;
                    return $arr;
                }     
                if(isset($checki)){
                    $arr = filter( $checki );
                    $sql = 'UPDATE pedidos SET status="Em separação" WHERE id IN('.implode( ',', $arr ).')';
                    $result = mysqli_query($connect,$sql);
                }
                break;
                case 'cancelado':
                function filter( $dados ){
                    $arr = Array();
                    foreach( $dados AS $dado ) $arr[] = (int)$dado;
                    return $arr;
                }     
                if(isset($_POST['checkbox'])){
                    $arr = filter( $_POST['checkbox'] );
                    $sql = 'UPDATE pedidos SET status="Cancelado" WHERE id IN('.implode( ',', $arr ).')';
                    $result = mysqli_query($connect,$sql);
                }
                break;
                case 'faturado':
                function filter( $dados ){
                    $arr = Array();
                    foreach( $dados AS $dado ) $arr[] = (int)$dado;
                    return $arr;
                }     
                if(isset($_POST['checkbox'])){
                    $arr = filter( $_POST['checkbox'] );
                    $sql = 'UPDATE pedidos SET status="Faturado" WHERE id IN('.implode( ',', $arr ).')';
                    $result = mysqli_query($connect,$sql);
                }
                break;
                case 'exp':
                function filter( $dados ){
                    $arr = Array();
                    foreach( $dados AS $dado ) $arr[] = (int)$dado;
                    return $arr;
                }     
                if(isset($_POST['checkbox'])){
                    $arr = filter( $_POST['checkbox'] );
                    $sql = 'UPDATE pedidos SET status="Expedido" WHERE id IN('.implode( ',', $arr ).')';
                    $result = mysqli_query($connect,$sql);
                }
                break;
                case 'exc':
                function filter( $dados ){
                    $arr = Array();
                    foreach( $dados AS $dado ) $arr[] = (int)$dado;
                    return $arr;
                }     
                if(isset($_POST['checkbox'])){
                    $arr = filter( $_POST['checkbox'] );
                    $sql = 'DELETE FROM pedidos WHERE id IN('.implode( ',', $arr ).')';
                    $result = mysqli_query($connect,$sql);
                }
                break;
                case 'entrg':
                function filter( $dados ){
                    $arr = Array();
                    foreach( $dados AS $dado ) $arr[] = (int)$dado;
                    return $arr;
                }     
                if(isset($_POST['checkbox'])){
                    $arr = filter( $_POST['checkbox'] );
                    $sql = 'UPDATE pedidos SET status="Mercadoria Entregue" WHERE id IN('.implode( ',', $arr ).')';
                    $result = mysqli_query($connect,$sql);
                }
                break;
                case 'separado':
                function filter( $dados ){
                    $arr = Array();
                    foreach( $dados AS $dado ) $arr[] = (int)$dado;
                    return $arr;
                }     
                if(isset($_POST['checkbox'])){
                    $arr = filter( $_POST['checkbox'] );
                    $sql = 'UPDATE pedidos SET status="Separado" WHERE id IN('.implode( ',', $arr ).')';
                    $result = mysqli_query($connect,$sql);
                }
                break;
             };

             ?>

Here is my code. 这是我的代码。

 $('#SubBtn').click(function(){ var checkboxValues = $.map($('.checkbox:checked'), function(e){ return $(e).val(); }).join(); $.ajax({ url: '', method: 'POST', data: { changePed: $('[name=changePed]').val(), checkbox: checkboxValues, } }).done(function(result){ alert('success'); }).fail(function(){ alert('error'); }); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <label>Selecione o status:</label> <select name="changePed"> <option value="separacao">Em Separação</option> <option value="separado">Separado</option> <option value="faturado">Faturado</option> <option value="exp">Expedido</option> <option value="entrg">Mercadoria Entregue</option> <option value="cancelado">Cancelado</option> </select> 1<input type="checkbox" class="checkbox" value="1"> 2<input type="checkbox" class="checkbox" value="2"> 3<input type="checkbox" class="checkbox" value="3"> <button type="submit" id="SubBtn">Alterar</button> 

If you want pass a list value by AJAX, you can join it by JavaScript at first. 如果要通过AJAX传递列表值,则可以首先通过JavaScript加入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM