使用ajax json php将表单数据存储到数据库中

I'm trying to store form data in database but my code is reflecting anything. Here is my code

add.php

<form name='reg' >
<fieldset>
    <legend>Student information:-</legend>
    <ul>
        <li>
            <label> FirstName:  </label><input type="text" id="name"  name="name" required>
            <span id='error' style="display:none;color:red;"> Only alphabets </span>
        </li>  

        <li>
            <label> LastName: </label><input type="text" id="lname" name="lname"  required>
            <span id='error1' style="display:none;color:red;"> Only alphabets </span>

        </li> 
        <li>
            <label>Username:</label>
            <input type="text" id="username" name="username"/>
        </li>
        <li>
            <label>Password:</label>
            <input type="password" id="password" name="password"/>
        </li>

        <label>
            Gender:  </label> 
        <input type="radio" id='gender' name="gender" value="male" required> Male
        <input type="radio" name="gender" id='gender' value="female" required> Female
        <input type="radio" name="gender" id='gender' value="other" required> Other

        <li>
            <label>
                Email:    </label>
            <input id="email" type="text" name="email"  required>
            <span id='error2' style="display:none;color:red;"> Invalid email </span>
        </li>
        <li>
            <label> Mobile:</label>
            <input id="mobile" type="text" maxlength="10" name="mobile"  required >
            <span id='error3' style="display:none;color:red;"> only digits </span>
        </li>  
        <li>
            address: <textarea name="address" id="address" type="text" rows="3" cols="40"></textarea></textarea>

        </li>   

    </ul>
    <p><a href="" class="btn btn-info"  id="btnBooking">Register</a></p>
</fieldset>
</form>

and javascript file is as

serve.js

$(document).ready(function () {
    $("#btnBooking").on("click", function (e) {

        // as you have used hyperlink(a tag), this prevent to redirect to another/same page
        e.preventDefault();

        // get values from textboxs  
        var name = $('#name').val();
        // alert('name');
        var lname = $('#lname').val();
        var username = $('#username').val();
        var password = $('#password').val();
        var gender = $('#gender').val();
        var mail = $('#email').val();
        var mobNum = $('#mobile').val();
        var address = $('#address').val();

        $.ajax({
            url: "http://localhost/project_cloud/fun.php",
            type: "post",
            dataType: "json",
            data: {type: "add", Name: name, Lname: lname, User: username, Pass: password, Gen: gender, Email: mail, Mob_Num: mobNum, Addr: address},
            //type: should be same in server code, otherwise code will not run
            ContentType: "application/json",
            success: function (response) {
                alert(JSON.stringify(response));
            },
            error: function (err) {
                alert(JSON.stringify(err));
            }
        })
    });
});

and another php file which stores the result in database

fun.php

<?php
header('Access-Control-Allow-Origin: *');
mysql_connect("localhost", "root", "");
mysql_select_db("ocean");

if (isset($_GET['type'])) {
    $res = [];

    if ($_GET['type'] == "add") {
        $name = $_GET ['Name'];
        $lname = $_GET['Lname'];
        $userN = $_GET['User'];
        $passW = $_GET['Pass'];
        $gen = $_GET['Gen'];
        $mail = $_GET ['Email'];
        $mobile = $_GET ['Mob_Num'];
        $address = $_GET['Addr'];
        $query1 = "insert into oops(username, password, firstname, lastname, gender, email, mobile, address) values('$userN','$passW','$name','$lname','$gen','$mail','$mobile','$address')";
        $result1 = mysql_query($query1);

        if ($result1) {
            $res["flag"] = true;
            $res["message"] = "Data Inserted Successfully";
        } else {
            $res["flag"] = false;
            $res["message"] = "Oppes Errors";
        }
    }
} else {
    $res["flag"] = false;
    $res["message"] = "Invalid format";
}

echo json_encode($res, $result1);
?>

When I write my serve.js file code in add.php file it gives me result as stored in database .But when I tried to separate it js file it shows nothing. What wrong in it or I missing something.

dslf46995
dslf46995 在您的ajax请求中POST数据,但在PHP文件(fun.php)中,您尝试检索GET数据($_GET)。
大约 4 年之前 回复

1个回答



您有</ p>

 类型:“post”,
</ code> </ pre>

在您的AJAX请求中,但服务器端处理$ _GET参数:</ p>

  $ lname = $ _GET ['Lname']; \  n </ code> </ pre> 

$ _ GET </ code>更改为 $ _ POST </ code>,您将看到您的值。</ p>

但你的所有代码都很糟糕。 您无法在Internet中发布此内容。 你有很糟糕的JavaScript和许多问题服务器端,包括MySQL注入。 需要用准备好的语句和JS重写所有这些:</ p>

  $(function(){
$(“#btnBooking”)。on(“click”,function (e){
e.preventDefault();
var data = $(this).parents('form')。serializeArray();
data.type ='add'
$ .post('/ project_cloud / fun.php',data)
.done(function(response){
alert(JSON.stringify(response));
})
.fail(function(err){
alert(JSON) .stringify(err));
})
});
})
</ code> </ pre>
</ div>

展开原文

原文

You have

type:"post",

in your AJAX request, but server side handle $_GET parameters:

$lname = $_GET['Lname'];

Change $_GET to $_POST and you'll see your values.

But all your code is terrible. You can't publish this in Internet. You have bad JavaScript and many issues serverside, include MySQL Injection. Need to rewrite all of this with prepared statements and JS to:

$(function() {
    $("#btnBooking").on("click", function(e){
        e.preventDefault();
        var data = $(this).parents('form').serializeArray();
        data.type = 'add'
        $.post('/project_cloud/fun.php',data)
        .done(function(response){
            alert(JSON.stringify(response));
        })
        .fail(function(err){
            alert(JSON.stringify(err));
        })
    });
})

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐