menu

Questions & Answers

How do I go about getting a value from button function to be used in AJAX and sql finding?

So I have this button which is basically there to allow the user to change a given category name. So when you press this edit button, pop-up alert will come up on screen with an input field and you write whatever you want inside the input field, press okay and it should update the value with what ever you typed in that input field. This is my code so far :

<tbody>
<?php foreach (get_all_categories() as $r) { ?>

<td>
     <?php
           echo '<button type="button" class="btn btn-warning  edit-category"><i class="fa fa-pencil-square-o"></i> Edit</a></button> 
                 <input type="hidden" value="'. $r['category_id'] .'"  name="edit[]">';
     ?>
</td>

<?php } ?>
</tbody>


<script>

var id;
$('button.edit-category').click(function(e) {
id = $(this).parent()[0].childNodes[3].value;
  swal({   title: "An input!",   
    text: "Write something interesting:",   
    type: "input",   
    showCancelButton: true,   
    closeOnConfirm: false,   
    animation: "slide-from-top",   
    inputPlaceholder: "Write something" 
  }, 
    function(inputValue){   
      if (inputValue === false) return false;      
      if (inputValue === "") {     
        swal.showInputError("You need to write something!");     
        return false   }      
        swal("Nice!", "You wrote: " + inputValue, "success"); 
        //alert(inputValue);

        $.post( "edit_category_name.php", { editcategory: id,inputValue}, function( data ) {

        });

      }
      );

setTimeout(function () { location.reload(1); }, 5000);
});

</script>

edit_category_name.php :

<?php include '../core/session.php'; ?>

<?php admin_protect (); 

if (isset($_POST['editcategory'])) {
   change_category_name($_POST['editcategory']);
   echo 200;
}
else {
   echo 404;
}


?>

Function change_category_name:

function change_category_name ($category_id) {
$category_id = (int)$category_id;

mysql_query("UPDATE `mock_exam_category` SET `category_name` = '$category_id' WHERE `category_id` = '$category_id'");

}

inputValue is the variable where the input user types in will be stored

I am not fully sure how to do the function, Please can someone help me fix this. I hope I have described the question in detail however if you need any further clarification please ask, Thanks

Answers(1) :

This is a basic example of using Ajax with form data. You can change it for any need, such as a login, settings, or registration form.

I use something like this when I send any data to my server:

I fetch the HTML elements with the data I need by using the data attributes (data-id, data-user, data-XYZ) and security token, and then send that data to the server side for verification. Once the data is verified, it is inserted into the database. Here is an article that covers validating data before the data is sent to the server.

This example Ajax function can send the data to a remote address and return a response, errors, or other data. Another example can be found, which uses the jQuery $.ajax method to send data to a server instead of the $.post method below:

Sending Data:

e.stopPropagation();
var id = $(this).data('id');
var token = document.getElementById("token").value;
$.post("https://{server-address}/process.php",{
    data: id,
    token: token
},

Receive Data Response:

function(data, status){
    $("#load").html(data);
});

Full Code:

$(document).on('click', '.report', function(e) { //on click, if ajax loaded in or not
    e.stopPropagation(); 
    var id = $(this).data('id');
    var token = document.getElementById("token").value;
    $.post("https://{server-address}/process.php",{
        data: id,
        token: token
    },
    function(data, status){
        $("#load").html(data);
    });
});

The token variable is to prevent Cross-Site Request Forgery. Read more about this here Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet

Comments:
2023-01-20 23:01:03
Hi, thanks for the feedback but how would I get so that what ever user has typed inside that input field, will then be used to update the value in my database ?
2023-01-20 23:01:03
var token = document.getElementById("token").value; replace token to whatever the id of the element the user is typing in
2023-01-20 23:01:03
Also use data attribute in your html to retrieve id. like <div class="post-report" data-id="id"> then var postID = $(this).data('id');
2023-01-20 23:01:03
I sort of getting what you telling me, but the way I have structured out and the way I am carrying out is sort of different i think from what you said
2023-01-20 23:01:03
still confused about how to go about doing this
2023-01-20 23:01:03
It's just i am not fully sure where I will be able to pass in the user input value so that it updates the database query
2023-01-20 23:01:03
Which part? after the ajax submits it? on click, or inserting? I can't chat but I don't mind giving examples for what works for me
2023-01-20 23:01:03
well I am not 100% sure if my edit_category_name.php and the function for sql query is correct
2023-01-20 23:01:03
Use mysqli $conn->query("insert whatever")
2023-01-20 23:01:03
$conn = new mysqli($host, $user, $password, $database);
2023-01-20 23:01:04
I am sorry to ask, but is there anyway we can take this as a chat ? like how can we take this into a chat coversation if that is possible