简体   繁体   English

序列化表格并将ajax发布到功能

[英]Serialzing form and posting ajax to function

I am trying to pass the form field values to a php function located into a file. 我试图将表单字段值传递给位于文件中的php函数。 The problem is that I can't understand how to pass that serialized form data to the function from this ajax to a function in php. 问题是我无法理解如何将序列化表格数据从此ajax传递到函数到php中的函数。

$('#insert_news').submit(function(event) {
    event.preventDefault();
    var form = $('#insert_news').serialize();
    $.ajax({
        type: 'POST',
        url: 'includes/ajax.php',
        data: {
            action: 'insert_news',
            $('#insert_news').serialize(); // how do I add this data here?
        },
        success: function(datas) {
            $('#message').html(datas).show() /*fadeIn(1000).fadeOut(1000)*/ ;
        }
    });
});

This ajax passed the values to the file ajax.php right beyond. 这个ajax将值直接传递到了文件ajax.php。 And from ajax.php is called the function located in functions.php. 从ajax.php开始,称为位于functions.php中的函数。

ajax.php ajax.php

if (isset($_POST['action']) && $_POST['action'] == 'insert_news') {
    $cp->insert_into_table('newss', array(
                                        'NewsTitle' => $_POST['title'], 
                                        'NewsDescrption' => $_POST['description'], 
                                        'Date' => date('Y-m-d H:i:s'), 
                                        'status' => '1'
                                    )
                           );
}

function.php function.php

public function insert_into_table($table_name, array $data){
    foreach($data as $col=>$value) {
        $cols[] = $col;
        $values[] = '\''.$value.'\'';
    }
    $cols = implode(', ', $cols);
    $values = implode(', ', $values);
    $this->db->query("INSERT INTO $table_name ($cols) VALUES ($values)");
    echo "INSERT INTO $table_name ($cols) VALUES ($values)";
}

You can pass serialized data via ajax to a function the way you are doing but your code needs slight modification. 您可以通过ajax将序列化的数据传递给您正在执行的功能,但是您的代码需要稍作修改。

$('#insert_news').submit(function(event) {
    event.preventDefault();
    var form = $('#insert_news').serialize();
    $.ajax({
        type: 'POST',
        url: 'includes/ajax.php',
        data: {
            action: 'insert_news',
  serializedData: form // use variable to assign data here 
        },
        success: function(datas) {
            $('#message').html(datas).show() /*fadeIn(1000).fadeOut(1000)*/ ;
        }
    });
});

The issue is serialize() produces a URL encoded key value paired string, so you can't mix that with your data object. 问题是serialize()会生成一个URL编码的键值配对字符串,因此您不能将其与数据对象混合使用。

You can use serializeArray() to get an array of objects, representing the form elements, then iterate over them and add them to a data object: 您可以使用serializeArray()获取对象数组,这些对象代表表单元素,然后对其进行迭代并将它们添加到数据对象中:

var data = { action: 'insert_news' };

$.each($('#insert_news').serializeArray(), function(){
    data[this.name] = this.value;
});

$.ajax({
    type: 'POST',
    url: 'includes/ajax.php',
    data: data,
    success: function(datas) {
        $('#message').html(datas).show() /*fadeIn(1000).fadeOut(1000)*/ ;
    }
});

Side note: your PHP code is vulnerable to SQL Injection. 旁注:您的PHP代码容易受到SQL注入的攻击。 Consider using a Prepared Statement instead of concatenating user input into the SQL. 考虑使用预处理语句,而不是将用户输入串联到SQL中。

$('#insert_news').submit(function(event) {
    var name = $("#t1").val();
    var pass = $("#t2").val();  //add more var as u need
    var key  = 0;

     var formName = new FormData();

     formName.append(key++,name)
     formName.append(key++,pass)    //append the the var to formdata


        $.ajax({
            url         :   'includes/ajax.php',
            dataType    :   'text',
            cache       :   false,
            contentType :   false,
            processData :   false,
            data        :   formName,                                    
            type        :   'post',

            success     :   function(data){
                        $('#message').html(data).show() /*fadeIn(1000).fadeOut(1000)*/ ;
                }

        });
});

this works fine for me :-) 这对我来说很好:-)

I think you can use alternate like this 我想你可以这样使用替代

First : add hidden input for action on your form 首先:在表单上添加隐藏的操作输入

<input type="hidden" name="action" value="insert_news"/>

Then your ajax post like this 然后像这样你的ajax帖子

$('#insert_news').submit(function(event) {
    event.preventDefault();
    $.ajax({
        type: 'POST',
        url: 'includes/ajax.php',
        data: $(this).serialize(), // $(this) is from <form id="insert_news">
        success: function(datas) {
            $('#message').html(datas).show() /*fadeIn(1000).fadeOut(1000)*/ ;
        }
    });
});

And then use print_r on your ajax.php 然后在ajax.php上使用print_r

print_r($_POST);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM