2

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.

Sue Renki
  • 25
  • 2
  • From what I see, `$.post( $("#dataforms").attr("action")` would result in finding an empty string because of... `
    `
    – Dhruv Saxena Mar 17 '17 at 23:21
  • Once this issue is solved, it'd be worthwhile to upgrade the code to use [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) or [PDO Prepared Queries](http://php.net/manual/en/pdo.prepare.php). As the code stands right now, it's broad open to [SQL Injection Attacks](http://bobby-tables.com/), besides [`mysql_*()` functions are now long deprecated](http://stackoverflow.com/q/12859942/2298301). – Dhruv Saxena Mar 17 '17 at 23:34
  • As I mentioned this was only an example script as I knew it worked when the page was loaded directly in the browser just to show the issue. I am sorry if this is a stupid question from your first question but do you mean because there is no action defined that is what is causing the issue? I ask as I tried with
    and the php elements in that file and end up with an error showing $task_name is not defined.
    – Sue Renki Mar 17 '17 at 23:49
  • It's a perfectly valid question and your hunch is spot on. Right now, `$.post()` doesn't receive the URL that it should invoke because the `action` attribute contains nothing. – Dhruv Saxena Mar 17 '17 at 23:51
  • ok so I have
    with the php code in the insert.php file, now I have this issue: Parse error: syntax error, unexpected '$task_name' (T_VARIABLE)
    – Sue Renki Mar 17 '17 at 23:57
  • I'm sorry, I'm missing something. Do you mean you got this error when the `action` attribute is set? If I may ask, what is it set to? Also, do you receive the aforementioned error in the foreground or background? While loading the page for the first time or after clicking `Save`? – Dhruv Saxena Mar 18 '17 at 00:01
  • The page with the form: `


    ` insert-task.php: ``
    – Sue Renki Mar 18 '17 at 00:03
  • The form is displayed correctly, I enter a value for task name and then click save and I then have Parse error: syntax error, unexpected '$task_name' (T_VARIABLE) displayed on full white page not in the ajax content div. If I insert a # in the file path the error displays in the div if that makes sense. Currently in the js file only the class "ajax-link" is set to change the content of the div. – Sue Renki Mar 18 '17 at 00:14
  • Well, I just tried the exact same code (though only replaced `if(mysql_query("....")` with `if(true)` - that is anyway after the initial declaration of `$task_name`) and am able to place the `$.post()` call and see `Successfully Inserted` written in the `span`. – Dhruv Saxena Mar 18 '17 at 00:17
  • Is your jQuery loaded properly? Do you see any errors in the console (press F12 if you're on Chrome / Firefox)? – Dhruv Saxena Mar 18 '17 at 00:19
  • no only the doc type warning – Sue Renki Mar 18 '17 at 00:30
  • Although it might be unlikely, but I'm just wondering if `$task_name` is also used somewhere in `config.php` too. Anyway, please have a look at the answer posted herewith and see if you're able to make a successful `$.post()` call if the two code snippets are used as is? – Dhruv Saxena Mar 18 '17 at 00:39

1 Answers1

0

First Page — can be .html or .php, doesn't matter:

<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>

Second page — insert-task.php:

<?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; 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.

EDIT:

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.

Dhruv Saxena
  • 1,336
  • 2
  • 12
  • 29
  • Thanks very much, just changed to mysqli now and have figured out that the url handling wasn't set up correctly either which I think created an issue. This is really not a strong point for me so your input has been invaluable – Sue Renki Mar 18 '17 at 00:58
  • @SueRenki - Thanks for confirming. Glad that the problem is solved and something useful was found along the way. Props to the code being updated to MySQLi now, just please remember that it's essentially the Prepared Statements that would be required to shield the code from unwarranted SQL attacks. – Dhruv Saxena Mar 18 '17 at 01:05
  • Thanks. I do have one other question now I have set the input to required. Once submitted and I received the confirmation message but also I get this is a required filed pop up for the input box. Is this now because of the clear input function? PS I am really sorry for being a pain, I have only started dabbling with php, ajax, mysqli for about a week. – Sue Renki Mar 18 '17 at 01:21
  • @SueRenki Please check out the edit made to the above post. In a way, the required fix would perhaps end up simplifying the code a little bit. – Dhruv Saxena Mar 18 '17 at 02:00