Accessing smarty multidimensional array values using jquery - php

I have an array being passed from php which looks like:
$resultsArr[123]['A']='q';
$resultsArr[123]['B']='d';
$resultsArr[113]['C']='s';
$resultsArr[113]['A']='ss';
$resultsArr[113]['B']='sd';
$resultsArr[111]['C']='sds';
$resultsArr[111]['A']='vv';
$resultsArr[111]['B']='vv';
i need to access certain values frmo this array using jquery.
i am trying to access it like
keyVal = 123; //dynamically generated
var pri = '~$results['keyVal']['B']`'
but i am getting a blank value in variable 'pri'
How can this be solved?

Could you not convert it to a JSON Array and then use it directly in Javascript, rather than picking out individual elements of the array?
<script>
var myArray = <?php echo json_encode($resultsArr); ?>;
</script>
Then use jQuery each to read the array.
This would give you greater flexibility in the long term of what was available to javascript for reading and manipulation.
EDIT
You can read a specific element like so, this will alert "vv":
<script>
var myVar = myArray[111].A;
alert(myVar);
</script>

In php use :
$ResultsArr = json_encode($resultsArr);
$this->jsonResultsArr = $ResultsArr; //its seems u r using smarty.
In javascript
jsonResultsArr = "~$jsonResultsArr`";
requireValue = jsonResultsArr[111].A;

Related

Pass array into GET URL using jQuery

I am trying to pass an array into a GET URL BUT it is coming as add_cart?ids=1,2,3,4,5 as opposed to sending it properly.
This is my jquery code where it adds the array to the URL and directs the user to the next page:
$(document).on("click", 'button.btn_checkout', function(){
var cart = <?php echo json_encode($carts); ?>;
window.location.href = "addcart.php?cart=" + cart;
});
And then on the addcart.php page I am unable to get these values.
Ideally on this page, I want the values in the form 1,2,3,4,5
This is the code for that page:
<?php
session_start();
$cart = isset($_GET['cart']) ? $_GET['cart'] : "";
$cart = explode(",", $_GET['cart']);
for($i = 0; $i<$cart.size; $i++){
echo $cart[$i];
}
?>
Where am I going wrong?
You are using the jQuery GET request a little wrongly. You will use
window.location.href
when you are trying to change the location of your current webpage.
Try this instead:
$(document).on("click", 'button.btn_checkout', function(){
var result = <?php echo json_encode($carts); ?>;
$.get( "addcart.php", { cart: result } );
});
I'm assuming by ARRAY you mean to include the braces {}?
If so, your problem is actually the php part. json_encode is creating a proper json object. Which then is being added onto the url AS the object itself, and NOT a string. You actually want it to be a string.
this line: var cart = <?php echo json_encode($carts); ?>; is the main issue.
convert it to something like: var cart = "<?php echo json_encode($carts); ?>";
Use $.param() function to convert params to get query string.
You are directly initialising Json to param but not converting to query string.
Above function will convert Json to query string
Try to use the javascript function JSON.stringify() to convert to json.
Note: Don't sent long data over a URL. There is a limit for sending data via url and it will end up in a corrupted data if exceeded the limit. For large data, use POST method.

How to replace strings in a Javascript array

I am trying to pass the values of a Javascript array to a PHP URL through Ajax. Here is script array
<script>"Talent_Percentile.php?"+globalArray"</script>
Where globalArray is my Javascript array. When I alert this, I get
Talent_Percentile.php?eqt_param1=4.00,eqt_param2=4.00,eqt_param3=4.00
I know about string replace but I don't know how to use it on an array. I need an output like
Talent_Percentile.php?eqt_param1=4.00&eqt_param2=4.00&eqt_param3=4.00
Can someone help me?
I'd recommend encoding your array to JSON:
<script>
var url = "Talent_Percentile.php?" + JSON.stringify(globalArray);
</script>
On the server side, use json_decode to decode the data.
var mystring = globalArray.join("&");
var url = "Talent_Percentile.php?" + mystring;
Generally, to apply a function to all elements of an array you should use map:
globalArray = globalArray.map(function(v) {
return v.replace("old", "new");
});

Passing a php array into javascript using JSON

I have a multidimensional array, here:
$noticeDate = json_encode( $noticesDates );
and I want to pass the array into javascript:
var unavailableDates[] = $noticeDate;
Both variables are in the same php file so there is little point using $.getJSON, which basically looks for the variable in an external file. However, how do I pass the object into the javascript array in the same script.
Cheers
You cant directly assign php variables to js, but you can use something like that:
<script>
var unavailableDates = jQuery.parseJSON('<?php echo json_encode($noticeDates) ?>');
</script>
use this
var array = JSON.parse("<?php echo json_encode($noticesDates) ?>");
Try this one:
$.pareseJSON()
here is example:
var json = "<?php echo json_encode($noticesDates); ?>";
jsArray = jQuery.parseJSON(json);

Use php to populate javascript array

All,
I have the following bit of code:
function addPoints() {
newpoints[0] = new Array(41.45998, 87.59643, icon0, 'Place', 'Content to open');
for(var i = 0; i < newpoints.length; i++) {
var point = new GPoint(newpoints[i][1],newpoints[i][0]);
var popuphtml = newpoints[i][4] ;
var marker = createMarker(point,newpoints[i][2],popuphtml);
map.addOverlay(marker);
}
}
There is other code around this to display the marker on my map. However this value is hardcoded. I have a PHP/mySQL database that has lat/long coordinates along with some other values. Say I have like three entries that I want to create markers for. How would I pass the addPoints function the lat/long that I got from my database so I can use it in this function correctly?
I updated my code to look like the following for the addPoints:
function addPoints(num, lat, long) {
newpoints[num] = new Array(lat, long, icon0, 'Place', 'Stuff name');
alert("The newpoints length is: "+newpoints.length);
for(var i = 1; i < newpoints.length; i++) {
var point = new GPoint(newpoints[i][1],newpoints[i][0]);
var popuphtml = newpoints[i][4] ;
var marker = createMarker(point,newpoints[i][2],popuphtml);
map.addOverlay(marker);
}
}
I call this function by doing this:
<script>
addPoints('<?php echo json_encode($num_coordinates); ?>','<?php echo json_encode($lat_coordinates); ?>', '<?php echo json_encode($long_coordinates); ?>');
</script>
It doesn't work though. When I try not to pass it to javascript and just output the lat coordinates for example. I get the following output:
{"1":"40.59479899","2":"41.4599860"}
Which are the correct coordinates in my array. No markers get created though. Any ideas on what to do next or what I'm doing wrong?
An easy and clean way to pass an array from PHP to JavaScript is to simply echo the json_encode version of the array.
$array = array(1,2,3,4,5,6);
echo 'var values = '.json_encode($array).';';
PHP executes on the server before getting sent to the the client. Therefor, if you can do things like this:
newpoints[0] = new Array(<?php echo $lattitude;?>, <?php echo $longitude;?>, icon0, 'Place', 'Content to open');
Where $lattitude and $longitude are values that you pulled out of you database with PHP.
When this page is requested by the client, your php code executes, real values get plugged in where those php tags are making it look like the example you provided, and then it gets sent to the client.
If you want to change these values using JS on the client, or fetch new ones from the server, let me know and I'll add an example of that.
EDIT:
Okay, in light of your comments, it sounds like you've got a few options. Here's one:
When the user selects a category (restaurants, bars, etc) you pass that category as a url parameter and reload either the whole page, or just the map part of it (depends on your set up but might be worth investigating). Your link would look something like this:
http://www.your-domain-here.com/maps.php?category=bars
Maps.php is ready to catch the category using the $_GET array:
$category = $_GET['category']; //'bars'
Your php then grabs the appropriate location data from the database (I'll leave that part to you) and sticks it in a variable that your JS-controlled map will be able to use:
//JS in maps.php - you could add this var to the window object
// if you have separated js files...
var locationCoords = <?php echo json_encode($arrayOfCoordinatesFromDB);?>;
When you page loads on the client machine, it now has an array of coordinates to use for the map ready to go in the locationCoords variable.
Then, depending on which coordinates you need to display on the map, you pass them as arguments to your addPoints() using standard Javascript (nothing tricky here).
That's how I'd do it. Hope that helps!
It is as simple as echoing the php values.
new Array(<?php echo $php_lat;?>, <?php echo $php_long;?>, icon0 etc...
I made a dynamic banner with this javascript array initialization. It works fine when the javascript is embedded in php.
<?php
// This is our php array with URLs obtained from the server
$urlsPHP = ["img/img01.jpg","img/img02.jpg","img/img03.jpg"];
return = "
//...Some HTML...
<script type='text/javascript'>
// Now we use this inside the javascript
var urlsJavaScript = ".stripslashes(json_encode($urlsPHP)).";
//...Some javascript style to animate the banner...
</script>
";
// if we print this:
echo stripslashes(json_encode($urlsPHP));
// We obtain:
// ["img/banner/bak01.jpg","img/banner/bak02.jpg","img/banner/bak03.jpg"]
// This is a good syntax to initialize our javascript array
// if we print this:
echo json_encode($urlsPHP);
// We obtain:
// ["img\/banner\/bak01.jpg","img\/banner\/bak02.jpg","img\/banner\/bak03.jpg"]
// This is not a good syntax to initialize our javascript URLs array
?>

How do I use PHP variables as values for the <script> tag when rendering jQuery code in my CakePHP view?

I m new to CakePhp and JQuery.
I am getting an error in using the cakephp code inside my JQuery.
My code
<script type="text/javascript">
$(document).ready(function(){
var attributeid;var fieldname;
$("#"+<?=$r['Attribute']['id'];?>).change(function () {
fieldname=<?=$r['Attribute']['label'];?>;
alert(fieldname);//this show me that undefined
attributeid=<?=$r['Attribute']['id'];?>;
alert(attributeid);//But this works
});//attribute change
});//ready function
if I echoed ($r['Attribute']['label'];) this value is coming inside my <?php ?>.
But not inside my JQuery.
Note :
attributeid=<?=$r['Attribute']['id'];?>;
alert(attributeid);//But this works
Error:
Name is not defined
fieldname=name;
alert(fieldname);
You are not thinking about how this is translating over once the variables are echoed.
If you have a variable $x with the contents "test", doing this:
var x = <?=$myvar?>;
Will result in:
var x = test;
This is not valid (unless test is a variable) because you need quotations around it to make it a string:
var x = "<?=$myvar?>";
Which then results in the valid:
var x = "test";
The reason it works with the other variable is because you are echoing an ID, which is an integer:
var x = <?=$myid?>;
Would translate to:
var x = 5;
Which is perfectly valid.
All this being said, you should put all the stuff you want to send over to Javascript in an array and call json_encode on it to easily and safely print the values over. Without it, you have to worry above about escaping quotes in the string and such.

Categories