I'm trying to get a PHP array to use in some jquery script using the qTip plugin. This is my array:
$descqtip[ ] = array('name' => ''.$name.'', 'description' => ''.$description.'');
Here is my jquery code:
<script type="text/javascript">
$(document).ready(function() {
var description = <?php echo json_encode($descqtip)?>;
$('#homepage_catgames h2').each(function(i){
$(this).qtip({
content: description
})
});
});
</script>
I know the above doesn't work, but i'm stuck on trying to get the description variable in each part of the array to their own individual tooltip.
Can anyone help me?
Thanks
You have some problems with how you are referencing the array on the Javascript side. I went ahead and made an example of what you wanted to do.
What you need is this:
var rows = <?php echo json_encode($descqtip); ?>;
var index = 0;
$('#sections h2').each(function()
{
$(this).qtip(
{
content: rows[index].description
});
index++;
});
The details are covered in this article I put on my blog http://blake.breakwatersyndicate.com/2011/03/php-array-in-json/
I hope that helps.
Related
I am trying to post an existing array in jquery using $.post to a evaluate.php page. I tried to serialize it and send it. But its not working. I get a internal server error. Can somebody suggest a method for me to post my array? Very much in need of help.
<?php
function radioevaluation($qnum) {
echo "<script> $(document).ready(function(){
var x= ".$qnum.";
$('#q'+x+'verify').click(function(){
var answerarray = [];
answerarray['answer'] =$('input[name=q'+x+']:checked').val();
answerarray['qnum']= x;
var answer =jQuery.param(answerarray);
$.post('evaluate.php',answer,function(data){
var a= data;
alert(a.result);
}, 'json');
});
});</script>";
}
?>
EDIT:
Sorry I missed your second comment.
I think you want to define answerarray not as an array but like so:
var answerarray = {};
I've a pretty long sign up form and I have autocomplete on one field which has worked before. The site is on WordPress, I've loaded jQuery UI in main.js and it is shown on the source of the page. And it's included after jQuery. Here's the snippet that powers the autocomplete.
jQuery(document).ready(function($) {var kurssit = [<?php echo file_get_contents("http://xxx.xxx", "r");?>];
$("#kurssi").autocomplete({
source: kurssit
});
});
And php will load it like this:
jQuery(document).ready(function($) {var kurssit = [
"Taaperokurssi",
"Junnukurssi",
"Yhteiseloa myötäkarvaan",
"Lapsi ja koira",
"Pentutoko",
"Aktivoi tokolla",
"Rallytoko",
"Näyttelyyn tutustumiskurssi",
"Ratkaisuja pulmalliseen ohitukseen",
"Ratkaisuja pulmalliseen ohitukseen - jatkokurssi",
"Hihna-, kontakti- ja luoksetulokurssi",
"Naksutin",
"Lupa koskea",
"Sienikurssi",
"Mejä",
"Mejä jatkokurssi",
"Puuhakurssi",
"Koiranhoidon ABC",
"Hieronta",];
$("#kurssi").autocomplete({
source: kurssit
});
});
It should work, why it won't work?
In your code you have two element with the same id
id="kurssi"
I'm trying to implement jQuery Flare Video Plugin for my website.. There's a dropdown menu which the user must choose a year from, when the submit button is clicked, a video is meant to show on the screen. I have a database that grabs the path to the video from the database i.e $row['videoName'] .
My question is how can I pass PHP variables in jQuery function.. In the example given in the plugin a full path to the video was given insrc attribute of jQuery function. I'm trying to make the src dynamic by passing the PHP Variable into it.
I'm not getting any error, and the div containing the video appears on the screen, but the video does not show.
Thank you.
jQuery(function($){
fv = $("#video").flareVideo();
fv.load([
{
src: '$row['videoName']',
type: 'video/mp4'
}
]);
})
</script>
To access the PHP variable you must enclose the code in PHP brackets like so:
jQuery(function($){
fv = $("#video").flareVideo();
fv.load([
{
src: "<?php echo $row['videoName']; ?>",
type: 'video/mp4'
}
]);
})
</script>
This must also be on the same page as the PHP variable is created to allow access.
I would advice to keep PHP preprocessing out of javascript as much as possible. I have a convention of creating a hash of all variables from PHP in the view and then injecting them into my Javascript objects. In this case you could put something like this into the view:
<script>
var options = {
videoName: '<?php echo $row['videoName']?>'
}
</script>
or
<script>
var options = <?php echo json_encode($row);?>;
</script>
Later in any of your javascript files you could do this:
$(function(){
fv = $("#video").flareVideo();
fv.load([{
src: options.videoName,
type: 'video/mp4'
}]);
})
jQuery(function($){
fv = $("#video").flareVideo();
fv.load([
{
src: '<?= $row['videoName'] ?>',
type: 'video/mp4'
}
]);
})
</script>
Mix php and js code is ugly. So when you have all your js code into .js files you can do it in this way:
code into .js files
jQuery(document).ready(function($){
fv = $("#video").flareVideo();
fv.load([
{
src: videoName, // videoName is in the global scope
type: 'video/mp4'
}
]);
})
var videoName = ""; // init var to avoid undefined values
code into .php files
echo <<<EOM
<script type="text/javascript">
var videoName = '{$row['videoName']}';
</script>
EOM;
The URL to the Video should be somewhere within the HTML Scope. JS comes in handy to grab the URL, with something like
fv.load({
src: $('.videlink').attr('href'),
type: 'video/mp4'
})
I do not know the precise javascript of this flareVideo() thing, but the URL SHOULD really be somewhere inside your HTML. Do not just pass this to the JavaScript, this is really ugly design :\
Another way to pass PHP variables to jQuery is through the DOM. You said that you have a dropdown list of years that the user selects. When you build your page, get the whole array of videos like so:
$rows = array(
'1991' => '/url/to/your/1991-video',
'1992' => '/url/to/your/1992-video',
'1993' => '/url/to/your/1993-video',
'1994' => '/url/to/your/1994-video'
);
So you can just build your select list like so:
<select id="videoName">
<option value="<?php echo $rows['1991'] ?>">1991</option>
<option value="<?php echo $rows['1992'] ?>">1992</option>
<option value="<?php echo $rows['1993'] ?>">1993</option>
<option value="<?php echo $rows['1994'] ?>">1994</option>
</select>
I've used a simple array but you would use the results of your database query, and you could also use a foreach to build your drop down list.
Then your video script would just reference the $('#videoName').value().
By doing a .change() event handler on the select, you can start the video without having to reload any pages.
You can use the same approach to build tables of items based on a database query. Just name your objects or id them with unique values based on your database output.
(code is untested)
Thoughts about doing this with a cookie? I think something like this...
PHP
setcookie('your_cookie_name', json_encode($your_array), time()+3600, "\");
Javascript
You would then have the PHP array in JS to do whatever JS you wanted to preform on it.
var arrayVar = []
arrayVar = $.parseJSON($.cookie('your_cookie_name'));
I am currently using - http://code.drewwilson.com/entry/autosuggest-jquery-plugin for an autosuggest on my site. I have limited the number of choices to 3.
This is the autosuggest code:
<script type="text/javascript">
$(document).ready(function() {
$("input[id=category]").autoSuggest("http://localhost:8888/bl/pages_mx/category_1.php",
{selectedItemProp: "name", selectedValuesProp: "value", searchObjProps: "name",
minChars: 1, matchCase: false, selectionLimit: 3});
});
</script>
The categories the visitor can choose is taken from a table within the MYSQL database. I can now successfully see the suggestions when I begin to type in potential categories!
The 2 values that are queried from the 'category' table are - category_ID and name.
My question is, once the user has chosen their 1,2 or 3 choices, how can I get the category_ID in 3 different variables in php, or in an array?
The closest I have got to help on their discussion forum is by using this code:
var arr = $(".as-values").val().split(",");
But from there, I have no idea how to implement this?
I have tried using an explode function to split the CSV using this:
<?php if($_POST['category_submit']){ ?>
<script type="text/javascript">
var arr = $(".as-values").val().split(",");
var exploded = arr.split(',');
var category_1=exploded[0];
var category_2=exploded[1];
var category_3=exploded[2];
print (category_1);
</script>
<?php } ?>
But nothing seems to print when I press submit?
Any help would be hugely appreciated.
Many thanks!
But nothing seems
First, it's important to write JavaScript when writing JavaScript. "Print" is not a valid line of JavaScript.
Second, when you call .split(), what you get is an array that's immediately indexable.
var arr = $(".as-values").val().split(",");
var category_1=arr[0];
var category_2=arr[1];
var category_3=arr[2];
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...