简体   繁体   中英

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. 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.

I learned how to send text variables through AJAX, but I also need to send the checkbox selection.

Would anyone know how to write AJAX code?

//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

  <?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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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