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 );
}
});
Related
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 want to call php file from javascript, and this php file will update id=1
like this way:
javascript:
if(lastTemp >= document.getElementById("TempSet").value){
var jsonData2 =$.ajax({
url: "setpp.php",
dataType: "json",
async: false
}).responseText;
var obj2 = JSON.parse(jsonData2);
console.log(obj2);
}
else {
}
php file:
<?php
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'use';
$DATABASE_PASS = 'pass';
$DATABASE_NAME = 'database';
// Try and connect using the info above.
$db = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS,
$DATABASE_NAME);
if (!$db){
die("Connection Failed: ". mysqli_connect_error());
}
$db_update = "UPDATE setpoint_control SET status='ON' WHERE id=1";
$result = mysqli_query($db, $db_update);
?>
<?php
$data = array();
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_array($result)){
array_push($data, $row['status']);
}
}
echo json_encode($data);
?>
the code is executed and the status in database table is changed but I got error in console : SyntaxError: JSON.parse: unexpected character at line 4 column 2 of the JSON data
How can I solve this issue which I think I need to rewrite json_encode but I don't know how?
$.ajax({
type: 'post',
dataType: 'json',
cache: false,
url: 'setpp.php',
success: function (response) {
$.each(response, function(i, item) {
alert(item);
});
},
error: function () {
alert("error");
},
});
example php answer setpp.php
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
array_push($data, $row['status']);
}
die(json_encode($data));
} else {
$answer = array(
'No Records'
);
die(json_encode($answer));
}
I think the problem is the value returned by setpp.php.
remember to die(), otherwise the php answer will not be correct
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!
I'm trying to get the data from the database in real time but facing an issue, the java script is not running, i have tried it multiple times and also searched in stackoverflow for answers for my particular type of code but failed.
A simple fetch.php
<?php
include_once('db.php');
$sql = "SELECT * FROM people";
$res = mysql_query($sql);
$result = array();
while( $row = mysql_fetch_array($res) )
array_push($result, array('name' => $row[0],
'age' => $row[1],
'company' => $row[2]));
echo json_encode(array("result" => $result));
?>
And the my_script.js
$(document).ready( function () {
done();
});
function done() {
setTimeout( function() {
updates();
done();
}, 200);
}
funtion updates() {
$.getJSON("fetch.php", function(data) {
$("ul").empty();
$.each(data.result, function() {
$("ul").append("<li>Name: "+this['name']+"</li><li>Age: "+this['age']+"</li><li>Company: "+this['company']+"</li><br />");
});
});
}
The data received from the database is not displaying at all, only when it is refreshed and the data from the database is not getting into proper format of table even after using it in the script, and i have established proper database connectivity but i have just not mentioned it here as it is quite simple and since i'm receiving the data but not in the proper format and not in real time.
Thank You.
I prefer to use pure ajax. Also please don't use timers, search for an ajax synchronizer. Anyway, if this doesn't work you need to post the database structure.
fetch.php
<?php
include_once('db.php');
$sql = "SELECT * FROM people";
$res = mysql_query($sql);
$result = array();
$rs = mysql_query("SELECT * FROM people");
while($obj = mysql_fetch_object($rs)) {
$result[] = $obj;
}
echo $_GET['callback'] . '{"result":'.json_encode($result).'}';
?>
JS
$.ajax({
url: 'fetch.php',
type: 'GET',
dataType: 'json',
success: function(data) {
for (var x = 0; x < data.result.length; x++) {
$("ul").append("<li>Name: "+ data.result.name[x] +"</li><li>Age: "+ data.result.age[x] +"</li><li>Company: "+ data.result.company[x] +"</li><br />");
}
},
error: function () { alert('error'); },
});
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.