I'm using PHP and trying to get values from a MySQL database using jQuery/AJAX.
My mysql table has four columns: id, tail, cg and cw
My php code looks like this:
<?php
$inputvalue = $_POST;
$errors = false;
$result = false;
$mysqli = new mysqli('localhost', "root", "", "tp");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
foreach ($inputvalues as $key => $value) {
if(isset($value) && !empty($value)) {
$inputvalues[$key] = $mysqli->real_escape_string( $value );
} else {
$errors[$key] = 'The field '.$key.' is empty';
}
}
if( !$errors ) {
$addresult = "
SELECT *
FROM `air_cg`
WHERE `tail` = '" . $inputvalue['tail'] . "'
ORDER BY `id` DESC
";
if( $result = $mysqli->query($addresult) ) {
// collect results
while($row = $result->fetch_all())
{
$returnResult = $row;
}
}
}
mysqli_close($mysqli);
echo json_encode(['result' => $returnResult, 'errors' => $errors]);
exit;
?>
The resulting JSON has this format:
{"result":[["255","Lapdogie","1","2"],["254","Lapdogie","23","234"],["253","Lapdogie","132","454"]],"errors":false}
My javascript code that im using for the ajax function and to parse the resulting JSON looks like this:
function getcgdata(aa){
$.ajax({
type: "POST",
url: "drawchart.php",
data: {tailnumber:taildata},
dataType: 'json',
cache: false,
})
.success(function(response) {
$('input').removeClass('error').next('.errormessage').html('');
if(!response.errors && response.result) {
$.each(response.result, function( index, value) {
var chartdata=(value);
var cgdata =(cg.value);
console.log(chartdata);
console.log(cgdata);
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
}
The console log for chartdata shows this:
["256", "Lapdogie", "232", "333"]
["239", "Lapdogie", "23", "12"]
["238", "Lapdogie", "1232", "1232"]
The console log for cgdata only shows one value many times:
232
232
232
I am not sure if the issue is with my PHP code or with the way im trying to parse the JSON.
i dont see that you define cg.value..
you use
var cgdata =(cg.value);
but cg is where defined?
it should be probably something like chartdata[3] .. ?
Rajdeep Paul's suggestion below worked for me for this particular situation:
Change
var cgdata =(cg.value);
to
var cgdata = value[2];
I'm aware that there are many issues with my code as pointed out by Ludovit Scholtz and Magnus Eriksson and I shall refine it at a later stage.
Thank you all!
Related
When I run the code shown below on my website, I have the following error in my Chrome console: Uncaught SyntaxError: Unexpected end of JSON input.
jQuery:
$('#SearchBtn').click(function() {
$.ajax({
type: 'POST',
url: 'request.administration.php',
data: {id: $("#InputId").val()},
cache: false,
success: function(data) {
if (data == 1) {
console.log("not found");
} else {
$("#InputFirstname").val(data[0]);
$("#InputLastname").val(data[1]);
$("#InputPhone").val(data[2]);
}
}
});
});
PHP:
$sql = "SELECT * FROM User WHERE id=" . $_POST["id"];
if ($result = mysqli_query($link, $sql)) {
if (mysqli_num_rows($result) == 1) {
$row = mysqli_fetch_assoc($result);
$firstname = $row["firstname"];
$lastname = $row["lastname"];
$phone = $row["phone"];
$values = array(
$firstname,
$lastname,
$phone
);
json_encode($values);
} else {
echo "1";
}
}
As a matter of fact, I don't know how to display my firstname, lastname and phone number, from a Json function. I've read similar topics but I didn't get the answer to my question.
I did some checking before I came to you for help:
-the input ids are correct.
-the PHP creates the array correctly.
-when I run a console.log(data), nothing happens.
Thank you in advance to those who will be able to help me.
How to display the data title, image and content?
Here's the code:
view.php
$id = $_REQUEST['edit_literature_id'];
$literature = $_REQUEST['literatureID'];
$module = $_REQUEST['edit_moduleId'];
if (isset($id)) {
$dataArr = array();
$responseArr = array();
$sql = "SELECT * FROM $literature WHERE `id`='".$id."'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$data['title'] = $row['title'];
$data['name'] = 'data:image/jpeg;base64,' . base64_encode($row['name']);
$data['content'] = $row['content'];
array_push($dataArr, $data);
}
echo json_encode($dataArr);
}
mysqli_free_result($result);
} else {
echo "No Record";
}
}
index.php
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
rowId = $(this).attr('data-id');
moduleData = $(this).attr('data-module');
literatureData = $(this).attr('data-literature');
$('#edit_id').val(rowId);
$('#edit_module').val(moduleData);
$('#edit_literature').val(literatureData);
$('#edit_imageId').val(rowId);
$('#update').val('update');
$.ajax({
type: 'POST',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (data) {
alert(data)
}
});
});
});
What I'm trying to do is to get the title, image and content.
How to get the value of title, image and content?
How to call the "title", "name" and "content" from the php?
console.log('DATA: ' + data);
No need to use while loop for result. Also remove extra $dataArr and $responseArr
Update your code to:
in view.php
$id = $_REQUEST['edit_literature_id'];
$literature = $_REQUEST['literatureID'];
$module = $_REQUEST['edit_moduleId'];
if (isset($id)) {
$sql = "SELECT * FROM $literature WHERE `id`='".$id."'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
$data['title'] = $row['title'];
$data['name'] = 'data:image/jpeg;base64,' . base64_encode($row['name']);
$data['content'] = $row['content'];
echo json_encode($data); exit;
}
mysqli_free_result($result);
}
}
$data['error'] = "No Record";
echo json_encode($data); exit;
Index.php
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
rowId = $(this).attr('data-id');
moduleData = $(this).attr('data-module');
literatureData = $(this).attr('data-literature');
$('#edit_id').val(rowId);
$('#edit_module').val(moduleData);
$('#edit_literature').val(literatureData);
$('#edit_imageId').val(rowId);
$('#update').val('update');
$.ajax({
type: 'POST',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (data) {
var response = jQuery.parseJSON(data);
var title = response.title;
var name = response.name;
var content = response.content;
alert(title);
alert(name);
alert(content);
}
});
});
});
After taking data from jQuery side, you can set value in html side using id or class attribute in jQuery.
How your ajax receiving .php file should look:
$validLiteratureIds = ['yourTable1', 'yourTable2'];
if (!isset($_GET['edit_literature_id'], $_GET['literatureID']) || !in_array($_GET['literatureID'], $validLiteratureIds)) {
$response = ['error' => 'Missing/Invalid Data Submitted'];
} else {
$conn = new mysqli('localhost', 'root', '', 'dbname');
$sql = "SELECT title, name, content
FROM `{$_GET['literatureID']}`
WHERE `id` = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $_GET['edit_literature_id']);
$stmt->execute();
$stmt->bind_result($title, $name, $content);
if (!$stmt->fetch()) {
$response = ['error' => 'No Record'];
} else {
$response = [
'title'=> $title,
'name' => 'data:image/jpeg;base64,' . base64_encode($name),
'content' => $content
];
}
}
echo json_encode($response);
Important practices:
Validate the user input so that only qualifying submissions have the privilege of accessing your database.
Write the failure outcomes before success outcomes consistently throughout your project, this will make your scripts easier to read/follow.
Always use prepared statements and bind user-supplied data to placeholders into your query for stability/security.
The tablename cannot be bound like the id value; it must be written directly into your sql string -- this is why it is critical that you validate the value against a whitelist array of literature ids.
There is no need to declare new variables to receive the $_GET values; just access the values directly from the superglobal array.
I am going to assume that your id is a primary/unique key in your table(s), so you don't need to loop over your result set. Attempt to fetch one row -- it will either contain data or the result set was empty.
Call json_encode() only once and at the end of your script.
It is not worth clearing any results or closing a prepared statement or a connection, because those tasks are automatically done when the script execution is finished anyhow -- avoid the script bloat.
As for your jquery script:
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (response) {
if (response.hasOwnProperty('error')) {
console.log(response.error);
} else {
console.log(response.title, response.name, response.content);
}
}
});
});
});
I've trim away all of the irrelevant lines
changed POST to GET -- because you are merely reading data from the database, not writing
parseJSON() is not necessary -- response is a ready-to-use object.
I am checking for an error property in the response object so that the appropriate data is accessed.
Both scripts above are untested (and completely written from my phone). If I have made any typos, please leave me a comment and I'll fix it up.
I am trying to make a user search system like facebook using ajax and php json. But i have one problem.
From the data users table have Marc Zuckerberg, Marc Zeyn, Marc Alp. I mean 3 user first name is same, so normaly when i write the Marc name then i should be get all Marc names from data. Like
<div class="ul">Marc Zuckerbert</div>
<div class="ul">Marc Zeyn</div>
<div class="ul">Marc Alp</div>
but i am not getting all Marc names just i am getting one marc result. Chrome developer console show me all Marc name but not show my within HTML. I think i need some code from ajax success.
JS
$('body').delegate('#searchkey','keyup', function(){
clearTimeout(timer);
timer = setTimeout(function(){
var box = $('#searchkey').val();
contentbox = $.trim(box);
var dataString = 'keys=' + contentbox;
if(contentbox !==''){
$.ajax({
type: "POST",
url: siteurl +"requests/search.php",
data: dataString,
dataType:"json",
cache: false,
beforeSend: function(){},
success: function(data){
$('.un').html(data.username);
$('.uf').html(data.fullname);
}
});
}
});
});
search.php
<?php
include_once 'inc.php';
if(isset($_POST['keys'])) {
$keys = mysqli_real_escape_string($db, $_POST['keys']);
$keyRestuls = $WidGet->SearchUser($keys);
if($keyRestuls) {
// If array is in data
foreach($keyRestuls as $datas) {
$dataUsername = $datas['username'];
$dataUserID = $datas['fullname'];
$data = array(
'username' => $dataUsername,
'fullname' => $dataUserID
);
echo json_encode( $data );
}
}
}
?>
SearchUser function is here
public function SearchUser($keys){
$keys = mysqli_real_escape_string($this->db, $keys);
$result = mysqli_query($this->db,"SELECT
username,
uid,
fullname FROM
users WHERE
username like '%{$keys}%' or fullname like '%{$keys}%'
ORDER BY uid LIMIT 10") or die(mysqli_error($this->db));
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)) {
$data[]=$row;
}
if(!empty($data)) {
// Store the result into array
return $data;
}
}
Your PHP script is generating a malformed JSON
{"username":"marc1","fullname":"Marc Zuckerberg"}
{"username":"marc3","fullname":"Marc Zeyn"}
{"username":"marc2","fullname":"Marc Alp"}
It shoulds generate
[
{"username":"marc1","fullname":"Marc Zuckerberg"},
{"username":"marc3","fullname":"Marc Zeyn"},
{"username":"marc2","fullname":"Marc Alp"},
]
You can fix it by appending to an array instead of writting each row independamently
foreach($keyRestuls as $datas)
{
$dataUsername = $datas['username'];
$dataUserID = $datas['fullname'];
$data[] = array(
'username' => $dataUsername,
'fullname' => $dataUserID
);
}
echo json_encode( $data );
And then you'll have to loop over $data in your JS, I suggest you use $.each
function success(data) {
$.each(data, function(key, value) {
console.log(value.username + ": " + value.fullname);
})
}
I've seen that there has been a lot of questions about this but I did not find any specifics that could apply to my case so if I'm creating a duplicate, sorry for that.
I am trying to retrieve data from SQL database with php file that passes the data to ajax call. Everything seems to be working fine, just when I try to output data into console I get "undefined" variable, even when I tried accessing a precise part of the array with data.story for example. I have also tried data[0].story but that gave me an error that 'story' field of undefined cannot be accessed.
The code is below:
Thanks for your help guys.
my php file:
<?php
$con = mysqli_connect('localhost','root','password','db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$array = array();
$sqlFetch = "SELECT s.storyTitle, s.story, s.lattitude, s.longitude,
u.nickname, u.platformUsed, u.sexuality, u.gender, u.age, s.category,
s.dateRecorded FROM stories AS s INNER JOIN users AS u ON u.email = s.email
WHERE s.postStatus != 'published'";
$result = mysqli_query($con,$sqlFetch);
if(!is_null($result->num_rows)){
$encode = array();
while($row = mysqli_fetch_assoc($result)) {
$encode[] = $row;
}
echo json_encode($encode);
}
?>
and ajax code:
$.ajax({
type: 'post',
url: "http://localhost/wordpress/wp-content/themes/TinDA/js/loadData.php",
dataType: 'json',
data: "",
}).done(function(data){
console.log(data);
//tried also: console.log(data.story); and data[0].story;
});
It seems that you are mixing the mysqli connection for
Procedural Style with Object Oriented Style
Procedural:
$con = mysqli_connect('localhost','root','password','db');
$result = mysqli_query($con, "SOME SELECT STATEMENT");
while ($row = mysqli_fetch_assoc($result)){
$data[] = $row;
}
$rows = mysqli_num_rows($result);
if($rows){
json_encode(array('data' => $data, 'msg'=> 'successs'));
} else {
json_encode(array('data' => $data, 'msg'=> 'error or no records...'));
}
OOP:
$con = new mysqli('localhost','root','password','db');
if($con->connect_errno){
echo "WTF didn't work!!" . $con->connect_error;
}
$res = $con->query('SOME SELECT STMNT');
while ($row = $res->fetch_assoc()){
$data[] = $row;
}
$rows = $con->num_rows;
if($rows){
json_encode(array('data' => $data, 'msg'=> 'successs'));
}else {
json_encode(array('data' => $data, 'msg'=> 'error or no records...'));
}
I also like to use this version of ajax (different with 3.0 may not work).
You can then see the data errors. Note, you can have a successful ajax call and return but still have an error.
$.ajax( '/http://localhost/...', {
type: 'POST',
dataType: 'json',
success: function( json ) {
console.log( json );
},
error: function( req, status, err ) {
console.log( 'WTF!!', status, err );
}
});
PHP PAGE:
<?php
include "linkpassword.inc";
function showVotes()
{
$showresult = mysql_query("SELECT * from mms") or die("Invalid query: " . mysql_error());
$row = mysql_fetch_assoc($showresult);
}
function addVote()
{
$sql= "UPDATE mms SET votes = votes+1 WHERE color = '".$_POST['color']."'";
$result= mysql_query($sql) or die(mysql_error());
return $result;
}
addVote();
showVotes();
?>
I am trying to get the output of the array to load into a JavaScript page where I can break up the array into seperate divs that have IDs assigned to them. Here is what I tried
<script>
$(document).ready(function () {
$('.answer').click(function (e) {
var color = $(this).attr("data-color");
$.ajax({
type: 'POST',
url: 'mm.php',
data: { color: color},
dataType: 'json',
cache: false,
success: function(showVotes) {
$('#rvotes').html(showVotes[0]);
},
error: function (jqXHR) {
}
})
})
});
</script>
Where am I going wrong??
From what you've posted in comments, what you have is an array of objects.. not html, as your function seems to indicate. Depending on what you want done, the answer would be either of the following, to access that object's properties:
showVotes[0].votes
Or
showVotes[0]['votes']
Eg:
$('#rvotes').html(showVotes[0].votes);
Or etc.
Second attempt:
Firstly, change your current 'showVotes' function to this:
function showVotes()
{
$showresult = mysql_query("SELECT * from mms") or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_assoc($showresult)) {
$response[] = $row;
}
return json_encode($response);
}
Secondly, remove your 'connected successfully' text from the page, as well as any other text generated by anything else(aka, the other function which returns a result pointer). I may be wrong, but it would seem to me that the generation of this other text is causing the returned json to be interpreted as malformed.
Quick explanation on PDO:
try {
$dbh = new PDO("mysql:host=localhost;dbname=dbname", "user", "password");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (\PDOException $e) {
echo "Error! Could not connect to database: " . $e->getMessage() . "<br/>";
die();
}
Connecting to the database.. This is how I've learned to do it, though I've been warned(and downvoted) to not check for errors this way, though it was never explained why.
Database interaction:
$stmt = $dbh->prepare("UPDATE mms SET votes = votes+1 WHERE color = :color");
$stmt->bindParam(":color",$_POST['color']);
$stmt->execute();
Result use:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$response[] = $row;
}
And so on and so forth. PDO escapes the values for you, so you don't have to worry about injection attacks.