Bartram Wallace
Bartram Wallace

Reputation: 9

try to send ajax post request to php to db but got an error

I better show everything because I've no idea where it went wrong.. I'm very sure my database / tables are correctly connected.. but it still return error..

html

<!doctype html>
<html lang="en">
<head>
    <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript" src="main.js"></script>

    <meta charset="UTF-8">
    <title>Ajax Example</title>
</head>
<body>
    <ul>
        <li class='item'>item 1</li>
    </ul>
        <a href="#" id='btn'>Add</a>

    <br /><input type='text' id='input'>

</body>
</html>

js

$(document).ready(function(){

$('#input').hide();

$('#btn').click(function () {
    $(this).hide();
    $('#input').show().focus().val('');

});

$('#input').blur(function () {

    var userInput = $('#input').val().trim();
    if (userInput !== "") {
        var text = $(this).val().charAt(0).toUpperCase() + $(this).val().substring(1); // to uppercase first letter
        $('#btn').show();
        $('#input').hide();

        $.ajax({
          type: "POST",
          url: "send.php",
          data: { item : text }
        })
          .done(function( data ) {
            if(data == 1)
                alert('data inserted');
            else
                alert('error');
          });

        appendTab = "<li class='item'>" + text + "</li>"

        $('ul').append(appendTab);
    }
    else {
            $('#btn').show();
            $('#input').hide();
    }
});

});

php

<?php

$data = mysqli_real_escape_string($_POST['item']);

$conn = mysqli_connect("localhost","root","");
mysqli_select_db($conn, "ajaxExample");

$q = "INSERT INTO user (userList) VALUES ('$data')";
if(mysqli_query($conn, $q)){

echo 1;

}

?>

I use wamp and hv a mysql database, I think I can still use mysqli?

Upvotes: 0

Views: 116

Answers (1)

zzlalani
zzlalani

Reputation: 24384

In your php you cannot use mysqli_real_escape_string function before a valid mysql connection

What you need to do just put mysqli_real_escape_string after mysqli_connect function and this is probably your error

<?php

$conn = mysqli_connect("localhost","root","");

$data = mysqli_real_escape_string($_POST['item']);
mysqli_select_db($conn, "ajaxExample");

$q = "INSERT INTO user (userList) VALUES ('$data')";
if(mysqli_query($conn, $q)){

echo 1;

}

?>

Upvotes: 2

Related Questions