如何修改PHP / jQuery的/ AJAX脚本,有一个以上的表单字段posst [英] How to Modify PHP/Jquery/Ajax script to have more than one form field posst

查看:289
本文介绍了如何修改PHP / jQuery的/ AJAX脚本,有一个以上的表单字段posst的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PHP / AJAX / jQuery脚本中插入表单域到MySQL和更新页面而无需刷新,当你点击提交。我想脚本提交,而不是仅仅四位一体表单域。

I have an php/Ajax/Jquery script that inserts a form field into MySQL and updates the page without refreshing when you hit submit. I would like the script to submit four form fields, instead of just one.

我已经更新了数据库表 add_delete_record 与另外3个领域:的平衡,ACCOUNT_NUMBER 每月,加内容字段已经在那里了。

I have already updated the database table add_delete_record with 3 additional fields: balance, account_number and monthly, plus the content field that was already there.

下面可能是矫枉过正的code,因为我只需要修改几行,但我想这将回答所有的问题。

Below is probably overkill of code because I only need to modify a few lines, but I figured this would answer all the questions.

这是PHP和放大器; html页面:

This is the php & html page:

<div class="content_wrapper">
<ul id="responds">
<?php
//include db configuration file
include_once("config.php");

//MySQL query
$Result = mysql_query("SELECT id,content FROM add_delete_record");

//get all records from add_delete_record table
while($row = mysql_fetch_array($Result))
{
echo '<li id="item_'.$row["id"].'">';
echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$row["id"].'">';
echo '<img src="images/icon_del.gif" border="0" />';
echo '</a></div>';
echo $row["content"].'</li>';
}

//close db connection
mysql_close($connecDB);
?>
</ul>
<div class="form_style">
<textarea name="content_txt" id="contentText" cols="45" rows="5"></textarea>
<button id="FormSubmit">Add record</button>
</div>
</div>

这是PHP它张贴到:

<?php
//include db configuration file
include_once("config.php");

//check $_POST["content_txt"] is not empty
if(isset($_POST["content_txt"]) && strlen($_POST["content_txt"])>0)
{

    //sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH
    $contentToSave = filter_var($_POST["content_txt"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);

    // Insert sanitize string in record
    if(mysql_query("INSERT INTO add_delete_record(content) VALUES('".$contentToSave."')"))
    {
        //Record is successfully inserted, respond to ajax request
        $my_id = mysql_insert_id(); //Get ID of last inserted record from MySQL
        echo '<li id="item_'.$my_id.'">';
        echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$my_id.'">';
        echo '<img src="images/icon_del.gif" border="0" />';
        echo '</a></div>';
        echo $contentToSave.'</li>';
        mysql_close($connecDB);

    }else{
        //output error

        //header('HTTP/1.1 500 '.mysql_error());
        header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
        exit();
    }

}
elseif(isset($_POST["recordToDelete"]) && strlen($_POST["recordToDelete"])>0 && is_numeric($_POST["recordToDelete"]))
{//do we have a delete request? $_POST["recordToDelete"]

    //sanitize post value, PHP filter FILTER_SANITIZE_NUMBER_INT removes all characters except digits, plus and minus sign.
    $idToDelete = filter_var($_POST["recordToDelete"],FILTER_SANITIZE_NUMBER_INT);

    //try deleting record using the record ID we received from POST
    if(!mysql_query("DELETE FROM add_delete_record WHERE id=".$idToDelete))
    {
        //If mysql delete record was unsuccessful, output error
        header('HTTP/1.1 500 Could not delete record!');
        exit();
    }
    mysql_close($connecDB);

}else{

    //Output error
    header('HTTP/1.1 500 Error occurred, Could not process request!');
    exit();
}
?>

这是JQuery的

$(document).ready(function() {
    //##### Add record when Add Record Button is clicked #########
    $("#FormSubmit").click(function (e) {

        e.preventDefault();

        if($("#contentText").val()==="") //simple validation
        {
            alert("Please enter some text!");
            return false;
        }

        var myData = "content_txt="+ $("#contentText").val(); //post variables

        jQuery.ajax({
            type: "POST", // HTTP method POST or GET
            url: "response.php", //Where to make Ajax calls
            dataType:"text", // Data type, HTML, json etc.
            data:myData, //post variables
            success:function(response){
            $("#responds").append(response);
            $("#contentText").val(''); //empty text field after successful submission
            },
            error:function (xhr, ajaxOptions, thrownError){
                alert(thrownError); //throw any errors
            }
        });
    });

    //##### Delete record when delete Button is clicked #########
    $("body").on("click", "#responds .del_button", function(e) {
        e.preventDefault();
        var clickedID = this.id.split("-"); //Split string (Split works as PHP explode)
        var DbNumberID = clickedID[1]; //and get number from array
        var myData = 'recordToDelete='+ DbNumberID; //build a post data structure

        jQuery.ajax({
            type: "POST", // HTTP method POST or GET
            url: "response.php", //Where to make Ajax calls
            dataType:"text", // Data type, HTML, json etc.
            data:myData, //post variables
            success:function(response){
            //on success, hide element user wants to delete.
            $('#item_'+DbNumberID).fadeOut("slow");
            },
            error:function (xhr, ajaxOptions, thrownError){
                //On error, we alert user
                alert(thrownError);
            }
        });
    });
}); 

这是不是我的脚本,所以我想我也应该给一个链接到信贷它的作者: http://www.sanwebe.com/2012 / 04 / Ajax的插件删除-SQL-记录,jQuery的,PHP

This is not my script so I thought I should also give a link to credit the author of it: http://www.sanwebe.com/2012/04/ajax-add-delete-sql-records-jquery-php

推荐答案

我不是PHP的专家,但这应该让你通过:

i'm no php expert, but this should get you through:

首先改变窗体区域的主页上:

First change the form area on the main page:

<div class="form_style">
    <textarea name="content_txt" id="contentText" cols="45" rows="5"></textarea><br/>
    <input type="text" id="balance" /><br/>
    <input type="text" id="acctNum" /><br/>
    <input type="text" id="monthly" /><br/>
    <button id="FormSubmit">Add record</button>
</div>

那么你的myData看起来是这样的:

then your myData looks like this:

var myData = {
    content_txt: $("#contentText").val(),
    balance: $("#balance").val(),
    acctNum: $("#acctNum").val(),
    monthly: $("#monthly").val()
};

和后来在Ajax响应:

and later in the ajax response:

$("#contentText").val(''); //empty text field after successful submission
$("#balance").val('');
$("#acctNum").val('');
$("#monthly").val('');

和最后的PHP:

//sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH
$content = filter_var($_POST['content_txt'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$balance = filter_var($_POST['balance'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$account = filter_var($_POST['acctNum'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$monthly = filter_var($_POST['monthly'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);


$qry= "INSERT INTO add_delete_record(content,balance,account,monthly) VALUES('".$content."','".$balance."','".$account."','".$monthly."')";


// Insert sanitize string in record
if(mysql_query("INSERT INTO add_delete_record(content,balance,account,monthly) VALUES('".$content."','".$balance."','".$account."','".$monthly."')"))
{
    //Record is successfully inserted, respond to ajax request
    $my_id = mysql_insert_id(); //Get ID of last inserted record from MySQL
    echo '<li id="item_'.$my_id.'">';
    echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$my_id.'">';
    echo '<img src="images/icon_del.gif" border="0" />';
    echo '</a></div>';
    echo $content.'</li>';
    mysql_close($connecDB);

}else{
    //output error

    //header('HTTP/1.1 500 '.mysql_error());
    header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
    exit();
}

这篇关于如何修改PHP / jQuery的/ AJAX脚本,有一个以上的表单字段posst的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆