简体   繁体   English

AJAX \\ JQUERY:使用表单数据更新MYSQL数据库而无需刷新

[英]AJAX\JQUERY: Update MYSQL database with form data without refreshing

Ok, so I've gotten most of this thing done.. Now comes, for me, the hard part. 好的,所以我已经完成了大部分工作。现在,对我来说,困难的部分到了。 This is untreaded territory for me. 这对我来说是未读的领域。

How do I update my mysql database, with form data, without having the page refresh? 如何在不刷新页面的情况下使用表单数据更新mysql数据库? I presume you use AJAX and\\or Jquery to do this- but I don't quite grasp the examples being given. 我假设您使用AJAX和/或Jquery来执行此操作-但我不太了解所给出的示例。

Can anybody please tell me how to perform this task within this context? 有人可以告诉我如何在这种情况下执行此任务吗?

So this is my form: 这是我的表格:

 <form name="checklist" id="checklist" class="checklist">
        <?php // Loop through query results   
              while($row = mysql_fetch_array($result))
                  {
                  $entry = $row['Entry'];
                  $CID = $row['CID'];
                  $checked =$row['Checked'];
                 // echo $CID;
                  echo "<input type=\"text\" value=\"$entry\" name=\"textfield$CID;\" id=\"textfield$CID;\" onchange=\"showUser(this.value)\" />";
                  echo "<input type=\"checkbox\" value=\"\" name=\"checkbox$CID;\" id=\"checkbox$CID;\"  value=\"$checked\"".(($checked == '1')? ' checked="checked"' : '')."  />";
                  echo "<br>";
                  }
        ?> 
        <div id="dynamicInput"></div>
        <input type="submit" id="checklistSubmit" name="checklistSubmit" class="checklist-submit"> <input type="button" id="CompleteAll" name="CompleteAll" value="Check All" onclick="javascript:checkAll('checklist', true);"><input type="button" id="UncheckAll" name="UncheckAll" value="Uncheck All" onclick="javascript:checkAll('checklist', false);">                  
     <input type="button" value="Add another text input" onClick="addInput('dynamicInput');"></form>

It is populated from the database based on the users session_id, however if the user wants to create a new list item (or is a new visitor period) he can click the button "Add another text input" and a new form element will generate. 它是根据用户session_id从数据库中填充的,但是,如果用户要创建一个新的列表项(或者是一个新的访问者时期),则可以单击“添加另一个文本输入”按钮,然后将生成一个新的表单元素。

All updates to the database need to be done through AJAX\\JQUERY and not through a post which will refresh the page. 对数据库的所有更新都需要通过AJAX \\ JQUERY来完成,而不是通过将刷新页面的帖子来完成。

I really need help on this one. 我真的需要这方面的帮助。 Getting my head around this kind of... Updating method kind of hurts! 让我的头绕开这种...更新方法有点痛苦!

Thanks. 谢谢。

You will need to catch the click of the button. 您将需要单击按钮的单击。 And make sure you stop propagation. 并确保您停止传播。

$('checklistSubmit').click(function(e) {
    $(e).stopPropagation();

    $.post({
        url: 'checklist.php'
        data: $('#checklist').serialize(),
        dataType: 'html'
        success: function(data, status, jqXHR) {
           $('div.successmessage').html(data);
           //your success callback function
        } 
        error: function() {
           //your error callback function
        } 
    });
});

That's just something I worked up off the top of my head. 那只是我努力工作的结果。 Should give you the basic idea. 应该给你基本的想法。 I'd be happy to elaborate more if need be. 如果需要,我很乐意详细说明。

Check out jQuery's documentation of $.post for all the nitty gritty details. 查看jQuery的$ .post文档,了解所有详细信息。

http://api.jquery.com/jQuery.post/ http://api.jquery.com/jQuery.post/

Edit: 编辑:

I changed it to use jquery's serialize method. 我将其更改为使用jQuery的序列化方法。 Forgot about it originally. 最初忘记了它。

More Elaboration: 更多说明:

Basically when the submit button is clicked it will call the function specified. 基本上,当单击提交按钮时,它将调用指定的函数。 You want to do a stop propagation so that the form will not submit by bubbling up the DOM and doing a normal submit. 您想要停止传播,以免通过冒泡DOM并进行常规提交来提交表单。

The $.post is a shorthand version of $.ajax({ type: 'post'}); $ .post是$ .ajax({type:'post'})的简写版本;

So all you do is specify the url you want to post to, pass the form data and in php it will come in just like any other request. 因此,您要做的就是指定要发布到的url,传递表单数据,在php中,它将像其他任何请求一样进入。 So then you process the POST data, save your changes in the database or whatever else and send back JSON data as I have it specified. 因此,然后您处理POST数据,将所做的更改保存在数据库中或进行其他操作,然后按我指定的方式发送回JSON数据。 You could also send back HTML or XML. 您也可以发回HTML或XML。 jQuery's documentation shows the possible datatypes. jQuery的文档显示了可能的数据类型。

In your success function will get back data as the first parameter. 在您的成功函数中,将取回数据作为第一个参数。 So whatever you specified as the data type coming back you simply use it how you need to. 因此,无论您指定返回哪种数据类型,都可以按需使用它。 So let's say you wanted to return some html as a success message. 因此,假设您要返回一些html作为成功消息。 All you would need to do is take the data in the success function and place it where you wanted to in the DOM with .append() or something like that. 您需要做的就是将数据放入成功函数中,并使用.append()或类似的方法将其放置在DOM中所需的位置。

Clear as mud? 像泥一样清澈?

This is how i post form data using jquery 这就是我使用jQuery发布表单数据的方式

$.ajax({
    url: 'http://example.com',
    type: 'GET',
    data: $('#checklist').serialize(),
    cache: false,
}).done(function (response) {
    /* It worked */
}).fail(function () {
    /* It didnt worked */
});

Hope this helps, let me know how you get on! 希望对您有所帮助,让我知道您的生活!

You need two scripts here: one that runs the AJAX (better to use a framework, jQuery is one of the easiest for me) and a PHP script that gets the Post data and does the database update. 您在这里需要两个脚本:一个运行AJAX(最好使用框架,jQuery对我来说是最简单的脚本)和一个PHP脚本,用于获取Post数据并进行数据库更新。

I'm not going to give you a full source (because this is not the place for that), but a guide. 我不会为您提供完整的资源(因为这不是该资源的来源),而是指南。 In jQuery you can do something like this: 在jQuery中,您可以执行以下操作:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() { // DOM is ready
    $("form#checklist").submit(function(evt) {
        evt.preventDefault(); // Avoid the "submit" to work, we'll do this manually
        var data = new Array();
        var dynamicInputs = $("input,select", $(this)); // All inputs and selects in the scope of "$(this)" (the form)

        dynamicInputs.each(function() {
            // Here "$(this)" is every input and select
            var object_name = $(this).attr('name');
            var object_value = $(this).attr('value');
            data[object_name] = object_value; // Add to an associative array
        });

        // Now data is fully populated, now we can send it to the PHP
        // Documentation: http://api.jquery.com/jQuery.post/
        $.post("http://localhost/script.php", data, function(response) {
            alert('The PHP returned: ' + response);
        });
    });
});
</script>

Then take the values from $_POST in PHP (or any other webserver scripting engine) and do your thing to update the DB. 然后,从PHP(或任何其他Web服务器脚本引擎)的$ _POST中获取值,并执行更新数据库的操作。 Change the URL and the data array to your needs. 根据需要更改URL和数据数组。

Remember that data can be like this: { input1 : value1, input2 : value2 } and the PHP will get something like $_POST['input1'] = value1 and $_POST['input2'] = value2. 请记住,数据可以是这样的:{input1:value1,input2:value2},PHP将得到类似$ _POST ['input1'] = value1和$ _POST ['input2'] = value2的信息。

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

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