Skip to content Skip to sidebar Skip to footer

Return Response From Php To Jquery Using Ajax

I am submitting info to be saved in a MySQL database using Jquery/AJAX and PHP. This is what i've done so far: function Addinfo() { var ew = document.getElementById('ew').value

Solution 1:

Jquery: (main.js file)

$(document).ready(function(){

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

        $.ajax({
            // give your form the method POSTtype: $(this).attr('method'),
            // give your action attribute the value ajaxadd.phpurl: $(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 resultif(!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 (ajaxadd.php file)

<?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 valuesforeach ($inputvaluesas$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 resultswhile($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 requestecho json_encode(['result' => $returnResult, 'errors' => $errors]);

    exit;
?>

HTML:

<!doctype html><htmlclass="no-js"lang=""><head><metacharset="utf-8"><metahttp-equiv="x-ua-compatible"content="ie=edge"><title>Ajax form submit</title><metaname="description"content=""><metaname="viewport"content="width=device-width, initial-scale=1"></head><body><formclass="ajaxform"action="ajaxadd.php"method="POST"><inputtype="text"name="ew1" /><inputtype="text"name="mw" /><buttontype="submit">Submit via ajax</button></form><divid="message1"></div><scriptsrc="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><scriptsrc="main.js"></script></body></html>

Solution 2:

$.ajax({type:"POST",url:"ajaxadd.php",ew1:ew,mw1:mw,data:dataString,dataType:'text',cache:false,})

Solution 3:

In PHP code at the end where you

echo $aircraft change it to echo json_encode($aircraft); and in AJAX fucntion where you mentioned

cache:false include success:function(response){alert response;}

It will give your aircraft variable value in AJAX function. Good Luck!

Solution 4:

You should modify your php code as below instead of directly return mysql_fetch_assoc because it returns only the first row of your SQL result.

<?php$ew2 = $_POST['ew1'];
$mw2 = $_POST['mw1'];
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("tp", $connection);

if (isset($_POST['ew1']))
{
    $result = array();
    $query = mysql_query("insert into table(ew, mw) values ('$ew2', '$mw2')");
    $addresult = mysql_query("SELECT * FROM `table` WHERE `ew` = '" . $_POST['ew1'] . "' ORDER BY `id` DESC LIMIT 1");
    while($aircraft = mysql_fetch_assoc($addresult))
    {
        $result[] = $aircraft;
    }
    #echo $aircraft; // wait until whole result is collectedecho json_encode($result);
}

mysql_close($connection); // Connection Closed?>

Also you should edit your javascript code as below;

functionAddinfo() {
    var ew = document.getElementById("ew").value;
    var mw = document.getElementById("mw").value;
    var dataString = 'ew1=' + ew + '&mw=' + mw;
    if (ew == '' || mw == '') {
        alert("Please Fill All Fields");
    } else {
        $.ajax({
            type : "POST",
            url : "ajaxadd.php",
            data : dataString,
            dataType : 'text',
            cache : false,
            success: function(data)
            {
                //$('#message1').html(data);alert(data);
            },
            error: function(data)
            {
                alert("Error");
            }
        });
    }
    returnfalse;
}

In addition advice you may check $connection and $db for successful initialization of your database connection and database selection, and again an advice for your php code your should use mysqli extension instead of mysql extension which deprecated. You can just replace mysql part of your calling methods with mysqli. Also @RakhalImming's advice is quite good for security of your code.

Post a Comment for "Return Response From Php To Jquery Using Ajax"