PHP to Jquery through json ruins array - javascript

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',"; } ?>]

Related

Validate JSON with json schema is failing

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.

Javascript inside PHP MYSQL query

I know that using php inside js is a bad practice, but unfortunately for now my skill is not enough to come up with something else.
$(document).ready(function() {
$("#type").change(function() {
var val = $(this).val();
valSize = "<?php $sql = "SELECT model FROM cars WHERE brand = 'val'";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)){
echo '<option>'.$row['model'].'</option>';
}
?>";
$("#size").html(valSize);
});
});
Is there any way how I could add val variable inside php code?
Your best bet would be to use a JavaScript AJAX call to send a request to another php file on your server.
First, create a separate PHP file on your server, I'll label it query.php (ONLY for the purposes of this explanation, I'd recommend choosing something more meaningful to your application).
<?php
if ($_POST['brand']) {
// Be sure to set up your SQL $conn variable here
$conn = ...;
$sql = "SELECT model FROM cars WHERE brand = '" . $_POST['brand'] . "'";
$result = mysqli_query($conn, $sql);
$data = []; // Save the data into an arbitrary array.
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
echo json_encode($data); // This will encode the data into a variable that JavaScript can decode.
}
Then in your JavaScript, perform the AJAX request:
$(document).ready(function() {
$("#type").change(function() {
var val = $(this).val();
$.post('query.php', {'brand' : val}, function(data){
var jsonData = JSON.parse(data); // turn the data string into JSON
var newHtml = ""; // Initialize the var outside of the .each function
$.each(jsonData, function(item) {
newHtml += "<option>" + item['model'] + "</option>";
})
$("#size").html(newHtml);
});
});
});
You can't execute the php code once the page has loaded. You're going to have to make a ajax call to a php file, that queries the data you need and echos that back to the original file. I would also recommend encoding it using echo json_encode($queryResults); Then you can JSON.parse($data);the return data in the success function of the ajax call.

Sending html code through json from php to javascript

I am getting following error in JS:
SyntaxError: Unexpected token < in JSON at position 0
How can I properly send HTML code (it's a whole page) through the JSON.
I did not made this idea, but this is the plugin that I am trying to install, and I am getting this error. So if anybody can point me out what is wrong in here and how to fix it, it would be great. Thanks.
public function ajaxfilter()
{
$this->registry->set('bf_force_tmp_table_creation', true);
$data = $this->_prepareFilterInitialData();
$json = array();
$route = $this->_getRequestParam('curRoute');
if ($route && $this->_getRequestParam('withContent')) {
$this->request->get['route'] = $route;
$this->load->controller($route, $data);
$json['products'] = $this->response->getOutput();
}
$this->load->model('module/brainyfilter');
$model = new ModelModuleBrainyFilter($this->registry);
$model->setData($data);
if ((bool)$this->_getRequestParam('count', false)) {
$json['brainyfilter'] = $model->calculateTotals();
}
if ((bool)$this->_getRequestParam('price', false)) {
$minMax = $model->getMinMaxCategoryPrice();
$min = floor($this->currency->format($minMax['min'], $this->_currency, '', false));
$max = ceil($this->currency->format($minMax['max'], $this->_currency, '', false));
$json['min'] = $min;
$json['max'] = $max;
}
$this->log->debug($json);
$isMijoShop = class_exists('MijoShop') && defined('JPATH_MIJOSHOP_OC');
if ($isMijoShop) {
header('Content-Type: application/json');
die(json_encode($json));
} else {
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
}
Use json_encode to get a valid JSON string.
You can encode any scalar value, arrays and stdClass instances. For any other class, you may implement the JsonSerializable interface.
A simple HTML example:
<?php
$html = '<div class="container">What-Ever-Content </div>";
echo json_encode($html);
This will produce this output:
"<div class=\"container\">What-Ever-Content </div>"

JQuery form submission generates a new form

I have a JQuery script that submits user input to a PHP script in the same file, and then displays the result of what the PHP script does with the input. That part works fine. The issue that I’m having is that, upon submission, the JQuery script (at least, I think it's the script) also generates a new submission box below the original.
I’m not sure why. I thought at first that it was an issue with the input type, with the asynchronous part, or even with where I had the form in the overall code, but none of those seem to be playing any role. I'm still a beginner and I'm just not seeing the issue.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<form id = "my_form">
verb <input type = "text" id ="word1"/>
<input type = "submit"/></form>
<div id="name"></div>
<script>
$(document).ready(function(){
$("#my_form").on('submit', function(e)
{
e.preventDefault();
var verb = $ ("#word1").val();
var tag = "#Latin ";
var url = "http://en.wiktionary.org/wiki/"+verb+tag;
$.ajax({
url: "Parser.php",
data: {"verb": verb},
type: "POST",
async: true,
success: function(result){
$("#name").html(result);
$("#name").append(url);
}
});
});
});</script>
RESULT:
PHP
<?php
$bank = array();
function endsWith($haystack, $needle) {
return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== false);
}
function check_end_array($str, $ends)
{
foreach ($ends as $try) {
if (substr($str, -1*strlen($try))===$try) return $try;
}
return false;
}
function db_connect() {
static $connection;
if(!isset($connection)) {
$connection = mysqli_connect('127.0.0.1','username','password','Verb_Bank');
}
if($connection === false) {
return mysqli_connect_error();
}
return $connection;
}
function db_query($query) {
$connection = db_connect();
$result = mysqli_query($connection,$query);
return $result;
}
function db_quote($value) {
$connection = db_connect();
return "'" . mysqli_real_escape_string($connection,$value) . "'";
}
$y = false;
if (isset($_POST['verb'])){
$y=db_quote($_POST['verb']);
echo $y;
echo "\n";
$m = db_query("SELECT `conjugation` FROM normal_verbs WHERE (" . $y . ") LIKE CONCAT('%',root,'%')");
if($m !== false) {
$rows = array();
while ($row = mysqli_fetch_assoc($m)) {
$rows[] = $row;
}
}
foreach ($rows as $key => $value){
if (in_array("first",$value)==true){
echo "first conjugation verb\n";}
$y = $_POST["verb"];
$x = $y;
foreach ($bank as $key => $value)
(series of IF-statements)
}}?>
As Roamer-1888 says's the problem lies in server side, you are returning a html which has a input too. You need to change your code to return only the result string which you append to the div. Else if this is not possible doing at server side as it might require you to change lot of code, then you can strip off the input element from the result and then append it to the div. Like below.
success: function(result){
var div = document.createElement('div');
div.innerHTML = result;
$(div).find('input').remove();
$("#name").html(div.innerHTML);
$("#name").append(url);
}

calling a function with arguement as a string not working

This is part of my code to display an album on my page. If I call the function like this
<?php
for ($key_Number = 0; $key_Number < count($album); $key_Number++) {
echo 'Gallery1<br>';
}
?>
<script type="text/javascript">ajax_json_gallery('gallery1');</script>
It works fine. gallery1 is a file on my server with test photos inside. If I call it like this
<?php
for ($key_Number = 0; $key_Number < count($album); $key_Number++) {
echo ''.$album[$key_Number].'<br>';
}
?>
<script type="text/javascript">ajax_json_gallery($album[$key_Number]);</script>
It doesn't work. What am I doing wrong? Any ideas?
I need to pass different strings depending on the user so I need to give it a variable.
And yes, my array $album does contain the correct file folder names.
Here is the function that is called.
<script type="text/javascript">
function ajax_json_gallery(folder){
var thumbnailbox = document.getElementById("thumbnailbox");
var pictureframe = document.getElementById("pictureframe");
var hr = new XMLHttpRequest();
hr.open("POST", "json_gallery_data2.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var d = JSON.parse(hr.responseText);
pictureframe.innerHTML = "<img src='"+d.img1.src+"'>";
thumbnailbox.innerHTML = "";
for(var o in d){
if(d[o].src){
thumbnailbox.innerHTML += '<div onclick="putinframe(\''+d[o].src+'\')"><img src="'+d[o].src+'"></div>';
}
}
}
}
hr.send("folder="+folder);
thumbnailbox.innerHTML = "requesting...";
}
function putinframe(src){
var pictureframe = document.getElementById("pictureframe");
pictureframe.innerHTML = '<img src="'+src+'">';
}
And here is the page that gets the photos json_gallery_data2.php
<?php
header("Content-Type: application/json");
$folder = $_POST["folder"];
$jsonData = '{';
$dir = $folder."/";
$dirHandle = opendir($dir);
$i = 0;
while ($file = readdir($dirHandle)) {
if(!is_dir($file) && preg_match("/.jpg|.gif|.png/i", $file)){
$i++;
$src = "$dir$file";
$jsonData .= '"img'.$i.'":{ "num":"'.$i.'","src":"'.$src.'", "name":"'.$file.'" },';
}
}
closedir($dirHandle);
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData;
?>
This is mixing server-side and client-side code:
ajax_json_gallery($album[$key_Number]);
The variables $album and $key_number aren't defined in JavaScript, so it can't use them. (I'm sure when it's "not working" it's actually telling you on the JavaScript console that those variables aren't defined.)
To emit values from PHP, you need to surround them with <?php ?> tags. Additionally, since it's a string in JavaScript, it needs to be enclosed in quotes in the JavaScript. Something like this:
ajax_json_gallery('<?php echo $album[$key_Number]; ?>');
1st:
$key_Number varibale on your server in the line:
<script type="text/javascript">ajax_json_gallery($album[$key_Number]);</script>
Contains count($album) value, which not exists in the array.
2nd:
If you trying to output php value in this line:
<script type="text/javascript">ajax_json_gallery($album[$key_Number]);</script>
Then try to enclose output in <?php ?> tags:
<script type="text/javascript">ajax_json_gallery('<?php echo $album[$key_Number]; ?>');</script>
3rd:
Single quotes does not allow to parse variables in string.
echo ''.$album[$key_Number].'<br>';
This ^ line doing not what you expecting.
Try to use double quotes:
echo "{$album[$key_Number]}<br>";

Categories

Resources