robk27
robk27

Reputation: 693

AJAX post to database

I have looked at other questions and cannot find the answer to why this isn't working. I am following a tutorial online. Here is my code:

HTML file:

<!DOCTYPE HTML>
<html>
<head>
<title>AJAX Test</title>
</head>
<body>
<h4>Enter an Item</h4>
<input type="text" id="item" /><br />
<input type="button" id="button" value="Submit" /><br />
<div id="content"></div>
<script type="text/javascript" scr="ajax.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
</body>
</html>

JS file:

$('#button').click(function() {
var item = $('#item').val();

$('#content').text('Loading...');

$.post('ajax.php', { item: item }, function(data) {
    $('#content').text(data);
    });
});

PHP file:

<?php
include 'db.php';

if (isset($_POST['item'])) {
    $item = $_POST['item'];
    $sql = mysql_query("INSERT INTO items(item)VALUES('$item')");
    if ($sql === true) {
        echo "Inserted into database";
    } elseif ($sql ==== false) {
        echo "Error inserting into database";
    }
 }
 ?>

I don't see what I'm doing wrong. The tutorial has the same code. Thanks for your help.

Upvotes: 0

Views: 1149

Answers (3)

Aless
Aless

Reputation: 53

Well i dont know if i can help you:

You have some mistakes on your code

  1. The elseif condition is not ====(4) just ===(3)

  2. The ajax.js file should be after the jquery library

  3. The src attribute is not scr.

  4. And of course the URL of the jquery library should start with http:// because is an external resource.

  5. The mysql_query() function should have the conection variable, Example:
    mysql_query("[query here]", $connect);

Upvotes: 1

Simon
Simon

Reputation: 242

moonwave99 is right (I'm not sure why the downvotes).. and also the scr="ajax" should be src="ajax" in your html and should be put in head or even before. Other reason may be the position of ajax.php to the site, maybe declaring whole URL will help :

$.post('http://wholeurl/ajax.php', { 
      item: item 
   }, function(data) {
      $('#content').text(data);
   });

Hope this helps, if not please specify error.

Upvotes: 1

moonwave99
moonwave99

Reputation: 22817

Beside any other error you may get, you should import jQuery before your script:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>    
<script type="text/javascript" src="ajax.js"></script>

Upvotes: 0

Related Questions