找到你要的答案

Q:PHP jQuery aJax From responses and data

Q:PHP AJAX从响应和数据

not sure what im missing but im having a few issues with my code im trying to build.

  • The data is not passing from the form to the database (blank entries)
  • Its also going to repsonse.php and not staying on the forms page
  • How can i pass the response for success and error back from response.php to the form to display on the frontend form?
  • Lastly its adding the data twice (blank entries but twice all the same)

HTML

<form action="response.php" method="post" id="add_product">
    <input type="hidden" name="action" value="add_product">

    <div class="row">
        <div id="response" class="alert alert-success" style="display:none;">
        <a href="#" class="close" data-dismiss="alert">&times;</a>
        <div class="message"></div>
    </div>

    <div class="col-xs-4">
        <input type="text" class="form-control" id="product_name" placeholder="Enter product name">
    </div>
    <div class="col-xs-4">
        <input type="text" class="form-control" id="product_desc" placeholder="Enter product description">
    </div>
    <div class="col-xs-4">
        <div class="input-group">
            <span class="input-group-addon"><?php echo CURRENCY ?></span>
            <input type="text" id="product_price" class="form-control" placeholder="0.00" aria-describedby="sizing-addon1">
        </div>
    </div>
</div>
<div class="row">
    <div class="col-xs-12 margin-top btn-group">
        <input type="submit" id="action_add_product" class="btn btn-success float-right" value="Add product" data-loading-text="Adding...">
    </div>
</div>

RESPONSE.PHP

//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'] : "";

// Adding new product
if($action == 'add_product') {

    $data = $_POST['serialize']; // serialize the data
    $product_name = $data['product_name'];
    $product_desc = $data['product_desc'];
    $product_price = $data['product_price'];

    //our insert query query
    $query  = "INSERT INTO products SET
                product_name = '".$product_name."', 
                product_desc = '".$product_desc."',
                product_price = '".$product_price."'
              ";

    //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();
}

SCRIPTS.JS

// add product
    $('#action_add_product').click(function(){
        var $btn = $(this).button('loading');

        $.ajax({

            url: 'response.php',
            type: 'POST',
            data: $('#add_product').serialize(),
            success: function(result){
                $('#response .message').html('Product has been added successfully!');
                $('#response').fadeIn();
                $btn.button('reset');
            }

        });
    });

不知道什么IM失踪,但IM有一些问题与我的代码我试图建立。

  • 数据不是从窗体传递到数据库(空白项)
  • 它也会repsonse.php不停留在形式的页面
  • How can i pass the response for success and error back from response.php to the form to display on the frontend form?
  • Lastly its adding the data twice (blank entries but twice all the same)

HTML

<form action="response.php" method="post" id="add_product">
    <input type="hidden" name="action" value="add_product">

    <div class="row">
        <div id="response" class="alert alert-success" style="display:none;">
        <a href="#" class="close" data-dismiss="alert">&times;</a>
        <div class="message"></div>
    </div>

    <div class="col-xs-4">
        <input type="text" class="form-control" id="product_name" placeholder="Enter product name">
    </div>
    <div class="col-xs-4">
        <input type="text" class="form-control" id="product_desc" placeholder="Enter product description">
    </div>
    <div class="col-xs-4">
        <div class="input-group">
            <span class="input-group-addon"><?php echo CURRENCY ?></span>
            <input type="text" id="product_price" class="form-control" placeholder="0.00" aria-describedby="sizing-addon1">
        </div>
    </div>
</div>
<div class="row">
    <div class="col-xs-12 margin-top btn-group">
        <input type="submit" id="action_add_product" class="btn btn-success float-right" value="Add product" data-loading-text="Adding...">
    </div>
</div>

response.php

//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'] : "";

// Adding new product
if($action == 'add_product') {

    $data = $_POST['serialize']; // serialize the data
    $product_name = $data['product_name'];
    $product_desc = $data['product_desc'];
    $product_price = $data['product_price'];

    //our insert query query
    $query  = "INSERT INTO products SET
                product_name = '".$product_name."', 
                product_desc = '".$product_desc."',
                product_price = '".$product_price."'
              ";

    //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();
}

scripts.js

// add product
    $('#action_add_product').click(function(){
        var $btn = $(this).button('loading');

        $.ajax({

            url: 'response.php',
            type: 'POST',
            data: $('#add_product').serialize(),
            success: function(result){
                $('#response .message').html('Product has been added successfully!');
                $('#response').fadeIn();
                $btn.button('reset');
            }

        });
    });
answer1: 回答1:

The data is not passing from the form to the database (blank entries)

You're missing name attributes on your form inputs. Debugging the output of $('#add_product').serialize() verifies this.

Its also going to repsonse.php and not staying on the forms page

You can set the form action to # (as Harigovind points out), I prefer to bind the submit event of the form instead, and prevent the default execution of the form. This also fixes the issue of people not pressing the button (firing your click event) but using the enter key instead:

$("#add_product").on("submit", function(e) {
   e.preventDefault(); // prevent default POST of form
   $.ajax({
      // etc
   });
});

JSFiddle: https://jsfiddle.net/trL5t80w/

数据不是从窗体传递到数据库(空白项)

您缺少表单输入的名称属性。调试输出(美元的# add_product”)。serialize()验证这。

它也会repsonse.php不停留在形式的页面

你可以设置为#形式作用(正如Harigovind所指出的),我更喜欢将提交事件的形式相反,防止窗体的默认执行。这也修正了人们不按按钮(触发你的点击事件)的问题,但使用回车键代替:

$("#add_product").on("submit", function(e) {
   e.preventDefault(); // prevent default POST of form
   $.ajax({
      // etc
   });
});

JSFiddle:https://jsfiddle.net/trl5t80w/

answer2: 回答2:

Your form is submitting when you click on #action_add_product button. If you want use ajax, you can:

  1. Change your #action_add_product element from button to a with href='#' - that prevent your form from being submitted
  2. Change your js code $('#action_add_product').click(function(){ to something like this: $('#add_product').submit(function(e){ e.preventDefault();

表单提交按钮,当你点击# action_add_product。如果你想使用Ajax,你可以:

  1. Change your #action_add_product element from button to a with href='#' - that prevent your form from being submitted
  2. Change your js code $('#action_add_product').click(function(){ to something like this: $('#add_product').submit(function(e){ e.preventDefault();
answer3: 回答3:

Hi the issue you are facing is because your data is getting posted twice. Since you are using ajax you dont have to give form action. You can replace it by a '#' symbol. You can also use the jquery prevent default function to prevent the default posting of the form.

Your echo in Response.php will act only as the response to athe ajax call so even if your database query is not executed the result will be you have successfully created the fields.

Also check if your serialized values are correct.

You can get the values of the serialized data just by replacing

$data = $_POST['serialize']; // serialize the data
$product_name = $data['product_name'];
$product_desc = $data['product_desc'];
$product_price = $data['product_price'];

these with

//$data = $_POST['serialize']; 
$product_name = $_POST['product_name'];
$product_desc = $_POST['product_desc'];
$product_price = $_POST['product_price'];

Hi the issue you are facing is because your data is getting posted twice. Since you are using ajax you dont have to give form action. You can replace it by a '#' symbol. You can also use the jquery prevent default function to prevent the default posting of the form.

你的回音在response.php只会为a Ajax响应呼叫,即使你的数据库查询不执行的结果将是您已成功创建领域。

也检查你的序列化的值是正确的。

你可以得到的值序列化数据只需更换

$data = $_POST['serialize']; // serialize the data
$product_name = $data['product_name'];
$product_desc = $data['product_desc'];
$product_price = $data['product_price'];

这些

//$data = $_POST['serialize']; 
$product_name = $_POST['product_name'];
$product_desc = $_POST['product_desc'];
$product_price = $_POST['product_price'];
answer4: 回答4:

You are missing the name attribute of your fields. Any ajax request equivalent to $_GET or $_POST needs the fields.

您缺少字段的名称属性。任何Ajax请求相当于_get美元或美元_post需求领域。

javascript  php  jquery  mysql