php 使用 Jquery/ajax 将数据发送到数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18722028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:05:47  来源:igfitidea点击:

Sending data to database using Jquery/ajax

phpjavascriptjqueryhtmlajax

提问by Roald Van Der Tempel

I've been trying to put up my form but I keep getting stuck. I got it to work with jquery disabled. But if I turn Jquery on it does not send anything. (Without errors in my element inspection)

我一直在尝试填写表格,但我一直被卡住。我让它在禁用 jquery 的情况下工作。但是,如果我打开 Jquery,它不会发送任何内容。(在我的元素检查中没有错误)

I've been on it for a while now and I tried different solutions (a few from different topics here on Stack overflow) but I keep getting to the same point. It might be something on the server side but I keep thinking that if that would be the case it shouldn't work at all. Does anyone might have an idea?

我已经研究了一段时间,我尝试了不同的解决方案(一些来自堆栈溢出的不同主题),但我一直在同一点上。这可能是服务器端的问题,但我一直在想,如果是这种情况,它根本不应该工作。有没有人可能有想法?

The link: http://www.volunteeringnews.com/osf.php

链接:http: //www.volunteeringnews.com/osf.php

The codes:

代码:

Client side: osf.php

客户端:osf.php

<?php include("osb.php");?>
<link href="css/styles.css" rel="stylesheet">
<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type = "text/javascript">

$(function(){

$('#submit').click(function(){
 $('#container').append('<img src = "img/ajax/ajax-loader.gif" alt="Currently loading" id = "loading" />');

    var name=$("#name").val();
    var continent=$("#continent").val();
    var country=$("#country").val();
    var website=$("#website").val();
    var email=$("#email").val();
    var nameorg=$("#nameorg").val();
    var category=$("#category").val();
    var price=$("#price").val();
    var currency=$("#currency").val();
    var description=$("#description").val();
    var wanted=$("#wanted").val();
    var expectation=$("#expectation").val();
    var extra=$("#extra").val();


     $.ajax({

        url: 'osb.php',
        type: 'POST',
        data: 'name =' + name + '&continent=' + continent + '&country=' + country + '&website=' + website + '&email=' + email + '&nameorg=' + nameorg + '&category=' + category + '&price=' + price + '&currency=' + currency + '&description=' + description + '&wanted=' + wanted + '&expectation=' + expectation + '&extra=' + extra,


        success: function(result){
             $('#response').remove();
             $('#container').append('<p id = "response">' + result + '</p>');
             $('#loading').fadeOut(500, function(){
                 $(this).remove();

             });

        }

     });         

    return false;

});


});

</script>



<!--we have our html form here where user information will be entered-->
<form action='osb.php' method='post' border='0'>
<div id = "container">  <br>
    <label>Name:            </label>    <input type='text' id="name" name='name' /><br>  <br>
    <label>Continent:       </label>    <select id="continent" name="continent"> <option>Africa</option><option>America</option><option>Asia</option> <option>Australia</option><option>Europe</option></select><br><br>
    <label>Country:         </label>    <input type='text' id="country" name='country' /><br><br>
    <label>Website:         </label>    <input type='text' id="website" name='website' /><br><br>
    <label>E-mail:          </label>    <input type='text' id="email" name='email' /><br><br><br>
    <label>Organisation:    </label>    <input type='text' id="nameorg" name='nameorg' /><br><br>
    <label>Category:        </label>    <input type='text' id="category" name='category' /><br><br>
    <label>Price per week:  </label>    <input type='text' id="price" name='price' /><br><br>
    <label>Currency:        </label>    <select id ="currency"  name="currency" >  <option> EUR </option> <option> DOL </option> <option> GBP </option></select><br><br>
    <label>Description:     </label>    <textarea id="description" rows="5" cols="40"  placeholder="Describe what kind of volunteer is welcome" name='description'/></textarea><br><br>
    <label>Wanted:          </label>    <textarea id="wanted" rows="5" cols="40"  placeholder="Describe what kind of volunteer is welcome" name='wanted'/></textarea><br><br>
    <label>Expectation:     </label>    <textarea id="expectation" rows="5" cols="40"  placeholder="Describe what a volunteer can expect"  name='expectation'/></textarea><br><br>
    <label>Extra:           </label>    <textarea id="extra" rows="5" cols="40"  placeholder="Describe what a volunteer can expect"  name='extra'/></textarea><br><br>

    <input type='hidden' name='action' value='create' />
    <input type='submit' value='Submit' id="submit" value = "send feedBack"/>
    <input type="reset" value="Reset" class="reset-org">

    <a href='index.php'>Back to index</a> 

The server side: osb.php

服务器端:osb.php

<?php
//set connection variables
$host = "";
$username = "";
$password = "";
$db_name = ""; //database name

//connect to mysql server
$mysqli = new mysqli($host, $username, $password, $db_name);



//check if any connection error was encountered
if(mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
}

$action = isset($_POST['action']) ? $_POST['action'] : "";



if($action=='create'){ //the the user submitted the form

//include database connection
include 'mysqli.php';

//our insert query query
//$mysqli->real_escape_string() function helps us prevent attacks such as SQL injection
$query  = "insert into organisation 
            set
                name = '".$mysqli->real_escape_string($_POST['name'])."', 
                continent = '".$mysqli->real_escape_string($_POST['continent'])."',
                country = '".$mysqli->real_escape_string($_POST['country'])."',
                website = '".$mysqli->real_escape_string($_POST['website'])."',
                email = '".$mysqli->real_escape_string($_POST['email'])."',
                nameorg = '".$mysqli->real_escape_string($_POST['nameorg'])."',
                category = '".$mysqli->real_escape_string($_POST['category'])."',
                price = '".$mysqli->real_escape_string($_POST['price'])."',
                currency = '".$mysqli->real_escape_string($_POST['currency'])."',
                description = '".$mysqli->real_escape_string($_POST['description'])."',
                wanted = '".$mysqli->real_escape_string($_POST['wanted'])."',
                expectation = '".$mysqli->real_escape_string($_POST['expectation'])."',
                extra  = '".$mysqli->real_escape_string($_POST['extra'])."'";


//execute the query
if( $mysqli ->query($query) ) {
    //if saving success
    echo "User was created.";
}else{
    //if unable to create new record
    echo "Database Error: Unable to create record.";
}
//close database connection
$mysqli->close();
}



?>

Thank you very much!!

非常感谢!!

回答by SarathSprakash

Try this

尝试这个

Here is the edited html

这是编辑后的html

html

html

    <form action='osb.php' method='post' border='0' id="form1">
    <div id = "container">  <br>
        <label>Name:            </label>    <input type='text' id="name" name='name' /><br>  <br>
        <label>Continent:       </label>    <select id="continent" name="continent"> <option>Africa</option><option>America</option><option>Asia</option> <option>Australia</option><option>Europe</option></select><br><br>
        <label>Country:         </label>    <input type='text' id="country" name='country' /><br><br>
        <label>Website:         </label>    <input type='text' id="website" name='website' /><br><br>
        <label>E-mail:          </label>    <input type='text' id="email" name='email' /><br><br><br>
        <label>Organisation:    </label>    <input type='text' id="nameorg" name='nameorg' /><br><br>
        <label>Category:        </label>    <input type='text' id="category" name='category' /><br><br>
        <label>Price per week:  </label>    <input type='text' id="price" name='price' /><br><br>
        <label>Currency:        </label>    <select id ="currency"  name="currency" >  <option> EUR </option> <option> DOL </option> <option> GBP </option></select><br><br>
        <label>Description:     </label>    <textarea id="description" rows="5" cols="40"  placeholder="Describe what kind of volunteer is welcome" name='description'/></textarea><br><br>
        <label>Wanted:          </label>    <textarea id="wanted" rows="5" cols="40"  placeholder="Describe what kind of volunteer is welcome" name='wanted'/></textarea><br><br>
        <label>Expectation:     </label>    <textarea id="expectation" rows="5" cols="40"  placeholder="Describe what a volunteer can expect"  name='expectation'/></textarea><br><br>
        <label>Extra:           </label>    <textarea id="extra" rows="5" cols="40"  placeholder="Describe what a volunteer can expect"  name='extra'/></textarea><br><br>

        <input type='hidden' name='action' value='create' />
        <input type='button' value='Submit' id="submit" />
        <input type="reset" value="Reset" class="reset-org">

        <a href='index.php'>Back to index</a> 
</form>

use .serialize(), it will automatically take all the form data

使用.serialize(),它会自动获取所有的表单数据

code

代码

    $(function(){

    $('#submit').click(function(){
     $('#container').append('<img src = "img/ajax/ajax-loader.gif" alt="Currently loading" id = "loading" />');
    $.ajax({

            url: 'osb.php',
            type: 'POST',
            data: $('#form1').serialize(),
            success: function(result){
                 $('#response').remove();
                 $('#container').append('<p id = "response">' + result + '</p>');
                 $('#loading').fadeOut(500);

               }

         });         

    });
 });

and in your php page add this

并在您的 php 页面中添加这个

osb.php

osb.php

<?php
$data=$_POST['serialize'];
$name=$data['name'];  //access data like this

?>