简体   繁体   中英

mysqli insert / update and ajax issue

I have question regarding inserting and updating a MySQL database from a form which is loaded in a div via ajax. I have taken various examples from different websites to check if it was an error on my part but they all work when the page is loaded independently and insert or amended to the database. When the form is loaded into the div, the inputs are completed and submitted it then redirects to the home page as defined in the script file but no information is inserted into the database:

 (ajax_url.length < 1) {
        ajax_url = 'app/pages/home.php';
    } 

As I said the form works and inserts if I load the form page directly. For that reason I have also tried the following while giving the form an id of "dataforms" and the submit button an id of "sub":

$("#sub").click( function() {
 $.post( $("#dataforms").attr("action"),
         $("#dataforms :input").serializeArray(),
         function(info){ $("#result").html(info);
   });
clearInput();
});
 
$("#dataforms").submit( function() {
  return false;
});
function clearInput() {
    $("#dataforms :input").each( function() {
       $(this).val('');
    });
}

Is there something basic I am completely missing?

This is an example I was trying to get to work:

    <?php
        include_once('/config.php');
        $task_name = $_POST['task_name'];
       
        if(mysql_query("INSERT INTO task (task_name) VALUES('$task_name')"))
         echo "Successfully Inserted";
        else
        echo "Insertion Failed";
?>

    <span id="result"></span>

    <form id="dataforms" action="" method="post">

        <label id="first"> Task Name</label><br/>
        <input type="text" name="task_name"><br/>


        <button id="sub">Save</button>

    </form>

I have also attempted to define the php in a separate file and call it on action and I end up with what looks like the post values not being carried across as I get an error showing $task_name is not defined.

The js script file is referenced in the footer and have no issues with datatables displaying and selecting data from the database so I guess it has something to do with how the form is being submitted and reloading. Do I need to treat form submissions differently when ajax is involved? I have used various insert and update scripts to test and all behave the same way.

<span id="result"></span>
<form id="dataforms" action="insert-task.php" method="post">
   <label id="first"> Task Name</label><br/>
   <input type="text" name="task_name"><br/>

   <button id="sub">Save</button>
</form>

<script src="https://code.jquery.com/jquery-3.2.0.min.js"
    integrity="sha256-JAW99MJVpJBGcbzEuXk4Az05s/XyDdBomFqNlM3ic+I="
    crossorigin="anonymous"></script>

<script>
    $("#sub").click( function() {
        $.post( 
            $("#dataforms").attr("action"),
            $("#dataforms :input").serializeArray(),
            function(info){ 
                $("#result").html(info);
            });
        clearInput();
    });

    $("#dataforms").submit( function() {
        return false;
    });

    function clearInput() {
        $("#dataforms :input").each( function() {
            $(this).val('');
        });
    }
</script>

<?php         
    //include_once('/config.php');
    $task_name = $_POST['task_name'];
    //if(mysql_query("INSERT INTO task (task_name) VALUES('$task_name')")) 
    // echo $task_name; die;
    if(true) 
        echo "Successfully Inserted";         
    else
        echo "Insertion Failed"; 
?>


The two pages do work in tandem. Though there are a couple of things to note, please:

  • The database operations aren't yet a part of the executable code.
  • However, if // echo $task_name; die; // echo $task_name; die; was uncommented, then the <span> in the first page would be populated with whatever value was keyed in the input field, which would establish that the form data is relayed properly to the backend.

To deal with the required fields, following change is required in the first page:

  • Get rid of the click function for $("#sub")
  • Prevent the default submit action when dataforms is submitted

So, in effect, the updated code would look like follows:

<span id="result"></span>
<form id="dataforms" action="insert-task.php" method="post">
    <label id="first"> Task Name</label><br/>
        <input type="text" name="task_name" required><br/>
        <button id="sub">Save</button>
</form>

<script src="https://code.jquery.com/jquery-3.2.0.min.js"
    integrity="sha256-JAW99MJVpJBGcbzEuXk4Az05s/XyDdBomFqNlM3ic+I="
    crossorigin="anonymous"></script>


<script>
    $("#dataforms").submit( function(e) {
        e.preventDefault();
        $.post( 
            $("#dataforms").attr("action"),
            $("#dataforms :input").serializeArray(),
            function(info){ 
                $("#result").html(info);
            }
        );
        clearInput();
        return false;
    });

    function clearInput() {
        $("#dataforms :input").each( function() {
            $(this).val('');
        });
    }
</script>


This would still show up Please fill out this field message if no data was entered in the input field and, at the same time, prevent the unexpected pop-up as a consequence of clearing the field after a successful submit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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