Adamhumbug Posted September 16, 2018 Share Posted September 16, 2018 Hi All, I am trying to do ajax insert into my database but i need to use the value/name of the button which is being generated from my sql. Each of these buttons needs to become a submit button. This is blowing my mind but any help on this would be amazing. Quote Link to comment Share on other sites More sharing options...
requinix Posted September 16, 2018 Share Posted September 16, 2018 Well, if you're triggering the AJAX then you must be able to know which button was clicked, right? So... pass that information along in the request. Maybe posting code would help explain where the difficulty is? Quote Link to comment Share on other sites More sharing options...
ginerjm Posted September 16, 2018 Share Posted September 16, 2018 As requinix says - show us some code. BTW - the 'value/name' of a button is two different things. I'm guessing you want the value and not the name in your db. And as for 'become a submit button', what's the problem there? Actually I think you probably don't want them to be submit buttons, but rather just a 'button' type so that you don't trigger a form action when you simply want your JS code to process an ajax call. I hope you are ready for a bit of a challenge if you haven't written an ajax call before, nor the script that will be triggered by it and the resulting values returned to the JS code on your client already. Are you sure this has to be an ajax call? Quote Link to comment Share on other sites More sharing options...
Adamhumbug Posted September 16, 2018 Author Share Posted September 16, 2018 17 minutes ago, ginerjm said: As requinix says - show us some code. BTW - the 'value/name' of a button is two different things. I'm guessing you want the value and not the name in your db. And as for 'become a submit button', what's the problem there? Actually I think you probably don't want them to be submit buttons, but rather just a 'button' type so that you don't trigger a form action when you simply want your JS code to process an ajax call. I hope you are ready for a bit of a challenge if you haven't written an ajax call before, nor the script that will be triggered by it and the resulting values returned to the JS code on your client already. Are you sure this has to be an ajax call? Re value/name, i wasnt sure if one was better to use than the other, i know how to set them. I assume i should be using value (makes sense). I think you are right re it not being a submit button. I assume then i am doing an onclick function rather than a for submit. "<div onclick='add_to_translog' name='product" .$row['product_id']. "' id='productID".$row['product_id']."' class='col-md-2 btn btn-primary btn-lg space' value='". $row['product_id'] ."'>". $row['product_name'] . "<br/> £" . $row['product_price'] ."</div>" The above is the line that i am echoing from my database and i have added the onclick to it. It is creating a div, should it actually be an input button in a form? I am up for the challenge and would of course appreciate being pointed in the right direction by you guys. I have not got to the actual ajax bit yet but i have an example that i can have a look at and hopefully model into what i need. Quote Link to comment Share on other sites More sharing options...
requinix Posted September 16, 2018 Share Posted September 16, 2018 It really should be a button, like a <button> or an old-school <input type=button>. It doesn't have to be a submit since you're using AJAX, but if you could if you wanted to (just make sure to cancel the submit event inside your handler). The event handler can know which element triggered the event. What's that code? Quote Link to comment Share on other sites More sharing options...
Adamhumbug Posted September 16, 2018 Author Share Posted September 16, 2018 Ok, so i have updated the echo to be a button. All of the buttons that are created are inside a form. The ajax example that i have modified is below. $(document).ready(function() { $("#IDOFBUTTON").click(function() { $.ajax({ type: "POST", url: "add_to_basket_action.php", dataType: "html", //expect html to be returned success: function(response){ $("#responsecontainer").html(response); //alert(response); } }); }); }); Does this need to be the ID or should it be something else becuase obviuosly there shouldnt be several elements with the same ID? The success part, i have done nothing with and is the same as the example. In my instance i dont really need an alert, i would however, like it to update another section. Basically you click a button and the item clicked is added to a list, like a shopping basket. I assume that the add_to_basket_action.php is the conenction to the database and the sql insert? Quote Link to comment Share on other sites More sharing options...
requinix Posted September 16, 2018 Share Posted September 16, 2018 1 hour ago, Adamhumbug said: Does this need to be the ID or should it be something else becuase obviuosly there shouldnt be several elements with the same ID? Depends. Do you have multiple buttons? You can't use the same ID for all of them, of course, so you would be forced into something else (like classes). 1 hour ago, Adamhumbug said: The success part, i have done nothing with and is the same as the example. In my instance i dont really need an alert, i would however, like it to update another section. Basically you click a button and the item clicked is added to a list, like a shopping basket. You know you aren't sending any actual data through AJAX yet, right? You kinda need to do that. 1 hour ago, Adamhumbug said: I assume that the add_to_basket_action.php is the conenction to the database and the sql insert? Probably? We don't know your application. If you have a question about your code then you're in the best position to find the answer. Quote Link to comment Share on other sites More sharing options...
Adamhumbug Posted September 16, 2018 Author Share Posted September 16, 2018 2 minutes ago, requinix said: Depends. Do you have multiple buttons? You can't use the same ID for all of them, of course, so you would be forced into something else (like classes). Yes i have multiple of them, i dont feel i would have any need for them so will go to a class. Will the ajax use the class to look for a button press? 3 minutes ago, requinix said: You know you aren't sending any actual data through AJAX yet, right? You kinda need to do that. Getting to that bit now, and will no doubt be back here very soon. 4 minutes ago, requinix said: Probably? We don't know your application. If you have a question about your code then you're in the best position to find the answer. I will post some code, but what i mean is, as i am linking this document url: "add_to_basket_action.php", my understanding is that i would put the connection and SQL code in this file? Quote Link to comment Share on other sites More sharing options...
requinix Posted September 16, 2018 Share Posted September 16, 2018 2 minutes ago, Adamhumbug said: Yes i have multiple of them, i dont feel i would have any need for them so will go to a class. Will the ajax use the class to look for a button press? You would change the Javascript so that it does the .click using the right selector (where you have the ID now). 2 minutes ago, Adamhumbug said: I will post some code, but what i mean is, as i am linking this document url: "add_to_basket_action.php", my understanding is that i would put the connection and SQL code in this file? If that's where the AJAX is going then yes, that is where you would need to put the code to do whatever it needs to do. Quote Link to comment Share on other sites More sharing options...
Adamhumbug Posted September 16, 2018 Author Share Posted September 16, 2018 Ok, so i have added the following (which came from a fairly complicated tutorial) and has been amended as i understand it. <script> $(document).ready(){ // Variable to hold request var request; // Bind to the submit event of our form $(".main-product-button").submit(function(event){ // Prevent default posting of form - put here to work in case of errors event.preventDefault(); // Abort any pending request if (request) { request.abort(); } // setup some local variables var $form = $(this); // Let's select and cache all the fields var $inputs = $form.find("button, value"); // Let's disable the inputs for the duration of the Ajax request. // Note: we disable elements AFTER the form data has been serialized. // Disabled form elements will not be serialized. $inputs.prop("disabled", true); // Fire off the request to /form.php request = $.ajax({ url: "actions/add_to_basket_action.php", type: "post", data: { action: this.value }, }); // Callback handler that will be called on success request.done(function (response, textStatus, jqXHR){ // Log a message to the console console.log("Hooray, it worked!"); }); // Callback handler that will be called on failure request.fail(function (jqXHR, textStatus, errorThrown){ // Log the error to the console console.error( "The following error occurred: "+ textStatus, errorThrown ); }); // Callback handler that will be called regardless // if the request failed or succeeded request.always(function () { // Reenable the inputs $inputs.prop("disabled", false); }); }); } </script> Then in the add_to_basket_action.php file i have the following. <?php include '../dbconn.php'; //have a look at the database, may need to rethink this completely if (isset($_REQUEST['add_to_basket_submit'])) { $basket_product_id = $_POST['action']; $sql = "INSERT INTO transaction_log (product_id) VALUES ('$basket_product_id')"; if(mysqli_query($conn, $sql)){ echo "Records added"; header("Location:home.php"); }else{ echo "Something went wrong adding the product"; } mysqli_close($conn); } ?> I cant really tell if i am close or miles away but this is where i am at at the minute. Am i in the right area? Quote Link to comment Share on other sites More sharing options...
requinix Posted September 16, 2018 Share Posted September 16, 2018 You're on the right track. 1. Messed up the syntax with the $(document).ready stuff. Take another look. 2. There is no "add_to_basket_submit" anywhere in what you're submitting so that check in your code won't work. 3. Never put $_POST values directly into a query. Look at mysqli's prepared statements. 4. The script is being called through AJAX so there's no point trying to make it redirect anywhere. Quote Link to comment Share on other sites More sharing options...
Adamhumbug Posted September 16, 2018 Author Share Posted September 16, 2018 ok, so i am now echoing the following (these are the buttons that are being created) <button onclick='add_to_translog' name='product" .$row['product_id']. "' id='productID".$row['product_id']."' class='main-product-button col-md-2 btn btn-primary btn-lg space' value='". $row['product_id'] ."'>". $row['product_name'] . "<br/> £" . $row['product_price'] ."</button>" I have an onclick which i have used to call the following function (not sure if this is the correct method) and have "main-product-button" as a class - i dont know if need both. The following is the script - i have put the function in here but i feel i am still wrong with this. $( document ).ready(function(add_to_translog) { // Variable to hold request var request; // Bind to the submit event of our form $(".main-product-button").submit(function(event){ // Prevent default posting of form - put here to work in case of errors event.preventDefault(); // Abort any pending request if (request) { request.abort(); } // setup some local variables var $form = $(this); // Let's select and cache all the fields var $inputs = $form.find("button, value"); // Let's disable the inputs for the duration of the Ajax request. // Note: we disable elements AFTER the form data has been serialized. // Disabled form elements will not be serialized. $inputs.prop("disabled", true); // Fire off the request to /form.php request = $.ajax({ url: "actions/add_to_basket_action.php", type: "post", data: { action: this.value }, }); // Callback handler that will be called on success request.done(function (response, textStatus, jqXHR){ // Log a message to the console console.log("Hooray, it worked!"); }); // Callback handler that will be called on failure request.fail(function (jqXHR, textStatus, errorThrown){ // Log the error to the console console.error( "The following error occurred: "+ textStatus, errorThrown ); }); // Callback handler that will be called regardless // if the request failed or succeeded request.always(function () { // Reenable the inputs $inputs.prop("disabled", false); }); }); }); The if isset bit, i have put a class name in there - i guess i should be using the name? <?php include '../dbconn.php'; if (isset($_REQUEST['main-product-button'])) { $basket_product_id = $_POST['action']; $sql = "INSERT INTO transaction_log (product_id) VALUES ('$basket_product_id')"; if(mysqli_query($conn, $sql)){ echo "Records added"; }else{ echo "Something went wrong adding the product"; } mysqli_close($conn); } ?> Am i getting closer? Quote Link to comment Share on other sites More sharing options...
requinix Posted September 16, 2018 Share Posted September 16, 2018 1. You took a step backwards with the document.ready. You should not use an onclick with the <button>, so take that back off. Instead you'll use code for it. For the Javascript side, the first line should be just "$(function() {" - using document and .ready is a longer form that you don't actually need to do. No add_to_translog at all. 2. You swapped add_to_basket_submit with main-product-button, but that wasn't the problem. The data you are sending to the PHP script is the data:{action} you have in the Javascript code. Nothing else. Not even the button you clicked. Except your PHP code expects there to be more. If you want to test that the data was submitted then either the use "action" that is in the data being passed, or check that the $_SERVER["REQUEST_METHOD"] is POST. 3. Prepared statements are very important. It's about security and making sure people can't destroy your database. So make sure you take care of it. 4. Now the script is just doing some output without trying to redirect. Keep in mind that AJAX doesn't know whether "Records added" is a good thing or a bad thing. As it is, AJAX is going to think the call worked and you'll get the Hooray message either way. It's possible to indicate to AJAX whether it was good or bad, but for now you can simply use the "response" in the .done callback - like log that message to the console. Quote Link to comment Share on other sites More sharing options...
Adamhumbug Posted September 17, 2018 Author Share Posted September 17, 2018 Ok - i have made your suggested changes to the document ready code and have removed the onclick from the buttons that are being created. I forgot to mention that they are being created from a function (not sure if this is relevent) 16 hours ago, requinix said: You swapped add_to_basket_submit with main-product-button, but that wasn't the problem. The data you are sending to the PHP script is the data:{action} you have in the Javascript code. Nothing else. Not even the button you clicked. Except your PHP code expects there to be more. If you want to test that the data was submitted then either the use "action" that is in the data being passed, or check that the $_SERVER["REQUEST_METHOD"] is POST. I thought that i was sending the value of the button that was being clicked? However i kinda see that i might not be. How about now? I think i am selecting the value from the button that is being clicked and sending that along with the serialised form to the php. $(function() { // Variable to hold request var request; // Bind to the submit event of our form $(".main-product-button").click(function(event){ //Select the value attribute of the button being pressed var buttonvalue = $(this).attr('value'); //Send all form data var dataString = $( "#add_product_to_basket_form" ).serialize(); // Prevent default posting of form - put here to work in case of errors event.preventDefault(); // Abort any pending request if (request) { request.abort(); } // setup some local variables var $form = $(this); // Let's select and cache all the fields var $inputs = $form.find("button, value"); // Let's disable the inputs for the duration of the Ajax request. // Note: we disable elements AFTER the form data has been serialized. // Disabled form elements will not be serialized. $inputs.prop("disabled", true); // Fire off the request to /form.php request = $.ajax({ url: "actions/add_to_basket_action.php", type: "post", data: dataString + '&buttonvalue=' + buttonvalue, }); // Callback handler that will be called on success request.done(function (response){ // Log a message to the console console.log("Hooray, it worked!"); }); // Callback handler that will be called on failure request.fail(function (jqXHR, textStatus, errorThrown){ // Log the error to the console console.error( "The following error occurred: "+ textStatus, errorThrown ); }); // Callback handler that will be called regardless // if the request failed or succeeded request.always(function () { // Reenable the inputs $inputs.prop("disabled", false); }); }); }); I have removed everything apart from the "response" from the .done callback. I have taken on board with the prepared statements and changed from what i had to <?php include '../includes/dbconn.php'; //have a look at the database, may need to rethink this completely $stmt = $conn->prepare("INSERT INTO transaction_log (product_id) VALUES (?)"); $stmt->bind_param("s", $basket_product_id); $basket_product_id = $_POST['action']; $stmt->execute(); $stmt->close(); $conn->close(); ?> I feel like i am heading in the right direction but am still not really sure what is going on. Thanks for your continued help on this. Quote Link to comment Share on other sites More sharing options...
Adamhumbug Posted September 17, 2018 Author Share Posted September 17, 2018 So, the SQL is triggering and is successful. However i am being redirected to the url that i set in the ajax section above rather than staying in the same place. I feel like this may be a really simple mistake but at the same time i could be days away. Quote Link to comment Share on other sites More sharing options...
Barand Posted September 17, 2018 Share Posted September 17, 2018 Is it your form action that is taking you there? If you are using ajax you don't need an html form. This works: Sample.php <?php include("db_inc.php"); $db = pdoConnect('test'); /******************************************************************************* * PROCESS THE AJAX REQUEST ********************************************************************************/ if ($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['action'])) { $stmt = $db->prepare("INSERT INTO transaction_log (product_id) VALUES (?)"); $res = $stmt->execute( [ $_POST['action'] ] ); exit( $res ? 'Product log updated' : 'Oops!' ); } ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="generator" content="PhpED 18.0 (Build 18044, 64bit)"> <title></title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script type='text/javascript'> $(function() { $(".main-product-button").click( function() { var id = $(this).val() $.post ( "sample.php" , {"action":id} , function(resp) { alert(resp) } , 'TEXT' ) }) }) </script> </head> <body> <button name='product1' id='productID1' class='main-product-button col-md-2 btn btn-primary btn-lg space' value='1'>Widget<br/> £2.50</button> <button name='product2' id='productID2' class='main-product-button col-md-2 btn btn-primary btn-lg space' value='2'>Gizmo<br/> £4.50</button> <button name='product3' id='productID3' class='main-product-button col-md-2 btn btn-primary btn-lg space' value='3'>Wotsit<br/> £6.50</button> </body> </html> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.