简体   繁体   中英

Using ajax and php to insert data to MySQL

I feel like I'm probably about 90% of the way there, and just need some help with that last 10%. I've looked at a number of different examples, and tried to piece together a solution, but haven't figured it out, so I'm looking for some guidance.

I have a small html page, with a little javascript, and a short .php that is adding the received data to a database.

I can see that the code is getting into the ajax function, and then into the insert function. But it's not actually doing the insert. I suspect that it's never sending the data off to the php file, but I don't know that for sure.

Here's the html code:

    <html>
    <head>
        <script type ="text/javascript" language="javascript">
            function ajaxFunction(){
                var ajaxRequest;
                    alert("enter ajax"); //just a testing line
                try{
                    ajaxRequest = new XMLHttpRequest();
                } catch (e) {
                    try {
                        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
                    } catch (e) {
                        try {
                            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (e) {
                            alert("Your browser broke!");
                            return false;
                        }
                    }
                }

            ajaxRequest.onreadystatechange = function(){
                if(ajaxRequest.readyState == 4){
                    var ajaxDisplay = document.getElementById('responseDiv');
                    ajaxDisplay.innerHTML = ajaxRequest.responseText;
                        }
                }

                alert("enter insert");  //just for testing
                var type = $('#type').val();
                var vintner = $('#vintner').val();

                var myData = {"type": type, "vintner": vintner,};

                $.ajax({
                    url: "bottleAdd.php",
                    type: "POST",
                    data: "myData",
                    success: function(data, status, xhr)
                    {
                        $("$bottleAdd").html(data);
                        $("type").val();
                        $("vintner").val();
                        }
                });
            }

        </script>

        <title>Simple Add</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
    </head>
    <body>
        <div id="addBottle">
            <table>
                <tr>
                    <td>Type: <input type="text" id="type" /></td>
                    <td>Vintner: <input type="text" id="vintner" /></td>
                </tr>
                <tr>
                    <td><button onClick="ajaxFunction()">Save Bottle Now</button></td>
                </tr>
            </table>
        </div>
        <div id="responseDiv">Response will appear here</div>
    </body>
</html>

And here's the php

<?php
require_once 'login.php';
$conn = mysqli_connect($db_hostname, $db_username, $db_password, $db_database) or die("Connection failed: " . mysqli_connect_error());

$wineType = $_POST['type'];
$vintner = $_POST['vintner'];

$sql = "INSERT INTO bottleSimple (winetype, vintner)"
        . " values ('$wineType', '$vintner')";

if (mysqli_query($conn, $sql)) {
    echo "Successfully Inserted";
} else {
    echo "Insertion Failed<br />";
    echo $sql;
}
?>

I know there are some things to do in the php (prevent sql injection for example). But right now, I'm less concerned about that, and more about just figuring out how to get this to run correctly.

Any help would be appreciated.

Thank you.

You mixed plain JS AJAX with jQuery's ajax wrapper.

Change your code to the following:

<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width">
    <title>Simple Add</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script type ="text/javascript" language="javascript">
        var type = $('#type').val();
        var vintner = $('#vintner').val();
        var myData = {"type": type, "vintner": vintner};
        $.ajax({
            url: "bottleAdd.php",
            type: "POST",
            data: myData,
            success: function(data) {
                $("#responseDiv").html(data);
            }  
        });
    </script>
</head>

The rest is without a change.

That way you will use jQuery AJAX.

By the way, it is a good practice to place meta tags a the beginning of your head tag, because tag like the charset will cause the browser to start reading your page again from the beginning.

You mixed two invoke methods of XHR - the native method and jQuery method. If You go for native method with creating native xhr objct, You should operate only with the ajaxRequest variable which keeps the native XHR object. The solution is remove the code staring with

$.ajax

and, after define the onstatechange event, add Your request params, and finnaly send your xhr. So:

function ajaxFunction() {
        var ajaxRequest;
        try {
            ajaxRequest = new XMLHttpRequest();
        } catch (e) {
            try {
                ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {
                    alert("Your browser broke!");
                    return false;
                }
            }
        }

        ajaxRequest.onreadystatechange = function () {
            if (ajaxRequest.readyState === 4) {

                var data = ajaxRequest.responseText;
                console.log(data);
                // do something with response data...
            }
        }

        var type = 'atype';
        var vintner = 'avintner';


        var formData = new FormData();
        formData.append("type", type);
        formData.append("vintner", vintner);
        ajaxRequest.open('POST', 'bottleAdd.php', true); 
        ajaxRequest.send(formData);

    }

should work.

Try this: you may wrong use this code "mydata" it change to mydata ..

for see result look in console.

  function ajaxFunction() { var ajaxRequest; alert("enter ajax"); //just a testing line try { ajaxRequest = new XMLHttpRequest(); } catch (e) { try { ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser broke!"); return false; } } } ajaxRequest.onreadystatechange = function() { if (ajaxRequest.readyState == 4) { var ajaxDisplay = document.getElementById('responseDiv'); ajaxDisplay.innerHTML = ajaxRequest.responseText; } } alert("enter insert"); //just for testing var type = $('#type').val(); var vintner = $('#vintner').val(); var myData = { "type": type, "vintner": vintner, }; $.ajax({ url: "http://stackoverflow.com/index.php", type: "POST", data: myData, success: function(data, status, xhr) { $("$bottleAdd").html(data); $("type").val(); $("vintner").val(); } }); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <html> <head> <title>Simple Add</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width"> </head> <body> <div id="addBottle"> <table> <tr> <td>Type: <input type="text" id="type" /> </td> <td>Vintner: <input type="text" id="vintner" /> </td> </tr> <tr> <td> <button onClick="ajaxFunction()">Save Bottle Now</button> </td> </tr> </table> </div> <div id="responseDiv">Response will appear here</div> </body> </html> 

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