JSON Encode Failure - javascript

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.

Related

How to get the value of title image and content in ajax php

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.

Function Send from JS to PHP

I've tried to pass the "hide" value for delete a record. But the JS function send the data but the mysql code don't work.
With the "insert to" it works, for this it's strange that the same code don't work.
This is my code.
<script type="text/javascript">
function invia()
{
var hides = document.getElementById('hide').value;
$.ajax({
type: 'POST',
url: "note_db_php/delete_db_note.php",
data: {"hide": hides},
success: function(data){
console.log("Dati inviati");
},
error: function(data) {
console.log("Dati non inviati");
}
});
};
</script>
and this is the delete page;
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
$hide = $_POST["hide"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to delete a record
$sql = "DELETE FROM note WHERE id='$hide'";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
The console.log it work, and print "Dati inviati". So really, I don't understand. I have not error's message. But still don't work.
I have no idea why your code is not working -- you haven't described in any detail what error messages you are getting. But what other problem you have is that you are leaving yourself open to SQL Injection attacks and so you should be using a prepared statement. If this also corrects your problem (doubtful), that's a bonus:
$stmt = $conn->prepare("DELETE FROM note WHERE id=?");
/* Bind our parameter: */
$stmt->bind_param('i', $hide); // assuming $hide is an integer value, else use 's' for string
$success = $stmt->execute(); // execute the statement
if (!$success) {
error code here
}
$stmt->close();
I think the issue is with the sql query - $sql = "DELETE FROM note WHERE id=$hide";
Can you put the $hide in single quotes and try?
$sql = "DELETE FROM note WHERE id='$hide'"; // this will work
here your problem in sql syntax, and one line
enter code here
after else open on your code that causing error
updated query here , its working
// sql to delete a record
$sql = "DELETE FROM note WHERE id='$hide'";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
The attribute dataType is missing and type should be method.
$.ajax({
url:"note_db_php/delete_db_note.php",
method:'POST',
dataType:'json',
data:{
"hide": hides
},
success:function(data) {
console.log("Dati inviati");
},
error: function (request, status, error) {
console.log("Dati non inviati");
}
});
Replace your query -
$sql = "DELETE FROM note WHERE id='$hide'";
With below one -
$sql = "DELETE FROM note WHERE id = ".$hide;
And on the ajax end please console your data. If it is giving error then please echo your query (echo $sql), and copy and run the query in PHPMyAdmin.

AJAX call returning json array undefined

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 );
}
});

Insert into MySQL through a Buttons OnClick

Using a few answers on here I have got row being added to MySQL upon a button press but the data is blank and so I can only assume the variables are not being passed.
I really don't know what I am doing wrong, any help would be greatly appreciated.
PHP
<? $sql = "SELECT itemname FROM items ORDER BY itemname ASC";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<button onclick='javascript:ajaxCall(" . $row['id'] . ")'><span class='btn-text'>" . $row['itemname'] . "</span></button>";
}
?>
jQuery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function ajaxCall(id){
$.ajax({
type: "POST",
url: "additem.php",
success: function(data){
// callback function
}
});
return false;
}
</script>
additem.php
// Connect database.
include("settings.php");
mysql_connect($db_host,$db_user,$db_pass);
mysql_select_db($db_name);
$id = $_POST['id'];
$itemsearch = mysql_query("SELECT itemname, itemcategory, price, qty FROM presales WHERE id='$id'");
$itemsearchrest = mysql_num_rows($itemsearch);
$itemname = $itemsearchrest['itemname'];
$itemcategory = $itemsearchrest['itemcategory'];
$price = $itemsearchrest['price'];
$qty = $itemsearchrest['qty'];
$sql = "INSERT INTO presales (itemname, itemcategory, price, qty) VALUES('$itemname', '$itemcategory', '$price', '0')";
if(mysql_query($sql)){
return "success!";
}
else {
return "failed!";
}
?>
mysql_num_rows returns the number of rows. It's not an array. Use fetch_assoc or similiar.
See sample in the PHP documentation!
Also your AJAX call is missing the data:
$.ajax({
type: "POST",
url: "additem.php",
data: {
id: id
}
});
Please switch to PDO or MySQLi. MySQLi will use the same function names but it is object orientated. PDO will name the functions slightly different but basically work the same way.

Add and retrieve to mysql

I am building a small php application where you can add people and then see them on a page. When I was simply adding it went fine, but then I started using a switch and now it doesn't work to either add or retrieve. I cannot see any problem in my syntax, can anyone see something wrong?
php
<?php
$con = mysql_connect("hostWasHere","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dbIsHere", $con);
try{
switch($_POST['action'])
{
case 'retrieve':
$show=mysql_query("Select * from test",$con);
while($row=mysql_fetch_array($show)){
echo "<li><b>$row[firstName]</b> : $row[lastName]</li>";
}
mysql_close($con);
break;
case 'new':
$sql="INSERT INTO test (firstName, lastName)
VALUES
('$_POST[fname]','$_POST[lname]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
break;
}
}
?>
The javascript using this is :
function saveToServer() {
alert("clicked");
$.post("api.php", {
'action': "new",
'fname': $('#fname').val(),
'lname': $('#lname').val()
},
function () {
alert("succes");
}
);
}
function getFromServer() {
console.log("in get!");
$.ajax({
type: "post",
url: "api.php",
data: "action=retrieve",
success: function (data) {
$("#comment").html(data);
console.log("success!");
}
});
}
You are using a try block without any catch or finally – this doesn't work. Most likely, your server is configured not to output any errors, so it dies silently.
A few other remarks:
As pointed out in the comments, please use PDO or MySQLi instead of the deprecated MySQL class.
Beware of SQL injection and always sanitize properly, no excuses. (My code below with PDO uses prepare and takes care of this.)
Use quotes when you're accessing an array with a string as key: $_POST['fName'] or $row["lName"], as opposed to $row[lName].
Output all errors while you're developing your page by adding error_reporting(E_ALL) at the top of your file. Note that server settings may still suppress the error output, but this generally takes care of everything.
Using a switch statement with a lot of code is never a good idea; you want to keep all code there rather lightweight or switch to a combination of if, else if and else.
Enough talk. Here's my edit for your page, using PDO instead of the deprecated MySQL family.
<?php
error_reporting(E_ALL);
// PDO has more options to read about
// for initialization, but this should do for now
$con = new PDO("host=host;dbname=db_here", "username", "password");
if (!$con) {
die('Could not connect: !');
}
// Do some validation on $_POST before using it.
$action = '';
if(isset($_POST['action'])) {
$action = $_POST['action'];
}
if($action == 'retrieve') {
$sql = $con->execute('SELECT * FROM test');
$rows = $sql->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row) {
echo '<li><b>'.$row['firstName'].'</b> : '.$row['lastName'].'</li>';
}
$con = null;
}
else if($action == 'new') {
$sql = $con->prepare('INSERT INTO test (firstName, lastName)
VALUES (?, ?)');
// TODO: more checks on fname and lname before accepting
if(isset($_POST['fname']) || isset($_POST['lname'])) {
$result = $sql->execute( array($_POST['fname'], $_POST['lname']) );
if(!$result) {
die('Error occured');
}
else {
echo 'Added 1 row';
}
}
$con = null;
}
else {
// TODO: Default page
}
PS: Please don't ever trust user input. The code is still inserting $_POST values rather blindly (just checking that they're at least set), further checks with is_scalar() and some length checks would probably be good.
I hope this can help – good luck with your project!

Categories