sql >> Base de Datos >  >> RDS >> Mysql

Devuelve la respuesta de PHP a Jquery usando Ajax

Jquery:(archivo main.js)

$(document).ready(function(){

    $('.ajaxform').on('submit', function(e){
        e.preventDefault();

        $.ajax({
            // give your form the method POST
            type: $(this).attr('method'),
            // give your action attribute the value ajaxadd.php
            url: $(this).attr('action'),
            data: $(this).serialize(),
            dataType: 'json',
            cache: false,
        })
        .success(function(response) {
            // remove all errors
            $('input').removeClass('error').next('.errormessage').html('');

            // if there are no errors and there is a result
            if(!response.errors && response.result) {
                // success
                // loop through result and append values in message1 div
                $.each(response.result, function( index, value) {
                    $('#message1').append(index + ': ' + value + '<br/>');
                });

            } else {

                // append the error to the form
                $.each(response.errors, function( index, value) {
                    // add error classes
                    $('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
                });

            }
        });

    });

});

PHP (archivo ajaxadd.php)

<?php
    // assign your post value
    $inputvalues = $_POST;

    // assign result vars
    $errors = false;
    $returnResult = false;

    $mysqli = new mysqli('host', "db_name", "password", "database");

    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }

    // escape your values
    foreach ($inputvalues as $key => $value) {
        if(isset($value) && !empty($value)) {
            $inputvalues[$key] = htmlspecialchars( $mysqli->real_escape_string( $value ) );
        } else {
            $errors[$key] = 'The field '.$key.' is empty';
        }
    }

    if( !$errors ) {

        // insert your query
        $mysqli->query("
            INSERT INTO `table`(`ew`, `mw`) 
            values ('".$inputvalues['ew1']."', '".$inputvalues['mw']."')
        ");

        // select your query
        // this is for only one row result
        $addresult = "
            SELECT * 
            FROM `table` 
            WHERE `ew` = '".$inputvalues['ew1']."' 
            ORDER BY `id` DESC
            LIMIT 1
        ";

        if( $result = $mysqli->query($addresult) ) {
            // collect results
            while($row = $result->fetch_assoc())
            {
                // assign to new array
                // make returnResult an array for multiple results
                $returnResult = $row;
            }
        }
    }

    // close connection
    mysqli_close($mysqli);

    // print result for ajax request
    echo json_encode(['result' => $returnResult, 'errors' => $errors]);

    exit;
?>

HTML:

<!doctype html>
<html class="no-js" lang="">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>Ajax form submit</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>


        <form class="ajaxform" action="ajaxadd.php" method="POST">

            <input type="text" name="ew1" />
            <input type="text" name="mw" />

            <button type="submit">Submit via ajax</button>

        </form>

        <div id="message1"></div>

        <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
        <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.12.0.min.js"><\/script>')</script>
        <script src="main.js"></script>
    </body>
</html>