2

I'm trying to update a database using javascript and PHP, this is my index.html code:

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
    <input type="text" id="descriptioninput">
    <input type="number" id="budgetin">
    <input type="number" id="budgetout">
    <button type="button" onclick="addToDB()">Add to database</button>

    <script>
        function addToDB()
        {
            var descriptioninput = document.getElementById('descriptioninput').value;
            var budgetin = document.getElementById('budgetin').value;
            var budgetout = document.getElementById('budgetout').value;

            $.ajax ( {
                type: 'POST',
                url: 'addtodb.php',
                data:{descriptioninput:descriptioninput, budgetin:budgetin, budgetout:budgetout},
                success:function (data) {
                    // Completed successfully
                    alert('success!');
                }
            });
    </script>
</body>
</html>

Here's my addtodb.php code:

<?php

$host = "localhost";
$username = "root";
$password = "";
$dbname = "budgetdb";

$conn = new mysqli($host, $username, $password, $dbname);
if ($conn === TRUE)
{
$descriptioninput = $_GET['descriptioninput'];
$budgetin = $_GET['budgetin'];
$budgetout = $_GET['budgetout'];

$query = "INSERT INTO budget (description, budgetin, budgetout) VALUES ('$descriptioninput', '$budgetin', '$budgetout')";

$conn->query($query);

$conn->close();
}

?>

But it appears as if my PHP script doesn't run. No changes appear in my database. I've tried to do warning() in the PHP file and alert it it using.done(function(text)), but nothing is displayed.

4
  • 1
    Yeah it seems like it didn't go inside if condition. First see what comes inside $conn when db connected successfully. Commented Oct 20, 2015 at 7:17
  • 1
    can u use developer console or firebug (on firefox) or something like that to see what is happening? And also test your server side code first. Commented Oct 20, 2015 at 7:17
  • $conn !== true, $conn == true - that's the problem. mysqli_connect does not return true. Commented Oct 20, 2015 at 7:18
  • First write echo inside if to confirm is condition meets. Commented Oct 20, 2015 at 7:28

4 Answers 4

2

This is happening because you are doing the ajax request using POST method in js but you are trying to get the variables using the GET method in PHP. Switch it to GET and it will work.

Be aware of SQL Injection. You can prevent it either by using prepared statements or escaping the string as:

$descriptioninput = $conn->real_escape_string($_GET['descriptioninput']);

Also, the first if condition is not valid. You just need to do it like if ($conn) instead of if ($conn === TRUE)

Sign up to request clarification or add additional context in comments.

7 Comments

Tried doing that, but nothing happens in the database. I even tried writing the url manually in chrome. I also changed the type to GET now.
It works now, something was wrong with the SQL syntax it appears, after I removed the () before VALUES, it worked. I'll have a look at it
There's nothing wrong with the sql syntax.. depends on what you are trying to save in db.. use the real_escape_string to assure there are no wrong chars sent for db
@MuhammadMuazzam I tried to run the SQL query directly in PhpMyAdmin, which failed. Then I removed (description, budgetin, budgetout) and it ran successfully in PhpMyAdmin, so I did the same in my PHP file which made it work.
Indeed, perhaps description is a reserved keyword and should be avoided for column names?
|
1

I could be wrong but i believe description may be a reserved keyword in mySQL. try encapsing it

INSERT INTO budget (`description`, `budgetin`, `budgetout`) VALUES ('$descriptioninput', '$budgetin', '$budgetout')

Comments

1

Change ajax type to GET

$.ajax ( {
type: 'GET',
url: 'addtodb.php',
data:{descriptioninput:descriptioninput, budgetin:budgetin, budgetout:budgetout},
success:function (data) {
// Completed successfully
alert('success!');
}
});

Comments

0

its a little messy with your mix between ajax and JS. Try using this getHTTP function for regular JS.

function httpGet(theUrl){
	//FETCH Data From Server
	xmlhttp=new XMLHttpRequest();
	xmlhttp.open("GET", theUrl , false );
	xmlhttp.send();   
	return xmlhttp.responseText;
}

then just build your url as +addtodb.php?param1="+param1value+"&param2="+param2value

1 Comment

appologize. I am without sleep i was miss thinking ajax as jquery. I am not verry knowledgeable in ajax but the above is how i accomplish calling a PHP file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.