Hi I need to do a school assigement with a API thats generating json.
I get with $API my json. With some testing by myself I can say that the json is correct. But in the assigement it says I need to validate it with a json schema. I have the schema but I cant get it to work so it will check and validate the incomming json.
If someone sees the problem pls tell me because I cant find it.
<?php
//Json gets validated
if(isset($API))
{
?>
<script src="//cdnjs.cloudflare.com/ajax/libs/validate.js/0.13.1/validate.min.js">
var validator = require('validator');
var jsv = require('json-validator');
jsv.validate("<?php echo $API; ?>", "json_schema.json", function(err, messages)) {
if(err)
{
throw err;
}
else
{
$.getJSON("<?php echo $API; ?>", function(data)
{
var items = [];
$.each(data, function(key, val, val2) {
items.push("<li id='" + key + "'>" + val["COL 3"] + "</li>");
items.push("<br>");
});
$("<ul/>", {
"class": "my-new-list",
html: items.join("")
}).appendTo(".datapanel");
});
}
}
</script>
<?php
}
?>
Replace both <?php echo $API; ?> by <?php echo str_replace('"', '\\"', $API); ?>.
Even better, you could have this process once and then echo the escaped string:
<?php
// Json gets validated
if (isset($API))
{
// escape your JSON string
$escapedAPI = str_replace('"', '\\"', $API);
?>
...
<!-- echo the escaped string -->
<?php echo $escapedAPI; ?>
...
<?php
}
?>
The issue you're facing is that currenty, when PHP echo the JSON in your Javascript, it produces something like this:
jsv.validate("[{"COL 3":"(APPLAUSE)"}, ... ]", "json_schema.json", function() { ... })
As you can see, the " from the Javascript are mixed with the one "echoed" which produce invalid Javascript. This is why you need to escape them before "echoing" your JSON.
Related
In my db I save the json in a custom field called usp-custom-12 like this:
[{"Mamma":["Papa"]}]
Then I try to decode that
<?php
$jsonTable = usp_get_meta(false, 'usp-custom-12');
?>
var data = <?php echo htmlspecialchars_decode($jsonTable); ?>;
But it is giving me
var data = "[{"Mamma":["Papa"]}]";
And a console log error:
Uncaught SyntaxError: Unexpected identifier
The full code:
<?php
$jsonTable = usp_get_meta(false, 'usp-custom-12');
?>
var data = "<?php echo htmlspecialchars_decode($jsonTable); ?>";
console.log(data);
data = JSON.parse (data);
data.forEach(obj => {
Object.keys(obj).forEach(key => {
$('#newTable thead tr').append($('<th>').text(key));
obj[key].forEach((e, i) => {
if(!$("#newTable tbody tr:eq("+i+")").length) $("<tr>").appendTo($("#newTable tbody"));
$("#newTable tbody tr:eq(" + i + ")").append($('<td>').text(e))
})
})
});
In this jsFiddle if you click save table you will see it generates a table identical to the top one, that's also logging in console the correct json: https://jsfiddle.net/fbh0o67o/74/
$jsonTable contains a JSON string with html entities encoded, since it's already JSON, you just have to decode the html etities and echo it as is. No JSON decoding is required, no quoting is required. Just HTML decode and echo it into your javascript.
var data = <?php echo htmlspecialchars_decode(usp_get_meta(false, 'usp-custom-12')); ?>;
data.forEach(obj => {
// Loop stuff here...
});
The issue is with the quotes inside the string "mama" you need to escape those quotes using addslashes method.
Try using the following:
var data = "<?php echo addslashes(htmlspecialchars_decode($jsonTable)); ?>";
JSON to PHP:
json_decode($string);
If you use the optional parameter $assoc as true - json_decode($string, true) will return associative array on success.
PHP to JSON:
json_encode($array);
PHP manuals:
json_encode()
json_decode()
I have an image link in PHP that passes a variable to a script in a different file (functions.js), which is:
"img src=\"images/del.jpg\" onclick='delete_user_program(".$row1['program_name'].")' onmouseover=\"this.style.cursor='pointer'\" /"
The script is:
function delete_user_program(program_name){
var confirmed = confirm("Are you sure;");
if (confirmed == true){
var str="./delete_user_program.php?p1="+program_name;
window.location=str;
}
}
I try to pass "p1".
Then the delete_user_program.php is:
<?php
session_start();
include("connect_db.php");
$con = $_SESSION['connection'];
$select_query ="SELECT * FROM user_program WHERE program_name='".$_GET['p1']."'";
$result=#mysqli_query($con,$select_query) or die('Error, query failed');
$num_result=mysqli_num_rows($result);
if($num_result>0) {
//some code
}
else {
echo '<html><script language="javascript">alert("Program not exist.");</script></html>';
When calling delete_user_program.php I get the error that p1 is undefined and the message "Program not exist.". Any tips? Thanks in advance.
You should use ajax.
$(document).ready(function(){
function delete_user_program(program_name){
$.get("./delete_user_program.php",
{
p1: program_name
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
}
});
<?php
// file A.php
echo 'A';
?>
<?php
// file B.php;
$a = file_get_contents('A.php');
// thats synchron
echo $a;
?>
So I have a database pass a whole bunch of data using PHP back to jQuery through JSON.. I'm trying to access individual columns from the returned data but no luck..
My PHP:
header('Content-Type: application/json');
require 'database.php';
mysql_query('SET CHARACTER SET utf8');
$myjsons = array();
$qry = 'SELECT * FROM quotes ORDER BY id';
$result = mysql_query($qry);
while($row = mysql_fetch_assoc($result)){
$myjsons[] = json_encode(array($row));
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';
Here's my JS:
function getAll(){
jQuery.ajax({
url:'example.com/js/getAll.php',
async: true,
dataType: 'jsonp',
success:function(data){
$('.quoteList').append(data[0]);
}
});
}
Currently that appends the following to the element:
[{"id":"1","text":"The most wasted of all days is one without laughter.","author":"E.E. Cummings","status":"1"}]
So for example.. if I wanted the jQuery to go through data[0] to data[92] (the last one) and append the author of each to .quoteList, how could I do that? I've tried data[0][1] and data[0][author]
You can use $.each() to loop through the data and append the author:
$.each(data, function(i) {
$('.quoteList').append(data[i]['author']);
});
The PHP might be defective because json_encode is called twice, and this is unusual. As written this would be flattening the rows into JSON strings, but mere strings nonetheless, which then get JSON encoded again into an array of strings. This is probably not what you intended, as it would be making it possible to print the received data but not access the components of rows which will be decoded to strings and not objects.
Compare https://stackoverflow.com/a/6809069/103081 -- here the PHP echoes back a callback with a single JSON object inside parenthesis ().
I suspect the fix looks like https://stackoverflow.com/a/15511447/103081
and can be adapted as follows:
header('Content-Type: application/json');
require 'database.php';
mysql_query('SET CHARACTER SET utf8');
$myjsons = array();
$qry = 'SELECT * FROM quotes ORDER BY id';
$result = mysql_query($qry);
while($row = mysql_fetch_assoc($result)){
$myjsons[] = $row;
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';
Once you have this, you should be getting back proper JSON for your array of objects and be able to use #Felix's code on the client side.
you need to use loop on your data, try this
success:function(data){
for (var i in data) {
$('.quoteList').append(data[i]);
}
}
This should work:
(upd. all code:)
function getAll(){
jQuery.ajax({
url:'example.com/js/getAll.php',
async: true,
dataType: 'jsonp',
contentType: "application/json",
success:function(data){
var str = "";
$(data).each(function(index, item){
str += item.author + " ";
});
$('.quoteList').append(str);
}
});
}
Your problem is here:
while($row = mysql_fetch_assoc($result)){
$myjsons[] = json_encode(array($row));
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';
you need something like this:
while($row = mysql_fetch_assoc($result)){
$myjsons[] = $row;
}
$myjsons['callback'] = $_GET['callback'];
echo json_encode($myjsons);
I have a php file where I am outputing json.
<?php
header('Content-Type: application/json');
?>
var data = {
"cars": [
<?php foreach ($runshowcars as $rowscar):;?>
{
"id":"<?php echo $rowscar['id'] ?>",
"name":"<?php echo $rowscar['name'] ?>"
}
],
"boats": [
<?php foreach ($runshowboats as $rowsboat):;?>
{
"id":"<?php echo $rowsboat['id'] ?>",
"name":"<?php echo $rowsboat['name'] ?>"
}
],
};
This works however the output looks like this.
var data = {
"cars": [
{
"id":"1",
"name":"Ford"
}
,{
"id":"2",
"name":"Honda"
}
]
};
I want it to look like this.
var data = {"cars": [{"id":"1","name":"Ford"},{"id":"2","name":"Honda"}]};
The only way I have found to do this is to remove the white spaces from my php file, this is obviously not an ideal solution as it makes it very hard to maintain.
How can strip out all the white spaces here?
I have seen plenty of questions like this one, How to minify php page html output? however I can't get something like this working here as my data isn't in a variable?
Why don't you collect your data into an array and encode it to json.
Like this:
$data=array('cars'=>$runshowcars, 'boats'=>$runshowboats);
print json_encode($data);
(Otherwise you return javascript, and not json. At least if you prepend the result with the var data = part.)
Just create a multi dimensional associative array and use json_encode
You can remove everything outside <?php ?> like this :
<?php
header('...') ;
echo 'var data = {' ;
echo '"cars": [' ;
foreach ($runshowcars as $rowscar)
{
echo '{' ;
echo '"id":"'.$rowscar['id']?'",' ;
echo '"name":"'.$rowscar['name'] ;
echo '}' ;
}
echo '],' ;
...
?>
Or you can try json_encode php function (wich could be a better way imo) :
<?php
$data = Array('cars'=>$runshowcars,'boats'=>$runshowboats) ;
echo 'var data = '.json_encode($data) ;
?>
I'm trying to perform some PHP code and then pass it's results to another PHP script through jquery.
One of these results is an array, and I'm passing it to a GET so it gets to the other script. (alot of work, but I can't have page reloads even tho I have to use PHP).
The problem occurs when I'm trying to put the PHP variable through JQuery.
What I have to do this for me is:
var _leafs = <?php echo json_encode($leafs); ?>;
When I run json_encode on $leafs and then print the result (all using PHP), it gives me a json array that has been successfully validated by JSONLint.
When I use the above code and alert() the result it's missing the brackets and quotes.
Even weirder is when I pass it through like so:
$.get('set_fields.php?pt=' + _path + '&lf' + _leafs, function(data) {
The result is this:
" string(4) "
"
Which shows up to be a <br> in my html reader.
Am I missing something when I'm converting it to json?
Additional code:
<?php
// Fetch the XML from the URL
if (!$xml = file_get_contents($_GET['url'])) {
// The XML file could not be reached
echo 'Error loading XML. Please check the URL.';
} else {
// Get the XML file
$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);
$paths = [];
$leafs = [];
foreach ($xpath->evaluate('//*|//#*') as $node) {
$isLeaf = !($xpath->evaluate('count(#*|*) > 0', $node));
$path = '';
foreach ($xpath->evaluate('ancestor::*', $node) as $parent) {
$path .= '/'.$parent->nodeName;
}
$path .= '/'.($node instanceOf DOMAttr ? '#' : '').$node->nodeName;
if ($isLeaf) {
$leafs[$path] = TRUE;
} else {
$paths[$path] = TRUE;
}
}
$paths = array_keys($paths);
$leafs = array_keys($leafs);
echo "Choose a path<br><br>
<form>
<select id='field_dropdown'>";
foreach($paths as $value) {
echo "<option value='".$value."'>".$value."</option>";
}
echo " </select>
<button id='send_path'>Send path</button>
</form>
";
}
?>
<script>
$(document).ready(function() {
$('#send_path').click(function() {
var _path = $("#field_dropdown").val();
// Get the leafs array and send it as a json string to set_fields.php
var _leafs = <?php echo json_encode($leafs); ?>;
$.get('set_fields.php?pt=' + _path + '&lf=' + _leafs, function(data) {
$('#fields').append(data);
}).error(function() {
$('#fields').html('Error calling XML script. Please make sure there is no error in the XML file.');
});
return false;
});
});
</script>
And here the code where I want the json array to end up (and then get turned back into a PHP array).
<?php
// Match all the fields to the values
$path = $_GET['pt'];
$leafs = json_decode($_GET['lf']);
$fieldLeafs = [];
$pathLength = strlen($path) + 1;
foreach ($leafs as $leaf) { if (0 === strpos($leaf, $path.'/')) { $fieldLeafs[] = substr($leaf, $pathLength); } }
var_dump($path."<br>");
var_dump($leafs."<br>");
?>
What if you get the array through jquery instead of echoing it?
<input id="hidden-value" value="<?php echo json_encode($leafs); ?>" />
and then
var _leafs = $('#hidden-value').val();
What about adding an = after the lf query parameter when you build the get URI?
$.get('set_fields.php?pt=' + _path + '&lf=' + _leafs, ...
Just write 'json' in the last parameter of get method:
$.get('set_fields.php?pt=' + _path + '&lf' + _leafs, function(data) {
$('#fields').append(data);
},'json')//<-- this
.error(function() {
$('#fields').html('Error calling XML script. Please make sure there is no error in the XML file.');
});
Did you try this?
var _leafs = [<?php foreach($leafs as $leaf){ echo "'$leaf',"; } ?>]