0

I'm trying since hours, to submit a form with AJAX, in order not to refresh or redirect the page.

I use this code to submit :

$('#files').on(submit, function(e) {
    e.preventDefault();
    $.ajax({
        url:'actions.php',
        type:'post',
        data:$(this).serialize(),
        success:function(){
            console.log('sent');
        },
        error:function(){
            console.log('not sent');
        }
    });
});

However, I noticed that there is nothing when I serialize the form. It's just blank. I submit my form, and a PHP script fetches the name of the button pressed to determine what to do next. In my example, the button name starts with "edit" so I'll only show the concerned part.

else if (substr($index, 0, 4) == "edit") {
    $q = "UPDATE files SET file_name = '" . $_POST[$index] . "', file_path = 'users/" . $_SESSION['username'] . "/" . $_POST[$index] . "'" . " WHERE id = " . $file_id;
    mysqli_query($link, $q);
    rename('users/'.$_SESSION['username'].'/'.$filename, 'users/'.$_SESSION['username'].'/'. $_POST[$index]);
    echo(json_encode(array('success'=>true)));
}

It keeps redirecting when I don't use the e.preventDefault() and when I use it, it does not submit anything.

EDIT: Here is the HTML

<td>
    <span name="edit22" contenteditable="true">fake</span>
    <div>
        <span>
            <button type="submit" name="edit22" form="files" value="fake">
                <i class="fa fa-check" aria-hidden="true"></i>
            </button>
        </span>
        <span>
            <button>
                <i class="fa fa-times" aria-hidden="true"></i>
            </button>
        </span>
    </div>
</td>

the fa fa-check button, with javascript will take for value the content of the first <span> element.

Where am I doing it wrong ?

nook
  • 1,729
  • 1
  • 12
  • 34
  • 1
    `$('#files').on('submit',function(e) {` – Shadow Fiend Jan 05 '18 at 01:37
  • Well indeed, now it is sent (so success), but it doesn't do what my PHP script should do, you still resolved a big problem – nook Jan 05 '18 at 01:39
  • Do you want the form to be sumbitted then try `var form = new FormData($(this)[0]);` then `data: form,` Then you could do it like this in php `$input = $_POST["name_of_input"];` – Shadow Fiend Jan 05 '18 at 01:44
  • 2
    Also use [**Prepared Statements**](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) to avoid [**SQL Injections**](https://stackoverflow.com/questions/332365/how-does-the-sql-injection-from-the-bobby-tables-xkcd-comic-work) – Shadow Fiend Jan 05 '18 at 01:49
  • show us your html – samehanwar Jan 05 '18 at 01:53
  • @ShadowFiend Yes I know about prepared requests, for the first project it is not necessary to secure it, it will be later. I'll try using the object tomorrow, but basically this is the same like I did? Except I used `substr` to define what kind of button it was – nook Jan 05 '18 at 01:54
  • Where is the element with the id "form"? And it is supposed to be .on('submit', callback), put the event name in quotes. – AmazingTurtle Jan 05 '18 at 12:24

3 Answers3

1

To prevent the form to actually "submit" through redirection, just return "false" from within the event handler. Like so:

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

Also, you must set the "name" attribute of form elements in order to serialize them correctly. Refer to https://jsfiddle.net/ccsCoder/fyyd7mfw/3/ for an example.

So your submit handler should look something like this:

$("#files").on("submit", function(e) {
    $.post("action.php", $(this).serialize(), function(data) {
        console.log("success"); //do something with data
    }, function(error) {
        console.log("Failed!");
    });
    return false;
});

Here is the full snippet: https://jsfiddle.net/ccsCoder/fyyd7mfw/3/

Neo
  • 150
  • 1
  • 1
  • 6
  • Doesn't work, sends me that some functions don't exist. I edited the code over here with HTML. – nook Jan 05 '18 at 08:29
  • I could see it works well, Please try with this: https://jsfiddle.net/ccsCoder/fyyd7mfw/ – Neo Jan 08 '18 at 09:41
0

Why not rearrange you code to be something like this

    function onClick()
{
    $.ajax({
        url:'actions.php',
        type:'post',
        data:$('#FormID').serialize(),
        success:function(){
            console.log('sent');
        },
        error:function(){
            console.log('not sent');
        }
    });
}

Change the HTML To be something like this

<td>
    <span name="edit22" contenteditable="true">fake</span>
    <div>
        <span>
            <button type="button" name="edit22" form="files" value="fake" onClick='javascript:onClick();'>
                <i class="fa fa-check" aria-hidden="true"></i>
            </button>
        </span>
        <span>
            <button>
                <i class="fa fa-times" aria-hidden="true"></i>
            </button>
        </span>
    </div>
</td>
Lord Darth Vader
  • 1,895
  • 1
  • 17
  • 26
-1

or just use <input type="button" /> instead of <input type="submit" />. You can even still set it as the default action of the form if you use that forms behavior. I find it better not to though and just force the click if there are multiple required fields. From there, you'll just use the click event instead of submit.

Veritoanimus
  • 319
  • 3
  • 10
  • I showed HTML to show you how it behaves. I just don't get why it won't submit even tho the ajax will return me success... – nook Jan 05 '18 at 08:31
  • Pressing enter in the form will still submit this, so it's a really bad workaround. And ` – humanoid Jan 05 '18 at 13:17
  • The point is, if you're using a restful API Controller that shouldn't submit the page for postback, then you shouldn't use submit behavior. You should also probably be using the asynchronous RESTful JQuery calls ($.post or $.get) rather than the $.ajax calls that are being depricated. – Veritoanimus Jan 05 '18 at 16:39