How can i get data from a mysql databse using jQuery and AJAX and then alert the result using JavaScipt? [duplicate]

24
June 13, 2018, at 4:30 PM

This question already has an answer here:

  • Using Jquery Ajax to retrieve data from Mysql 4 answers

As the title says, i'm stuck with this issue. I'm not very experienced with jQuery / AJAX, only with JavaScript and PHP. What i want to do is to get data from a mysql database and then alert the result, let's say that the php variable $username is set to Peter. Example:

function getData(user) {
/*Somehow execute MySQL query using jQuery/AJAX: (SELECT id, email FROM
accounts WHERE user='$username')*/
//Set JavaScript variables to the result
var userID = //The ID of user
var email = //Email of user, 
window.alert('User ID: ' + userID + ' Email: ' + email);
} 

I do know that i need to create a php file with the db username, password and host etc, and i've already done that. It's called 'userget.php'

So how do i get the ID and Email from the database? I really need help..

Answer 1

This is a basic setup of an ajax call:

$.ajax({
    url: '/path/to/file',
    type: 'default GET (Other values: POST)',
    data: { user : "USERNAME_TO_GET_DATA_FOR"},
    success: function(response){
        var data = $.parseJSON(response);
        window.alert('User ID: ' + data.id + ' Email: ' + data.email);
    }
});

And yor getuser.php file needs to return json_encoded array containing the userID and email for that user

An example of your getuser.php:

$db = new PDO("mysql:host={$dbhost};dbname={$dbname};charset=utf8mb4", $dbusername, $dbpass);
$username = isset($_POST['user']) ? $_POST['user '] : null;
$stm = $db->prepare("SELECT id, email FROM accounts WHERE user=':username' ");
$stm->execute(array(":username" => $username);
$data = $stm->fetch(PDO::FETCH_OBJ);
echo json_encode($data);
READ ALSO
How to make jquery intellisense work in visualstudio for js file

How to make jquery intellisense work in visualstudio for js file

I working on HTML and JS pages (not a project)

32
How do I disable vertical scroll on a website on desktop and laptop screen resolutions? [on hold]

How do I disable vertical scroll on a website on desktop and laptop screen resolutions? [on hold]

so we are designing a website for a client, we are building our design to a wordpress frame work, the problem is we need the website to be totally unscrollabe on the screen for desktops and laptops

53
Get dynamically created element that was click javascript

Get dynamically created element that was click javascript

I'm trying to track what buttons users click via javascript/jqueryI have the following code

39