0v3k Shi3ld3r 0v3k Shi3ld3r - 4 months ago 22
SQL Question

Ajax Button to fetch data without refresh?

I would like to know how a button submit can interact with AJAX to SELECT FROM data as a MySQL query without refreshing the page . I already have a text box interacting with AJAX so that the page does not refresh when the user inputs the text and presses enter but have no idea how to make the button do it my code below shows how im getting the text box to insert data without refreshing

Here is my script for the textbox

<div id="container">
About me<input type="text" id="name" placeholder="Type here and press Enter">
</div>

<div id="result"></div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#name').focus();
$('#name').keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 13) {
var info = $('#name').val();
$.ajax({
method: "POST",
url: "about_me_action.php",
data: {name: info},
success: function(status) {
$('#result').append(status);
$('#name').val('');
}
});
};
});
});
</script>


Here is the action

<?php

if (isset($_POST['name'])) {
echo '<h1>'.$_POST['name'];

include('..\db.php');
$con = mysqli_connect($dbsrvname, $dbusername, $dbpassword, $dbname);

$name = $_POST['name'];
$name= mysqli_real_escape_string($con, $name);



$q = mysqli_query($con,"SELECT * FROM tbl1 WHERE username = '".$_COOKIE[$cookie_name]."'");


while($row = mysqli_fetch_assoc($q)){
//echo $row['id'];
$id = $row['id'];
}

$result=$con ->query=("REPLACE INTO about_user (about_me,number) VALUES ('".$name."','".$id."')");

$insert = $con->query($result);

echo "About Me Updated";
}

?>


Now all I need to do is have the below example of a button do something similar but instead of INSERTING just SELECT , how can i change the above script to allow a button to handle the action please?

<form

action="action_mail_view.php" method="post">

<input type="submit" class="button" name='msubmit' value="View Mail"/>

</form>

Answer

function callServer() {
  $('#mail-button').on('click', function() {
    var info = $('#name').val();
    $.ajax({
      method: "POST",
      url: "about_me_action.php",
      data: {
        name: info
      },
      success: function(status) {
        $('#result').append(status);
        $('#name').val('');
      }
    });
  });

}

$(document).ready(function() {
  $('#name').focus();
  $('#name').keypress(function(event) {
    var key = (event.keyCode ? event.keyCode : event.which);
    if (key == 13) {
      $('#mail-button').trigger('click');
    };
  });
});
<form action="action_mail_view.php" method="post">

  <input type="submit" class="button" id="mail-button" name='msubmit' value="View Mail" />

</form>