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>"
Related
It seems like Instagram has changed certain things, because I have tried several codes on my html website to show the amount of Instagram followers on a button, but nothing works.
I tried this:
<?php
$account='XXX';
$instagramsource=file_get_contents('https://instagram.com/' . $account);
preg_match_all('/"userInteractionCount":"(.*?)"/', $instagramsource, $count);
$followcount=$count[1][0];
echo "$account instagram account has $followcount followers";
?>
Also this
<?php
$otherPage = 'XXX';
$response = file_get_contents("https://www.instagram.com/$otherPage/?__a=1");
if ($response !== false) {
$data = json_decode($response, true);
if ($data !== null) {
$follows = $data['graphql']['user']['edge_follow']['count'];
$followedBy = $data['graphql']['user']['edge_followed_by']['count'];
echo $follows . ' and ' . $followedBy;
}
}
?>
And this ...
<?php
$url = "https://www.instagram.com/XXX";
$json = file_get_contents($url);
$obj = json_decode($json, true);
$content = $obj['query']['results']['script']['content'];
$content = str_replace("window._sharedData =", "", $content);
$content = str_replace(";", "", $content);
$content = trim($content);
$json = json_decode($content);
$instagram_follower_count = $json->entry_data->ProfilePage{0}->user->followed_by->count;
?>
And finally this:
<?php
$username = 'XXX';
$response = #file_get_contents( "https://www.instagram.com/$username/?__a=1" );
if ( $response !== false ) {
$data = json_decode( $response, true );
if ( $data !== null ) {
$follows = $data['graphql']['user']['edge_follow']['count'];
$followedBy = $data['graphql']['user']['edge_followed_by']['count'];
echo 'XXX follows:' . $follows . ' and is followed by: ' . $followedBy;
}
}
?>
None works.
Can anyone indicate what would work in 2021, please?
Thanks.
It's because the url https://www.instagram.com/$username/?__a=1 is redirecting to login page & giving u a html response
You can check it by echo $response
These posts will help you link1,link2
Instagram blocked access via __a=1 parameter since 2018-04-12. __a=1 must be replaced by JS and Ajax bypass. I've looked for an alternative solution. You can use javascript code inside php. For example:
async function instagramFollowers () {
const followers = []
try {
const userInfoSource = await Axios.get('https://www.instagram.com/123/')
const jsonObject = userInfoSource.data.match(/<script type="text\/javascript">window\._sharedData = (.*)<\/script>/)[1].slice(0, -1)
const userInfo = JSON.parse(jsonObject)
const mediaArray = userInfo.entry_data.ProfilePage[0].graphql.user.edge_owner_to_timeline_media.edges.splice(0, 10)
for (let media of mediaArray) {
const node = media.node
followers.push(node.thumbnail_src)
}
} catch (e) {
console.error('Unable to retrieve Followers. Reason: ' + e.toString())
}
return followers
}
Other helpful links: how to write javascript code inside php
https://code.tutsplus.com/tutorials/how-to-use-ajax-in-php-and-jquery--cms-32494
I have an empty test.php file,in that file, I've inserted data below shown.
This code is form controller. This trace data coming from UI using ajax.
Here my $trace array data like this :
array(
[0] => $test1 = "1,2,3,4,5,6,7";
[1] => $test2 = "1,2,3,4,7";
[2] => $test3 = "1,4,6,7,9,0";
)
This is coming from UI
$trace = $this->input->post('trace');
$viewsDir = 'C:/xampp/htdocs/project/application/views/html_v3/';
$fp = fopen($this->viewsDir.'test.php', 'w');
fwrite($fp, "<?php \n\n");
$i = 0;
if($trace){
foreach ($trace as $value) {
fwrite($fp, $trace[$i]."\n");
$i++;
}
}
fwrite($fp, "\n?>");
fclose($fp);
After inserted my data into test.php file then the file look like this:
<?php
$test1 = "1,2,3,4,5";
$test2 = "5,2,0,6,5";
$test3 = "4,8,9,7,1";
?>
Here, if once again I want to insert data into test.php file, my $trace array data like this:
aray(
[0] => $test1 = "9,9,9,9,9";
[1] => $test2 = "1,1,1,1,1";
[2] => $test4 = "1,2,6,7,8";
)
Here my query is how can I replace this ($trace)array variables if matched with test.php. If not matched it should be added to the test.php file.
Here my expected output is:
<?
$test1 = "9,9,9,9,9";
$test2 = "1,1,1,1,1";
$test3 = "4,8,9,7,1";
$test4 = "1,2,6,7,8";
?>
I tried like this,but i don't know how to compare my array($trace) and content of test.php
$file = $this->viewsDir.'test.php';
$contents = file_get_contents($file);
echo $contents; //i will get content of test.php based on this i have to replace or add
Please help me,
Thanks.
I'm not even sure I should help you with that. There is possibly something very wrong with your design if you're passing php code via POST and save it to a source file.
Anyways...
I'd declare helper function that 'parses' entry string line as key $trace1 and value "1,2,3,4,5" and adds it to array $arr
function addToTrace(&$arr, $entry) {
$entry = trim($entry);
if(substr($entry, 0, 1) == "$") {
$elements = explode("=", $entry);
if(count($elements) !== 2) {
return false;
}
$elements = array_map('trim', $elements);
$arr[$elements[0]] = $elements[1];
return true;
}
return false;
}
After that it's only a matter of reading the file first, adding all entries to new array $currTrace
$currTrace = [];
$fp = fopen($this->viewsDir . 'test.php', 'r');
if($fp) {
while (!feof($fp)) {
$line = fgets($fp);
addToTrace($currTrace, $line);
}
fclose($fp);
}
than adding new trace from post (ovewriting matching keys):
if($trace){
foreach ($trace as $value) {
addToTrace($currTrace, $value);
}
}
and saving $currTrace to file:
$fp = fopen($this->viewsDir . 'test.php', 'w');
fwrite($fp, "<?php \n\n");
foreach($currTrace as $key => $value) {
fwrite($fp, $key . " = " . $value . "\n");
}
fclose($fp);
I'm having an error parsing a JSON response from PHP.
Javascript:
function getStock()
{
var color = $("#select_color option:selected").val();
var comp = "<?= $idComp ?>";
$.post( "ajax/getStock.php",
{
idColor: color,
idComp: comp
}).done(function( data )
{
alert(data);
var obj = jQuery.parseJSON(data);
$('#stockReal').val(obj.StockReal);
$('#stockMinimo').val(obj.StockMinimo);
$('#stockMaximo').val(obj.StockMaximo);
});
}
PHP:
<?php
require_once "../../helper/db.php";
require_once "../../helper/security.php";
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(!empty($_POST['idColor']) && !empty($_POST['idComp']))
{
$idComponente = test_input($_POST['idComp']);
$idColor = test_input($_POST['idColor']);
$conn = db_connect($STOCKMANAGER);
$sql = "SELECT * FROM TableStock
WHERE idComponente = '$idComponente'
AND idColor = '$idColor';";
$stock = db_request_one($conn, $sql);
if($stock !== 0)
{
$respuesta = array('StockReal'=>$stock->StockReal
,'StockMinimo'=>$stock->StockMinimo
,'StockMaximo'=>$stock->StockMaximo);
echo json_encode($respuesta);
}
else
{
$respuesta = array('StockReal'=>''
,'StockMinimo'=>''
,'StockMaximo'=>'');
echo json_encode($respuesta);
//echo $respuesta;
}
}
}
?>
The error:
Uncaught SyntaxError: Unexpected token ... jquery-1.10.2.js:550
When I get data from alert for example I get:
{"StockReal":"33","StockMinimo":"0","StockMaximo":"55"}
This is a good Json data. But if I try to validate with http://jsonlint.com/ i get the next error message:
Parse error on line 1:
^
Expecting '{', '['
Also when I try to stringify the Json Data I get a lot of u0000\ before and after the data.
like this:
"\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000{\"StockReal\":\"33\",\"StockMinimo\":\"0\",\"StockMaximo\":\"55\"}\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000"
Can anyone help me?
Have you done an output of what is returned from $respuesta array? print_r($respuesta) and see what's in your array.
Also make sure you have NO white space in your getStock.php file.
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',"; } ?>]
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>";