简体   繁体   中英

How do I sync an AJAX call to a php file with posting data through a form to the same file?

My problem is update.php only gets the posted form data ( post_edit ). The variables posted earlier through AJAX don't go through

Notice: Undefined index: id_to_edit in ...\update.php on line 5

Notice: Undefined index: column_to_edit in ...\update.php on line 6

What I'm trying to do:

I have a callback function that traces the mouse's position on the table's body. This is done to detect the column and the id of the cell that the user wants to edit - id integer and column string are posted to a php file through AJAX and used in an SQL query using both values (for coordinates) on top of the data the user wants to update (posted through a form, more on this later).

Editing is done this way: when a user mouses over a cell a form is created inside, and filling in that form should post the data to update the corresponding entry in the SQL table (which is found by using the coordinates from the callback function). Mousing out removes the form.

To paraphrase a bit

How do I post the coordinates and the form data to a php file so that all these values can be used in an SQL query? If what I've been doing is fundamentally broken, is there another way?

$(function(){

    $("td")
    .hoverIntent(
        function(e){            
        var id_of_edit = $(e.target).siblings('th').text();
        var $clicked_column_i = $(e.target).index() + 1;
        var column_of_edit = $("#tableheader").children("th:nth-child(" + $clicked_column_i + ")").text();

        $.ajax({
            type: 'POST',
            dataType: 'text',
            url: 'update.php',
            data: { 
                'id_of_edit': id_of_edit,
                'column_of_edit': column_of_edit
                },

        });

        var $edit_button = $('<form action="update.php" method="post"><input type="text" name="post_edit"/></form>');

        $(e.target).append($edit_button);

        console.log(e.target.innerText + " was clicked");
        console.log(id_of_edit + " is the ID");
        console.log(column_of_edit + " is the column name");       
        //just to check the tracer function is working correctly
        },  

        function(e){            
        $id_of_edit = $(e.target).siblings('th').text();
        $clicked_column_i = $(e.target).index() + 1;
        $column_of_edit = $("#tableheader").children("th:nth-child(" + $clicked_column_i + ")").text();

        $(e.target).children('form').remove();
        });

});

update.php:

<?php

include 'config.php';

echo $_POST['id_to_edit'];
echo $_POST['column_to_edit'];
echo $_POST['post_edit'];


$stmt = $pdo->prepare('UPDATE food SET :column = :edit WHERE id = :id');
$stmt->execute([
    'id' => $_POST['id_to_edit'],
    'column' => $_POST['column_to_edit'],
    'edit' => $_POST['post_edit']
]);

?>

An ajax request and a form submission via standard postback are two separate HTTP requests. Your "update.php" script will execute twice - once for each separate request, and each request will have separate sets of POST variables, according to what you sent on that request. The variables do not persist between requests - just because you sent them to the same endpoint script does not matter.

To summarise: HTTP requests are stateless - they exist in isolation and any given request knows nothing about previous or future requests. Each one causes the named PHP script to run from start to finish, as if it had never run before, and might never run again. It remembers nothing about the past, and knows nothing about the future, unless you do something about it explicitly.

If you want values to persist between requests you have to store them yourself - in a DB, Session, cookies, whatever (it's up to you) - and then retrieve them later when you need them.


Having said that, looking at your server code it's not clear why you would want two separate requests anyway - you are doing a single UPDATE statement in the SQL, so it would make more sense to use one HTTP request to transmit all the data to the server, and then execute the script which runs the UPDATE. Unless there's some reason in the UI why this can't be done, in which case then you need to persist the values somewhere in between requests. From your description, you could potentially capture the cell/column ID into a hidden field inside the form you generate, rather than sending them immediately to the server via ajax. The hidden field values would then be posted to the server together with the user-generated values when the main form is submitted.

Also, if you really are using the mouse's position to determine the cell, this sounds very unreliable - browser windows can be resized to anything. Surely putting an ID inside the HTML markup of the cell (eg as a data- attribute) which you can then read when the cell is clicked / moused-over would be much more reliable?

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