AJAX post to database

白昼怎懂夜的黑 提交于 2020-01-06 18:08:49

问题


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.


回答1:


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.




回答2:


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);




回答3:


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>


来源:https://stackoverflow.com/questions/13221200/ajax-post-to-database

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!