jquery $.parseXML cannot parse XML from php strings? - php

Somehow I keep getting error in javascript when I try to parse xml from php string, my code is like:
<?php
$xml = simplexml_load_file('file.xml');
$products = $xml->xpath("/products/product[#model='".$model . "']");
$filtered_xml = $products[0]->asXML();
?>
<script>
alert( $.parseXML( '<?php echo $filtered_xml;?>' ).find('name').text() );
</script>
echo $filtered_xml is returning a well formed xml as I am looking for, but something in the javascript - $.parseXML( '<?php echo $filtered_xml;?>' ) is causing errors. Thanks in advance for any help.

$.parseXML() itself does not return a jQuery object. Look at example in docs
http://api.jquery.com/jQuery.parseXML/
Proper use in your case would look more like:
var xml= $.parseXML( '<?php echo $filtered_xml;?>') ;
alert( $(xml).find('name').text() )

Related

Echo javascript function

I am tryaing to to make this echo work, but i cant get the grip of it
echo '<script>
function replaceWithImgLinks(txt) {
var linkRegex = /([-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?(?:jpg|jpeg|gif|png))/gi;
return txt.replace(linkRegex, "<img class="sml" src="$1" /><br />");
}
var newHTML = replaceWithImgLinks($(".ms").html());
$(".ms").html(newHTML);';
echo "</script>";
What am i doing wrong? i think i got something wrong with my " ' .
There was a couple of issues. I started by just running it in JavaScript until I got it to work, then moved it into PHP (for the sake of sanity).
<?php
print '
<script>
function replaceWithImgLinks(txt) {
var linkRegex = /([-a-zA-Z0-9#:%_\+.~#?&\/\/=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&\/\/=]*)?(?:jpg|jpeg|gif|png))/gi;
return txt.replace(linkRegex, "<img class=\"sml\" src=\"$1\" /><br />");
}
var newHTML = replaceWithImgLinks($(".ms").html());
$(".ms").html(newHTML);
</script>';
?>
Shouldn't the regex be something like:
(^|\b)((https?:)?\/\/[^\s]*?\.(jpe?g|png|gif))(\b|$)
Debuggex Demo
You shouldn't be echo'ing scripts, especially scripts in script tags. I would seriously look into just using your back end to fetch, then use an asynchronous technology that fetches data parsed JSON. That way you can call your scripts normally.

Valid JSON not working with jQuery.parseJSON()

I'm saving a JSON string to a file and trying to read it back. For some reason it won't read it back. jsonlint.com is telling me it is a valid JSON.
Here is the JSON string:
{"userdef":{"vlan10":{"dfault":{"down":{"rate":"876","ceil":"876"},"up":{"rate":"876","ceil":"876"}},"upsell":{"down":{"rate":"876","ceil":"876"},"up":{"rate":"876","ceil":"76"}}},"br0":{"dfault":{"down":{"rate":"798","ceil":"987"},"up":{"rate":"987","ceil":"987"}},"upsell":{"down":{"rate":"98","ceil":"987"},"up":{"rate":"987","ceil":"89"}}},"br1":{"dfault":{"down":{"rate":"3","ceil":"654"},"up":{"rate":"654","ceil":"63"}},"upsell":{"down":{"rate":"65","ceil":"4"},"up":{"rate":"646","ceil":"5"}}},"eth3":{"dfault":{"down":{"rate":"65","ceil":"7876"},"up":{"rate":"7657","ceil":"5"}},"upsell":{"down":{"rate":"7865","ceil":"7"},"up":{"rate":"7","ceil":"5"}}}}}
Here is javascript/php code:
<?
if (file_exists('/tmp/qosconfig.conf'))
{
?>
var config = jQuery.parseJSON('<?=file_get_contents("/tmp/qosconfig.conf");?>');
<?
}
?>
This is a rather odd way of doing this. If you have the JSON string available to you in PHP, you can output it into the javascript as an object literal which saves the parsing step.
<?
if (file_exists('/tmp/qosconfig.conf')) {
$json = file_get_contents('/tmp/qosconfig.conf');
?>
var config = <?php echo $json; ?>;
<?
}
?>

Javascript String with Single Quote printed from PHP code

I have following script printed from PHP . If some one has a single quote in description it shows javascript error missing ; as it thinks string terminated .
print "<script type=\"text/javascript\">\n
var Obj = new Array();\n
Obj.title = '{$_REQUEST['title']}';
Obj.description = '{$_REQUEST['description']}';
</script>";
Form does a post to this page and title and description comes from textbox.Also I am unable to put double quotes around {$_REQUEST['title']} as it shows syntax error . How can I handle this ?
a more clean (and secure) way to do it (imo):
<?php
//code here
$title = addslashes(strip_tags($_REQUEST['title']));
$description = addslashes(strip_tags($_REQUEST['description']));
?>
<script type="text/javascript">
var Obj = new Array();
Obj.title = '<?php echo $title?>';
Obj.description = '<?php echo $description?>';
</script>
You also need to be careful with things like line breaks. JavaScript strings can't span over multiple lines. json_encode is the way to go. (Adding this as new answer because of code example.)
<?php
$_REQUEST = array(
'title' => 'That\'s cool',
'description' => 'That\'s "hot"
& not cool</script>'
);
?>
<script type="text/javascript">
var Obj = new Array();
Obj.title = <?php echo json_encode($_REQUEST['title'], JSON_HEX_TAG); ?>;
Obj.description = <?php echo json_encode($_REQUEST['description'], JSON_HEX_TAG); ?>;
alert(Obj.title + "\n" + Obj.description);
</script>
Edit (2016-Nov-15): Adds JSON_HEX_TAG parameter to json_encode calls. I hope this solves all issues when writing data into JavaScript within <script> elements. There are some rather annoying corner cases.
Use the string concatenation operator:
http://php.net/manual/en/language.operators.string.php
print "<script type=\"text/javascript\">\n
var Obj = new Array();\n
Obj.title = '".$_REQUEST['title']."';
Obj.description = '".$_REQUEST['description']."';
</script>";

JavaScript & JSON

I am new to JS & JSON.I am struggle with converting JSON array to JavaScript array.How to do that? Here is my code:
var data = {
items: [
<? $i=1; foreach($query->result() as $row){ ?>
<? if($i!=1){ ?>,<? } ?>
{label: '<?=$row->district_name;?>', data: <?=$row->countid;?>}
<? $i++; } ?>
]
};
how to get the JSON array value to JavaScript Array.
i just tried but it doesn't work. please some suggestions.
here is my javascript array
for(i=0;i<5;i++){
chartData[i]=data.items[i].label+";"+data.items[i].data;
}
As the others already said, be careful when talking about JavaScript and JSON. You actually want to create a JavaScript object and not JSON.
Don't mix PHP and JavaScript like this. It is horrible to maintain. Create an array beforehand, encode it as JSON* and print it:
<?php
$results = $query->result(); // get results
function m($v) { // a helper function for `array_map`
return array('label' => $v->district_name,
'data' => $v->countid);
}
$data = array('items' => array_map('m', $results));
?>
var data = <?php echo json_encode($data); ?>
*: Here we use the fact that a JSON string is valid JavaScript too. You can just echo it directly in the JavaScript source code. When the JS code runs, it is not JSON, it is interpreted as JavaScript object.
You really oughtn't think too hard about this. PHP does a fine job of serializing arrays as JSON.
var data = {
items: <?php
$arr = array();
foreach($query->result() as $row) {
$arr[] = array('label' => $row->district_name,
'data' => $row->countid);
}
echo json_encode($arr);
?>
};
[insert same disclaimer as above about how you're really trying to create a JavaScript object]
This is JSON:
var foo = "{bar: 1}";
This is not JSON:
var foo = {bar: 1};
Your code snippet is not using JSON at all and my educated guess is that you don't even need it. If you are using PHP to generate some JavaScript code, you can simply tweak your PHP code to print text that will contain real JavaScript variables. There is no need to encode stuff as plain text!
Now it's clear we don't need JSON, let's use a dirty trick. PHP has json_encode() and we can abuse the fact that a JSON strings resemble JavaScript variables. All we have to do is call json_encode() on our PHP variable and forget to quote the result:
<?php
$foo = array(
'bar' => 1,
'dot' => FALSE,
);
echo 'var JSONString = "' . json_encode($foo) . '";' . PHP_EOL;
echo 'var realVariable = ' . json_encode($foo) . ';' . PHP_EOL;
Compare:
var JSONString = "{"bar":1,"dot":false}";
var realVariable = {"bar":1,"dot":false};
Edit: Yep, my JSONString is not a valid string... but we get the idea <:-)

very simple javascript failing

Working Example:
This is almost identical to code I use in another places on my page but fails here for some reason.
<?php
//$p = "test";
?>
<script>
alert('posts are firing? ');
parent.document.getElementById('posts').innerHTML = "test";
</script>
Failing example: (alert still works)
<?php
$p = "test of the var";
?>
<script>
alert('posts are firing? ');
parent.document.getElementById('posts').innerHTML = '<?php $p; ?>';
</script>
Try
'<?php echo $p; ?>';
or
'<?= $p ?>';
Debugging 101: Start checking all variable values.
alert(parent);
alert(parent.document);
alert(parent.document.getElementById('posts'));
as well as the value rendered by: '<?php $p; ?>'
Make sure your 'posts' object (I guess it is DIV or SPAN) loads before you fill it using javascript.
You're trying to generate javascript with php, here I use a simple echo:
<?php
$p = "test of the var";
echo"
<div id='posts'></div>
<script type='text/javascript'>
var posts = document.getElementById('posts');
posts.innerHTML = '$p';
</script>
";
?>
Note the $p and that the div is printed before the javascript!
You are not outputting the variable data is why it isn't working. You need to echo or print the variable $p.
In your example the $p is being evaluated, not printed.
To print it you should use print, echo, or the syntax <\?=$p;?>. without the \

Categories