I've tried
var name = <?php echo json_encode($eventname); ?>;
and
var name = new Array("<?php echo implode('","', $eventName);?>");
to parse my name string array from PHP to Javascript. It displayed as
var name = ["lalalala","Lalala","test"];
and
var name = new Array("lalalala","Lalala","test");
in viewsource, but when I tried to use name[i] to get the string, it returned the character, not the string. The size of the array name is also not 3, but 20 (which is the total number of characters plus three ","). How can I fix this?
Pretty sure because 'name' points to window.name (Thanks Fabrício Matté). Look Here
It works fine if you change 'name' to 'names'.
Related
In PHP I'm trying to strip information and store them in $sysver variable from a string named $freply like this:
var id='E8ABFA19FDE2';
var sys_ver='17.37.2.49';
var app_ver='20.9.1.150';
using PHP sscanf with whe following parameters:
sscanf($freply, "var sys_ver='%[^']'", $sysver);
However a blank result in $sysver is all I get.
UPDATE
Working on the first row with:
sscanf($freply, "var id=' %[^']'", $ea);
Gives me a correct result loaded as expected in $ea, that shows E8ABFA19FDE2.
Someone is able to tell me where's the mistake?
Despite I'm using PHP I guess this question is related to Javascript too or any other C-like language.
What you're telling sscanf() is your string is formatted beginning with the literal characters var sys_ver... etc. then you're passing it a string that starts with var id... and it's NOPE'ing right out.
This works:
sscanf($freply, "var id='E8ABFA19FDE2';\nvar sys_ver='%[^']'", $sysver);
or this:
foreach (explode("\n", $freply) as $line) {
if (sscanf($line, "var sys_ver='%[^']'", $sysver)) break;
}
But really sscanf() is not quite the right tool for this job. Just use preg_match():
preg_match("/var sys_ver='([^']+)'/", $freply, $matches);
$sysver = $matches[1];
I am new to AS3, and I had tried a few times to pass an array from php to AS3. But i can't manage to do it.
But i managed to narrow down the problem to 1 set of code, so wondering what do i need to change it.
When the function is this
function Asandler(event:Event){
var responseVariables:URLVariables = new URLVariables(event.target.data);
nobed = responseVariables.nobed ;
zip = responseVariables.zip;
Location = responseVariables.Location;
price = responseVariables.price;
}
It returns an error Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
But when i change it to
function Asandler(event:Event){
s1.test.text=event.target.data
}
It displays array with no problem, inside the dynamic text field.
php echo part
$solutions = array();
while ($row = mysqli_fetch_assoc($sql))
{
echo "nobed=".$solutions[1]=$row['nobed'];
echo "&zip=".$solutions[2]=$row['zip'];
echo "&Location=".$solutions[3]=$row['Location'];
echo "&price=".$solutions[4]=$row['price'];
}
Test Data string
nobed=100&zip=100&Location=100&price=100
New try, testing it with dynamic text field, it display the whole string.
var receivedValue:String = event.target.data.replace(/^\s+|\s+$/mg, "");
var test:Array = receivedValue.split(",");
s1.test.text =test[0];
But not too sure how to split the string up.
I am trying to pass an array to the browser using php and jquery but I the when I try to use the 'data' returned from php's encode_json, it comes up undefined. I'm just learning php, jquery, and json and so far haven't found very good documentation on alot of this stuff, especially json, even in the books I have. Thanks in advance!
Here is a stripped down version of the jquery I have
$(document).ready(function(){
var jsonResult;//I will want to be able to use the data in other functions
$.getJSON("json.php", function(data){
jsonResult = data;
var str;
var nuts = [203,204,205,207];
str = '<p>' + data[nuts[0]].NutraDesc + '</p>';
$('#stuff').html(str);
}
);
});
This is the php:
include_once 'databasePHP.php';
$json_tst = $db->query( "SELECT def.Nutr_No, NutrDesc, Nutr_Val, Units
FROM nutr_def as def JOIN nut_data as data ON def.Nutr_No = data.Nutr_No
WHERE data.NDB_No = 1001 LIMIT 0, 2");
$food = array();
while($row = $json_tst->fetch(PDO::FETCH_ASSOC))
{
$Nutr_No = $row['Nutr_No'];
$food[$Nutr_No][] = array(
'NutrDesc' => $row['NutrDesc'],
'Nutr_Val' => $row['Nutr_Val'],
'Units' => $row['Units']
);
};
echo json_encode($food);
?>
which returns this json which I checked on jsonlint.com and it said it was valid:
{"203":[{"NutrDesc":"Protein","Nutr_Val":"0.85","Units":"g"}],"204":[{"NutrDesc":"Total lipid (fat)","Nutr_Val":"81.11","Units":"g"}]}
It probably doesn't work because the numbers should be strings. Try to add quotes around the numbers in nuts, like this:
var nuts = ["203","204","205","207"];
The following probably works as well:
str = '<p>' + data[String(nuts[0])].NutraDesc + '</p>';
Also, have you tried adding console.log(data); to the getJSON function to make sure it receives the JSON?
EDIT:
Here is a working JSFiddle from your code:
http://jsfiddle.net/rKLqM/
Things that were wrong:
you weren't parsing the result as JSON (JSON.parse)
NutraDesc was spelled wrong
You didn't convert the numbers to strings
You needed to add [0] to the jsonResult because there's an extra array within it (see the [])
In Javascript object property can be accessed with obj["propName"]
So, change
var nuts = [203,204,205,207];
to
var nuts = ["203","204","205","207"];
I've got a jquery script, which creates a h3 tag and print a variable called result.tbUrl to it. I'd like to explode the variable at "::" and use the 2nd piece.
This is my method.
var link = document.createElement('h3');
link.innerHTML = <?php $link = "result.tbUrl"; $linkpiece = explode("::", $link); echo $pieces[1]; ?>;
Could you tell me please where did i make a mistake?
The first problem is, you're echoing $pieces[1], but exploding your string into $linkpiece which is a different variable.
However, you have a more serious problem: You're setting $link to the string "result.tbUrl". The string doesn't contain the delimiter '::', so exploding it has no effect and $linkpiece will be set to array(0 => 'result.tbUrl'). The line echo $linkpiece[1] will fail regardless, as there is nothing at index 1.
If result.tbUrl is a JavaScript variable, you cannot mix it with server-side PHP this way. You'll have to explode the variable client-side, in JavaScript:
var parts = result.tbUrl.split('::');
link.innerHTML = parts[1];
how do i write a function in javascript that can get the current url eg:
http://www.blahblah.com/apps/category.php?pg=1&catId=3021
and depending on a user selection choice, appends another parameter to the url like:
http://localhost/buyamonline/apps/category.php?pg=1&catId=3021&limit=5
but heres the catch:
Everytime the user selects a diff choice, I dont want to keep appending stuff like
http://localhost/buyamonline/apps/category.php?pg=1&catId=3021&limit=5&limit=10 and so on.
I want to always replace add it if there is no limit parameter or replace the value if there is one.
I was trying to accomplish this using sprintf but failed.
i was doing like so:
var w = document.mylimit.limiter.selectedIndex;
var url_add = document.mylimit.limiter.options[w].value;
var loc = window.location.href;
window.location.href = sprintf(loc+"%s="+%s, "&limit", url_add);
Updated with regular expression solution implemented in JS.
You can use a regular expression using JavaScript replace() Method
You can use build the entire url each time rather than just appending a parameter
You can parse the url into it's parts before appending the parameter
Which would you prefer?
For #1: The following should do the trick. Note though, there are issues with using regular expressions for parsing urls. (Ref: stackoverflow.com/questions/1842681/…)
<script type="text/javascript">
var pattern = "&limit(\=[^&]*)?(?=&|$)|^foo(\=[^&]*)?(&|$)";
var modifiers = "";
var txt=new RegExp(pattern,modifiers);
var str="http://localhost/buyamonline/apps/category.php?pg=1&catId=3021&limit=5";
document.write(str+"<br/>");
var replacement = "&limit=10";
document.write(str.replace(txt, replacement));
</script>
Below you can find my sprintf implementation which you can use it in your JS code to achieve what you need. It works almost like the C++/Java/PHP sprintf function with some limitations: the format specifiers are written like %1 and does not support the typed format specifiers (like %d, %s, %.2f, etc).
String.prototype.sprintf = function() {
var matches,result = this, p = /%(\d)/g;
while (matches = p.exec(result)) {
result = result.replace(matches[0], arguments[parseInt(matches[1]) - 1]);
}
return result;
};
Syntax:
format.sprintf(arg1,arg2,...);
The format string is composed of zero or more format specifiers that follows this prototype:
a % followed by argument index, where the first argument has index 1.
The arg1, arg2, ... are the variable strings which will replace the format specifiers.
Example: 'The quick %1 fox jumps over the %2 dog'.sprintf('brown','lazy');
Usage example:
var str = 'The size of %1 (%2) exceeds the %3 (%4).';
console.log(str.sprintf('myfile.txt', '100MB', 'max. allowed size', '75MB'));
Output:
The size of myfile.txt (100MB) exceeds the max. allowed size (75MB).
Note: If you need a robust sprintf function then check the sprintf for JavaScript.