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.
Related
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;
I'm trying to figure out the least obtrusive and least computationally expensive way to store PHP objects coming from my MySQL database such that their data can be rendered by JavaScript on click by a user.
Currently, I'm storing the data as custom attributes on a button. But this generates a lot of code and I've heard is "slow". I'm wondering if I should JSON encode my PHP object, $items (see below), and how that JavaScript would then look. Note I'm using Codeigniter for the PHP so that's what up with the alternate foreach loop syntax.
Here's where I'm at so far with the HTML/PHP:
<img id="img"></img><a id="url"></a> <!--elements where data is rendered on click-->
<? foreach($items as $item):?>
<button data-id="<?=$item->id?>" data-url="<?=$item->url?>" data-img="<?=$item->img?>">click<?=$item->id?></button>
<?endforeach;?>
And here's my JS:
$(document.body).on('click', 'button', function(){
var $this=$(this), id=$this.data('id'), url=$this.data('url'), img=$this.data('img');
$('#img').attr('src', img);
$('#url').attr('href', url).html(url);
});
Most of my site's data is coming from PHP via MySQL and I've long been confused by the issue of when should I convert that data to a JavaScript array/JSON or not.
If you json_encode your $items array (assuming it only consists of data you will want in JS), you can assign this to a JS variable:
<script>var items = <?php echo json_encode($items); ?></script>
You can then remove the data-url and data-img attributes. Then, within your JS code:
var $this = $(this), id = $this.data('id'), url = items[id].url, img = items[id].img;
// the rest of your code
Edit: when you move the click handler in a separate file, you would get something like this:
function setup_click(items) {
var $img = $('#img'), $url = $('#url');
$('button').click(function(evt) {
var id = $(this).data('id'),
url = String(items[id].url),
img=String(items[id].img);
$url.attr('href', url).html(url);
$img.attr('src', img);
});
}
here's a JSfiddle showing off the javascript/JSON part: http://jsfiddle.net/fz5ZT/55/
To call this in one shot from your template:
<script src="[your ext script file path].js"></script>
<script>setup_click(<?php echo json_encode($items); ?>);</script>
Hope that helps :)
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
?>
I'm trying to build a form where certain text fields and text areas have autocomplete.
I've used the formidable plugin for wordpress to build my form. I'm using the jQuery autocomplete plugin for the autocomplete part.
The code looks like this:
<script>
$(document).ready(function(){
var data = "Core Selectors Attributes Traversing Manipulation CSS Events Effects Ajax Utilities".split(" ");
$("#example").autocomplete(data);
});
</script>
So basically I need to use php to pull data from the mysql database and feed it to that data var. I'm a php newbie, so I'm not sure how to do this. A coder who works on the formidable plugin suggested the following code for the var data part:
<?php
global $frm_entry_meta;
$entries = $frm_entry_meta->get_entry_metas_for_field($field_id, $order='');
?> //db_frm_entry_metas is the name of the mysql db that stores the values for every field from the form. I suspect get_entry_metas_for_field is a function added by the formidable plugin. $field_id is the id for a given field on the form.
var data = new Array();
<?php foreach($entries as $value){ ?>
data[] = <?php echo $value ?>;
<?php } ?>
I tried to run this code with an id number in the place of $field_id, but it didn't work. I'm stuck here.
I can understand most of the code, except for this part:
var data = new Array();
<?php foreach($entries as $value){ ?>
data[] = <?php echo $value ?>
I don't get what the data[] is doing there... should the php be feeding the data to the var data= line?
I have around 15 form text/textarea fields, each of which needs to pull data associated with its given field_id. Unless there's an easier way to do this, this means I'll have to write 15 scripts, each with a particular $field_id and jQuery object with field's css selector.
Any help getting this to work would be much appreciated!
The coder is wrong, this:
data[] = something;
will cause a syntax-error in JS, it's a PHP-shorthand for pushing members to an array and doesn't work in JS.
Try this:
data.push(unescape('<?php echo rawurlencode($value); ?>');
According to the autocomplete docs, you can pass a url as the data parameter. That being said, do something such as the following:
<?php
// --- PLACE AT VERY TOP OF THE SAME FILE ---
$search = isset($_GET['q']) && !empty($_GET['q']) ? $_GET['q'] : null;
if (!is_null($search))
{
$matches = Array();
// some search that populates $matches based on what the value of $search is
echo implode("\r\n",$matches);
exit;
}
?>
then, in your jQuery code replace the .autocomplete(data) with .autocomplete('<?php echo $_SERVER['PHP_SELF']; ?>');
your jquery will be something like this
$("#example").change(function(){
$.ajax(
{
type: "POST",
url: "php_page.php",
data: "data=" + $("#example").val(),
beforeSend: function() {
// any message or alert you want to show before triggering php_page.php
},
success: function(response) {
eval(response);
// print your results
}
});
});
in your php page after getting all info echo the results like this.
echo "var result=" . json_encode($results);
then eval(response) jquery function will give you javascript variable result with your results in it.
Hope this helps...
I'm using Rob Monies 'Jquery Week Calendar' to build a calendar application.
I have a MSSQL DB a with table named 'dates' and the following fields:
id
start
end
title
I would like to query this DB in PHP and then pass the results to Javascript, Javascript will then render the events in the browser.
The Javascript needs to receive the event details in JSON format as per the following example:
{"id":1,"start": 2010-10-09T13:00:00,"end":2010-10-09T14:00:00,"title":"Lunch with Mike"},
{"id":2,"start": 2010-10-10T13:00:00,"end": 2010-10-10T14:00:00, "title":"Dev Meeting"}
So far, to keep things simple I've just returned one row from the DB at a time, however - I will need the application to be able to render multiple events, as stored in the database.
I've tried using json_encode() to put the values into a var and pass them to a Javascript var called DB_events - if I return the DB_events in an alert box on the client side I see the following;
{"id":1, "start":2010-10-09T13:00:00, "end":2010-10-09T14:00:00,"title":"Lunch with Mike"}
which looks ok, but when I do this in my code:
events : [DB_events]
It doesn't work :(
If I take PHP out of the equation, and just do the following on the client side:
var DB_events = {"id":1, "start":2010-10-09T13:00:00, "end":2010-10-09T14:00:00,"title":"Lunch with Mike"};
and return DB_events in an alert box, I get:
[object] [Object]
But when I do this:
events : [DB_events]
it works!
Back to PHP …
If I put the SQL result into PHP vars as follows:
$id = id;
$start = start;
$end = end;
$title = title;
and pass those vars to the following JS vars:
JS_id
JS_start
JS_end
JS_title
and do this on the client side:
var DB_events = {"id":JS_id, "start":JS_start, "end":JS_end,"title":JS_title};
events : [DB_events]
that also works.
As you can probably tell - I'm new to this and probably missing something very basic.
Any help, advice or information would be very much appreciated :)
Many Thanks
Tim
when you get a string representation of your object it means that you've exported it as a string not as an object.
when you get [object] [Object] it means that it is now an object, which is right!
You can do this with JSONP if you get JSON from an URL:
// send the request via <script> tag
var src = "..."; // url of the JSON output
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", src);
head.appendChild(script);
Or parse it as a string with JSON parser:
https://github.com/douglascrockford/JSON-js/blob/master/json2.js
var DB_events = JSON.parse( ...JSON output as a string... );
Or by directly passing it from PHP with an inline <script> block in your page:
echo "<script>";
echo "var DB_events = " . json_encode( ... ) . ";";
echo "</script>";
Did you use jsocn decode
http://php.net/manual/en/function.json-decode.php
You can split the result and make it differenct variables like start ,end , events etc
http://php.net/manual/en/function.explode.php