Lucas Lucas -4 years ago 73
Javascript Question

Jquery .onclick POST var using ajax and receiving data from mysql



I'm trying this:

- Onclick on button get this.data-id as id in a DB select

- These data will be dynamically shown in a modal

What I dont know is how to work with ajax, can anyone help?




HTML

<a data-toggle="modal" data-id="'.$method['id'].'" title="Visualizar" class="itemview btn btn-info btn-mini" href="#MethodView">Visualizar</a>


.php

if(!empty($_POST)){
if (isset($_POST['id']) && $_POST['id'] > 0){
$id=$_POST['id'];
GetPaymentMethodView();
}
}
function GetPaymentMethodView() {
global $db;
try{
$query = $db->query("SELECT * FROM payment_methods WHERE id=$id");
$row=$query->fetch(PDO::FETCH_ASSOC);
$result['success'] = true;
$result['result'] = $row;
echo json_encode($result);
return true;
} catch (PDOException $pe) {
return false;
}
}


.js

$('.itemview').click(function (e) {
e.preventDefault();
var uid = $(this).data('id');
$.ajax({
type: "POST",
url: "resources/controllers/get.php",
data: 'id='+uid,
dataType: "json",
success: function (data) {
if (data.success) {
console.log(data.result);
console.log(data.result.id);
} else {
alert("error");
}
}
});
});

Answer Source

In try small modification

try{
            $query = $db->query("SELECT id, name, bank_info FROM payment_methods WHERE id=$id");
            $row=$query->fetch(PDO::FETCH_ASSOC); 
            $result['success'] = true;
            $result['result'] = $row;
            echo json_encode($result);
            exit;
        return true;
        }

In js small editing

success: function (data) {
            if (data.success) {
                //How to show rows in php?
               console.log(data.result);
               console.log(data.result.id);
            } else {
                alert("error");
            }
        }

And see in browser console to understand.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download