I want to receive data using AJAX from PHP which asks a database for some data. All i get from AJAX is NULL.
When i alert the result (e.g. data.name) it says undefined.
HTML, AJAX and jQuery are in the index.php while PHP in edit.php is.
The AJAX request I use ...
$('div[data-toggle="edit"]').click(function() {
var editid = $(this).attr('id').replace('edit','');
$.ajax({
cache: false,
type: 'GET',
url: 'edit.php',
data: editid,
dataType: 'JSON',
}).done(function(data) {
$('#mainlabel').modal('show');
$('input[name=add_name]').val(data.name);
$('input[name=add_date]').val(data.date);
$('input[name=add_image]').val(data.image);
$('input[name=add_info]').val(data.info);
}).fail(function(jqXHR, message) {
alert(message);
});
});
... to receive data from this PHP code.
<?php
require_once('main.conf');
require_once('db.php');
$stmt = $con->prepare("SELECT * FROM datas d WHERE d.dataid = ?");
$stmt->bind_param("i", $_GET["editid"]);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
while ($row = $result->fetch_assoc()) {
$editname = $row["name"];
$editdate = date("Y-m-d", strtotime($row["date"]));
$editimage = $row["image"];
$editinfo = $row["additionalinfo"];
}
$return[] = array("name" => $editname,
"date" => $editdate,
"image" => $editimage,
"info" => $editinfo,
"getid" => $_GET["editid"]); //only for debugging
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($return);
?>
When i invoke the this code manually via edit.php?editid=547 the JSON-result looks like it should.
0
name "Mike Minus"
date "2015-05-12"
image "employee.jpg"
info "some additional info"
getid "547"
With the expected informations i want to fill some input-boxes.
<div class="modal-body mx-3">
<div class="form-group">
<label for="add_name" class="col-form-label">Name:</label>
<input class="form-control validate" type="text" name="add_name" value="">
</div>
<div class="form-group">
<label for="add_name" class="col-form-label">Datum:</label>
<input class="form-control" type="date" name="add_date" size="8" value="">
</div>
<div class="form-group">
<label for="add_image" class="col-form-label">Bild:</label>
<input class="form-control" type="text" name="add_image" value="">
</div>
<div class="form-group">
<label for="add_info" class="col-form-label">Zusatzinfos:</label>
<input class="form-control" type="text" name="add_info" value="">
</div>
</div>
<div class="btn btn-info btn-sm" data-toggle="edit" id="edit547">
<i class="fa fa-pencil-square-o"></i>
</div>
I know there are quite a lot of possible solutions in SO. Using echo instead of return in the PHP code, the appropriate application/json header or other techniques. Nothing could help till yet.
