Home:ALL Converter>Passing an ID from foreach to modal

Passing an ID from foreach to modal

Ask Time:2018-08-11T02:15:42         Author:Joanne

Json Formatter

I am trying to pass my $model['id'] from a foreach to a modal which contains a form which heavily requires the $model['id'] for if statements and functions.

I have tried putting a link around the button to use the usual $_GET however that forces the page to refresh and therefore closes the modal box, is there a way to prevent the modal from closing if the url contains an id?

Alternatively I have tried using the data-id passing through an AJAX post method and retrieving it in the modal. However the $_POST is not being defined, have I missed something or can it not $_POST to the same page? I am not good with AJAX so any help or ideas would be greatly appreciated.

There is way too much code in my page to post it all so here's a snippet of the important stuff

<button data-id="<?php echo $model['id']; ?>" data-modal-type="type3" class="modal_button customer_button right">New Customer</button>

<div class="modal" id="type3">
    <div class="modal-content">
        <div class="modal-title"><h3>New Customer</h3></div>
        <div class="modal-padding">
            <?php
            $customer_model_id = (isset($_POST['id'])) ? $_POST['id'] : 'ID not found';
            echo $customer_model_id; // Always shows ID not found
            ?>
        </div>
    </div>
</div>

<script>
        $(".modal_button").click(function () {
        $(".modal").hide();
        var Type = $(this).data("modal-type");
        $("#" + Type).show();

        var id = $(this).data("id");
        alert($(this).data("id")); // Alert box shows the correct ID
        $.ajax({
            type: "POST",
            url: '<?php echo doc_root('index.php');//post to the same page we are currently on ?>',
            data: "id=" + id,
        });
    });
</script>

EDIT: I think I'm getting closer with this JavaScript.

<script> 
    $(".modal_button").click(function(){ 
    $(".modal").hide(); 
    var Type = $(this).data("modal-type"); 

    var id = $(this).data('id'); 
    $.ajax({ 
    type : 'POST', 
    url : 'customer_complete.php', 
    data : 'id='+ id, 
    cache: false, 
    success : function(data){ 
    $('.customer_complete').html(data); 
    } 
    }) 

    $("#"+Type).show(); 
    }); 
</script>

Author:Joanne,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/51792027/passing-an-id-from-foreach-to-modal
PajuranCodes :

I decided to write some code for you, because I found the task an interesting one. The code simulates the situation that you've presented in your question and comments, and is relatively easy to follow. You can run it as it is, but don't forget to replace my db credentials with yours, in connection.php. All files are on the same niveau in the file system hierarchy. So you can create a folder, bring all files in it, and run the index.php page. I used prepared statements to insert into db, thus avoiding any sql injections risc. I also commented that part, just in case you are not familiarize with it.\n\nHave fun.\n\n\n\nindex.php\n\nThis is the main page.\n\n<!DOCTYPE html>\n<html>\n <head>\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=yes\" />\n <meta charset=\"UTF-8\" />\n <!-- The above 3 meta tags must come first in the head -->\n\n <title>Demo - Modal</title>\n\n <!-- CSS assets -->\n <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n\n <style type=\"text/css\">\n body { padding: 20px; }\n .success { color: #32cd32; }\n .error { color: #ff0000; }\n </style>\n\n <!-- JS assets -->\n <script src=\"https://code.jquery.com/jquery-3.3.1.min.js\" type=\"text/javascript\"></script>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\"></script>\n <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n\n <script type=\"text/javascript\">\n $(document).ready(function () {\n $('#type3').on('show.bs.modal', function (event) {\n var modal = $(this);\n var button = $(event.relatedTarget);\n var modelId = button.data('model-id');\n\n $.ajax({\n method: 'post',\n dataType: 'html',\n url: 'new_customer.php',\n data: {\n 'modelId': modelId,\n 'modalId': 'type3'\n },\n success: function (response, textStatus, jqXHR) {\n modal\n .find('.modal-padding')\n .html(response);\n },\n error: function (jqXHR, textStatus, errorThrown) {\n modal\n .find('.modal-messages')\n .removeClass('success')\n .addClass('error')\n .html('An error occurred during your request. Please try again, or contact us.');\n }\n });\n });\n\n $('#type3').on('hide.bs.modal', function (event) {\n var modal = $(this);\n\n modal.find('.modal-padding').html('');\n\n modal\n .find('.modal-messages')\n .removeClass('success error')\n .html('');\n });\n });\n </script>\n </head>\n <body>\n\n <button type=\"button\" data-model-id=\"13\" data-modal-type=\"type3\" data-toggle=\"modal\" data-target=\"#type3\" class=\"modal_button customer_button right\">\n New Customer\n </button>\n\n <div class=\"modal\" id=\"type3\">\n <div class=\"modal-content\">\n <div class=\"modal-title\">\n <h3>New Customer</h3>\n </div>\n <div class=\"modal-messages\"></div>\n <div class=\"modal-padding\"></div>\n </div>\n </div>\n\n </body>\n</html>\n\n\nnew_customer.php\n\nThis page contains the form for adding a new customer into customers table.\n\n<?php\n$modelId = $_POST['modelId'] ?? NULL;\n$modalId = $_POST['modalId'] ?? NULL;\n?>\n\n<script type=\"text/javascript\">\n $(document).ready(function () {\n $('#saveCustomerButton').on('click', function (event) {\n var form = $('#addCustomerForm');\n var button = $(this);\n var modalId = button.data('modal-id');\n var modal = $('#' + modalId);\n\n $.ajax({\n method: 'post',\n dataType: 'html',\n url: 'add_customer.php',\n data: form.serialize(),\n success: function (response, textStatus, jqXHR) {\n modal\n .find('.modal-messages')\n .removeClass('error')\n .addClass('success')\n .html('Customer successfully added.');\n\n $('#resetAddCustomerFormButton').click();\n },\n error: function (jqXHR, textStatus, errorThrown) {\n var message = errorThrown;\n\n if (jqXHR.responseText !== null && jqXHR.responseText !== 'undefined' && jqXHR.responseText !== '') {\n message = jqXHR.responseText;\n }\n\n modal\n .find('.modal-messages')\n .removeClass('success')\n .addClass('error')\n .html(message);\n }\n });\n });\n });\n</script>\n\n<style type=\"text/css\">\n #addCustomerForm {\n padding: 20px;\n }\n</style>\n\n<form id=\"addCustomerForm\" action=\"\" method=\"post\">\n <input type=\"hidden\" id=\"modelId\" name=\"modelId\" value=\"<?php echo $modelId; ?>\" />\n\n <div class=\"form-group\">\n <label for=\"customerName\">Name</label>\n <input type=\"text\" id=\"customerName\" name=\"customerName\" placeholder=\"Customer name\">\n </div>\n\n <button type=\"button\" data-modal-id=\"<?php echo $modalId; ?>\" id=\"saveCustomerButton\" name=\"saveCustomerButton\" value=\"saveCustomer\">\n Save\n </button>\n\n <button type=\"reset\" id=\"resetAddCustomerFormButton\" name=\"resetAddCustomerFormButton\">\n Reset\n </button>\n</form>\n\n\nadd_customer.php\n\nThis page consists of code for handling the saving of the customer into the database.\n\n<?php\n\nrequire 'connection.php';\nrequire 'InvalidInputValue.php';\n\nuse App\\InvalidInputValue;\n\ntry {\n $modelId = $_POST['modelId'] ?? NULL;\n $customerName = $_POST['customerName'] ?? NULL;\n\n // Validate the model id.\n if (empty($modelId)) {\n throw new InvalidInputValue('Please provide the model id.');\n } /* Other validations here using elseif statements */\n\n // Validate the customer name.\n if (empty($customerName)) {\n throw new InvalidInputValue('Please provide the customer name.');\n } /* Other validations here using elseif statements */\n\n /*\n * Save the customer into db. On failure exceptions are thrown if and\n * only if you are setting the connection options correspondingly.\n * See \"connection.php\" for details.\n */\n $sql = 'INSERT INTO customers (\n model_id,\n name\n ) VALUES (\n ?, ?\n )';\n\n /*\n * Prepare the SQL statement for execution - ONLY ONCE.\n *\n * @link http://php.net/manual/en/mysqli.prepare.php\n */\n $statement = mysqli_prepare($connection, $sql);\n\n /*\n * Bind variables for the parameter markers (?) in the\n * SQL statement that was passed to prepare(). The first\n * argument of bind_param() is a string that contains one\n * or more characters which specify the types for the\n * corresponding bind variables.\n *\n * @link http://php.net/manual/en/mysqli-stmt.bind-param.php\n */\n mysqli_stmt_bind_param($statement, 'is', $modelId, $customerName);\n\n /*\n * Execute the prepared SQL statement.\n * When executed any parameter markers which exist will\n * automatically be replaced with the appropriate data.\n *\n * @link http://php.net/manual/en/mysqli-stmt.execute.php\n */\n mysqli_stmt_execute($statement);\n\n /*\n * Close the prepared statement. It also deallocates the statement handle.\n * If the statement has pending or unread results, it cancels them\n * so that the next query can be executed.\n *\n * @link http://php.net/manual/en/mysqli-stmt.close.php\n */\n mysqli_stmt_close($statement);\n\n /*\n * Close the previously opened database connection.\n * Not really needed because the PHP engine closes\n * the connection anyway when the PHP script is finished.\n *\n * @link http://php.net/manual/en/mysqli.close.php\n */\n mysqli_close($connection);\n} catch (InvalidInputValue $exc) {\n /*\n * Throw an error to be catched by the \"error\" callback of the ajax request.\n * This can be achieved by sending a specific or a custom response header to the client.\n *\n * - Specific header: A header containing any already assigned status code.\n * - Custom header: A header containing any NOT already assigned status code. This type of\n * headers have the reason phrase \"Unassigned\" in the official HTTP Status Code Registry.\n *\n * @link https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml HTTP Status Code Registry.\n */\n header('HTTP/1.1 500 Internal Server Error', TRUE, 500);\n echo $exc->getMessage();\n exit();\n} catch (Exception $exc) {\n // For all other system failures display a user-friendly message.\n header('HTTP/1.1 500 Internal Server Error', TRUE, 500);\n echo 'An error occurred during your request. Please try again, or contact us.';\n exit();\n}\n\n\nconnection.php\n\n<?php\n\n/*\n * This page contains the code for creating a mysqli connection instance.\n */\n\n// Db configs.\ndefine('HOST', 'localhost');\ndefine('PORT', 3306);\ndefine('DATABASE', 'tests');\ndefine('USERNAME', 'root');\ndefine('PASSWORD', 'root');\n\n/*\n * Enable internal report functions. This enables the exception handling,\n * e.g. mysqli will not throw PHP warnings anymore, but mysqli exceptions\n * (mysqli_sql_exception).\n *\n * MYSQLI_REPORT_ERROR: Report errors from mysqli function calls.\n * MYSQLI_REPORT_STRICT: Throw a mysqli_sql_exception for errors instead of warnings.\n *\n * @link http://php.net/manual/en/class.mysqli-driver.php\n * @link http://php.net/manual/en/mysqli-driver.report-mode.php\n * @link http://php.net/manual/en/mysqli.constants.php\n */\n$mysqliDriver = new mysqli_driver();\n$mysqliDriver->report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);\n\n/*\n * Create a new db connection.\n *\n * @see http://php.net/manual/en/mysqli.construct.php\n */\n$connection = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE, PORT);\n\n\nInvalidInputValue.php\n\nThis is a custom exception class. An exception of this type is thrown when posted user input values are invalid.\n\n<?php\n\nnamespace App;\n\nuse Exception;\n\n/**\n * Custom exception. Thrown when posted user input values are invalid.\n */\nclass InvalidInputValue extends Exception {\n\n}\n\n\nDefinition of \"customers\" table\n\nI didn't create a models table, so there is no FK.\n\nCREATE TABLE `customers` (\n `id` int(11) unsigned NOT NULL AUTO_INCREMENT,\n `model_id` int(11) DEFAULT NULL,\n `name` varchar(100) DEFAULT NULL,\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n",
2018-08-11T00:42:57
Alex Yokisama :

As I understood, you already have correct id value on the page. Looks like you get it from php script ($model['id']) and store in data-id of your button.\nAlso, looks like you're already able to get this id, when button is clicked. The further action depends on what exactly you are going to do.\n\n$(\".modal_button\").click(function () {\n var id = $(this).data(\"id\"); //here you have an id\n $(some_selector).html(id); //to put it inside elements html\n $(another_selector).attr(\"placeholder\", id); //to use it as placeholder (or any other attribute\n});\n\n\nThis is for usage with js on the same page.\n\nFor POSTing it to the server:\n\n$.ajax({\n type: \"POST\",\n url: your_url,\n data: {\n id: id\n },\n success: function(result) {\n console.log(result);\n //some actions after POSTing\n }\n});\n\n\nOn the server access it via $_POST[\"id\"]. \n\nWhy what you did was wrong?\nYour POST request worked. You can check this using Chrome Dev Tools (Network tab). It posted to the same page and it's ok. The response of the server was an html page with id's built in modals, just as you wanted. But that was the response to the AJAX call and it had no influence to the page you already have loaded. Also, reloading the page you always had \"ID not found\" because reloading page doesn't make POST request.\n\nHere is the general logic of what you need:\nYou already have id on the page. To transfer it to other elements on the same page, building into html markup and so on use JS. \nTo transfer data to the server (for SQL for example) use AJAX. You'd better create a separate file that would be an AJAX handler. That script will deal with POSTed id, make all required actions (like inserting new user to db) and send response (simple success-error code, string or JSON) back to the caller. Then, in AJAX.success you can handle the response and for example notify user if the operation was failed.\n\nHope this helps.",
2018-08-10T18:56:46
yy