Jump to content

Adamhumbug

Members
  • Content Count

    21
  • Joined

  • Last visited

Community Reputation

0 Neutral

About Adamhumbug

  • Rank
    Member
  1. Adamhumbug

    Ajax Insert Bason on Button Value

    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.
  2. Adamhumbug

    Ajax Insert Bason on Button Value

    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) 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.
  3. I am trying to count all of the rows that have a unique value in a field (meaning that it only appears once) I have a select that selects the rows but i would like this to be a count of the number of rows primerily Secondly i would like to turn this into a delete statement. (i thought i could change select to delete but it appears this is not correct) SELECT line_number,logon_time,product_id,transaction_product_qty,transaction_status, MIN(transaction_id) as transaction_id FROM transaction_log GROUP BY transaction_id HAVING COUNT(*) = 1"
  4. Adamhumbug

    Ajax Insert Bason on Button Value

    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?
  5. Adamhumbug

    Ajax Insert Bason on Button Value

    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?
  6. Adamhumbug

    Ajax Insert Bason on Button Value

    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? Getting to that bit now, and will no doubt be back here very soon. 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?
  7. Adamhumbug

    Ajax Insert Bason on Button Value

    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?
  8. Adamhumbug

    Ajax Insert Bason on Button Value

    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.
  9. 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.
  10. Adamhumbug

    PHP function - Undefined Variable

    Thanks Brand, That did really help. Kind regards Adam
  11. Hi, I am trying to select a single value from a database which will be the highest integer in a column. I have written $sql1 = "SELECT MAX(transaction_id) from pos_basket"; $result1 = $conn->query($sql1); $value =mysqli_fetch_object($result1); $_SESSION['transaction_id']=$value; Which is returning Array ( [transaction_id] => stdClass Object ( [MAX(transaction_id)] => 3 ) I would like it to be returning just the number 3 I have tried several fetch variations but seem to be getting a lot of fatals. I am sure that this is a very simple solution. Thanks in advance
  12. Adamhumbug

    PHP function - Undefined Variable

    Ok, thanks guys for the pointers. So i have returned the first value of the array $firstProd = $firstarray[0]; return $firstProd; Then i have writted a second function function useFirstProdValue(){ echo $firstProd; } i still get undefined variable so i am assuming that there is a step i need to take to get the variable into my new function. I have tried adding $firstProd into the () but this gives me a fatal. The google resuklts are not all too clear when looking at this.
  13. Adamhumbug

    PHP function - Undefined Variable

    Hi, Thanks so much for your reply. What you suggested worked for the most part - there is obviously something i am missing here. I now have the following function function showSideBarProductButtons($conn){ $sql = "SELECT DISTINCT product_catagory FROM pos_pr GROUP BY product_catagory ORDER BY product_catagory ASC"; if($result = mysqli_query($conn, $sql)){ if(mysqli_num_rows($result) > 0){ $firstarray = array(); while($row = mysqli_fetch_array($result)){ echo "<a href=home.php?product_catagory=" . urlencode($row['product_catagory']) ."><div class='col-md-12 btn btn-primary tb-space'>" . $row['product_catagory'] . "</div></a>"; //below - $prods becomes every product one at a time as it is in while $prods =$row['product_catagory']; //below - adds value of $prods to array called $firstarray one at a time until end array_push($firstarray,$prods); } mysqli_free_result($result); }else{ echo "This did not work!"; } //below - spits out first value of array } return $firstarray[0]; } And the following home page <div class="col-md-7 border"> <?php $setFirstArray = showSideBarProductButtons($conn); if (strpos($_SERVER['REQUEST_URI'], "product") == false){ $product_cat = $setFirstArray; }else{ $product_cat = urldecode($_GET['product_catagory']); } //this is looking at functions.php and running the code from there getProductMainButtons($conn, $product_cat); ?> </div> The issue is that the sidebar buttons now appear in the main section. I am assuming that i have put something in the wrong place? Thanks again Kind Regards
  14. Hi All, I have been trying to condilidate my code into a functions file so that i can call bits of code. I have a page that populates some buttons, using data from a DB, it decides what buttons to show based on information in the URL. The issue that i was having was that until they press another button, there is not the required information in the URL to be used in the SQL. To combat this i wrote a bit of code (the bit that is now not working) if (strpos($_SERVER['REQUEST_URI'], "product") == false){ $product_cat = $setFirstArray; }else{ $product_cat = urldecode($_GET['product_catagory']); } This was working but i now appear to have broken it by moving me code into functions. The error that i am getting is Notice: Undefined variable: setFirstArray in /homepages/29/d742272110/htdocs/home.php on line 20 This is the second line of the code above. function showSideBarProductButtons($conn){ $sql = "SELECT DISTINCT product_catagory FROM pos_pr GROUP BY product_catagory ORDER BY product_catagory ASC"; if($result = mysqli_query($conn, $sql)){ if(mysqli_num_rows($result) > 0){ $firstarray = array(); while($row = mysqli_fetch_array($result)){ echo "<a href=home.php?product_catagory=" . urlencode($row['product_catagory']) ."><div class='col-md-12 btn btn-primary tb-space'>" . $row['product_catagory'] . "</div></a>"; //below - $prods becomes every product one at a time as it is in while $prods =$row['product_catagory']; //below - adds value of $prods to array called $firstarray one at a time until end array_push($firstarray,$prods); } mysqli_free_result($result); }else{ echo "This did not work!"; } //below - spits out first value of array $setFirstArray=$firstarray[0]; echo $setFirstArray; } } The above is the function that creates the side buttons. It also sets the varaible $setFirstArray to be the first value in the array - this works and the echo at the end confirms this. What is not working (the code mentioned above) says that the variable $setFirstArray is not defined. <div class="col-md-7 border"> <?php if (strpos($_SERVER['REQUEST_URI'], "product") == false){ $product_cat = $setFirstArray; }else{ $product_cat = urldecode($_GET['product_catagory']); } //this is looking at functions.php and running the code from there getProductMainButtons($conn, $product_cat); ?> </div> Above is the code for this section in full. Any help or pointers on this would be apprecitaed.
  15. Hi all, I have been totally lost with this and have done some reading around the topic. I have made some changes but i am still having no luck in getting it to work. This is my Register.php <!DOCTYPE html> <html> <head> <title>Register</title> <link rel="stylesheet" type="text/css" href="style.css"> <script type="text/javascript" src="java.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { //##### send add record Ajax request to response.php ######### $("#Spirit").click(function (e) { e.preventDefault(); if($("#textfield").val()==='') { alert("Please enter some text!"); return false; } var myData = 'content_txt='+ $("#textfield").val(); //build a post data structure jQuery.ajax({ type: "POST", // HTTP method POST or GET url: "response.php", //Where to make Ajax calls dataType:"text", // Data type, HTML, json etc. data:myData, //Form variables success:function(response){ $("#buttonArea").append(response); $("#textfield").val(''); //empty text field on successful $("#Spirit").show(); //show submit button }, error:function (xhr, ajaxOptions, thrownError){ $("#Spirit").show(); //show submit button alert(thrownError); } }); }); </script> </head> <body> <div class="headerBar"> TOP </div> <div class="sideBar"> <div class="productCatagoryButton" id="sideBarSettings">Settings</div> <form method="post"> <?php require 'productCatagory.php' ?> </form> </div> <div class="mainArea"> <div class="buttonArea" id="buttonArea"> <?php /*require 'productButtons.php'*/ ?> <?php require_once 'response.php' ?> <input type="text" name="textfield"> </div> <div class="itemArea"> <div class="itemisedArea"> <table style="width:100%;"> <tr> <th style="width:70%;">Product</th> <th>Price</th> </tr> </table> </div> <div class="keypadArea"> <div class="payButton">PAY</div> </div> </div> </div> </body> </html> This is my response.php <?php include_once("dbconn.php"); if(isset($_POST["textfield"])) { $pro_cat_from_button = $_POST["textfield"]; $sql = "SELECT * FROM products WHERE product_catagory = '$pro_cat_from_button'"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { $pro_id = "productButton".$row["product_id"]; $pro_display = $row["product_name"]. "<br/><br/>"."£". $row["product_price"]; echo <<< "EOT" <div class="productButton" id="$pro_id">$pro_display</div> EOT ; } } else { echo "No results found"; } $conn->close(); } ?> This is my dbconn.php <?php $servername = "localhost"; $username = "root"; $password = "root"; $dbname = "register"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } This is my productcatagory.php that creates the sidebar buttons that i want to use to show other buttons when clicked. <?php include 'dbconn.php'; $sql = "SELECT DISTINCT(product_catagory) FROM `products`"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { $pro_cat = $row["product_catagory"]; echo <<< "Escaped" <input type="submit" name="productCatagoryButton" class="productCatagoryButton" id="$pro_cat" value="$pro_cat"/> Escaped ; } } else { echo "0 results"; } $conn->close(); ?> this is my productbuttons.php file that i have included to show an example of what i want to happen. <?php include 'dbconn.php'; $sql = "SELECT * FROM products WHERE product_catagory = 'Spirit'"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { $pro_id = "productButton".$row["product_id"]; $pro_display = $row["product_name"]. "<br/><br/>"."£". $row["product_price"]; echo <<< "EOT" <div class="productButton" id="$pro_id">$pro_display</div> EOT ; } } else { echo "No results found"; } $conn->close(); ?> So obviously this isnt working but let me explain what i would like it to do. The prouct catagory buttons are populated in a side bar when the page loads - the sql selects all of the different product catagories and creates a button for each unique value in the table. I want to - when these buttons are clicked run a query that shows all of the products that match the product type that the button represents. (I know that my code isnt doing that, it is currently looking at a text box which i tried to utilise to understand where i was going wrong. This text box will not be part of the final product) So if you click the Spirit button, all of the products in the table with the product_catagory "Spirit" should be displayed. I can get the products to display when the page loads, but am struggling to get this to happen from a button click. I know you guys have tried to guide me before and i really appreciate it - can we start again with what i have? Kind Regards Adam
×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.