How to use php to feed data to jQuery autocomplete? - php

This is a continuation of an earlier post. Unfortunately, The solutions posted didn't work and my follow up questions weren't addressed. Just in case this is because my generous respondents didn't notice I had replied, I'm reposting my problem.
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.
After implementing the suggestions of one of my respondents, the code now looks like this:
<script>
$(document).ready(function(){
<?php global $frm_entry_meta;
$entries = $frm_entry_meta->get_entry_metas_for_field(37, $order=''); ?>
var data = new Array(); <?php foreach($entries as $value){ ?>
data.push(unescape('<?php echo rawurlencode($value); ?>');
<?php } ?>
$("#field_name-of-the-school").autocomplete(data); })
</script>
// 37 is the field id I want to pull from in the database,
// and #field_name-of-the-school is the css id
// for the text field in the form where a user can enter the name of a school.
// the data for that field is stored in the db under field id 37.
// other fields, like school id, have their own field ids.
My respondent suggested adding the data.push(unescape('<?php echo rawurlencode($value); ?>'); bit. Unfortunately, it's still not working.
BTW, the code is in the body of page.php, a template which wordpress uses to generate static pages (the form is on one of these).
I would seriously, seriously appreciate any and all help with this. If this approach is a dead end (on the earlier posts, there were two other answers that were over my head,) I would be more than willing to learn some new tricks (though it would really help to be pointed to a relevant learning resource.)
Thanks in advance.

I would jsut use json_encode and simplify it:
<script>
$(document).ready(function(){
<?php global $frm_entry_meta;
$entries = $frm_entry_meta->get_entry_metas_for_field(37, $order=''); ?>
var data = <?php echo json_encode($entries); ?>;
$("#field_name-of-the-school").autocomplete({source: data});
}); // note you were missing a semicolon at the end of this, which i added
</script>
Of course using the above may not be waht you want if $entries is an associative array instead of a numeric indexed one. If thats the case you can do json_encode(array_values($entries));

You have to use
$("#field_name-of-the-school").autocomplete({ source : data });
as shown in the Autocomplete documentation example. Also you might think
about using JSON.

Related

jQuery UI autocomplete gets has suggestions but doesn't display them

I have a jQuery autocomplete script in my page, and if I type in the field it works on, and as requested after 3 characters, the drop containing the expected number of suggestions pops down...sort of...as there is no text in the drop down.
If I mouse over the drop down as though I were selecting one of the suggestions, a narrow bar shows a highlight for each row where a suggestion would be, but selection of one of the empty highlights empties the field. This is not surprising. I don't really understand the handling of the return data. I have seen very simple and complex code in autocomplete examples in other posts in these forums, but using the ones I thought I understood has usually broken it to the point where I don't get the drop down at all. Thus I'm unashamedly looking for someone to provide me with the code that works so I can pick it apart and work out how it works.
My basic JS code is:
$("#tf_txt_CLIENTNAME").autocomplete({
source: "search.php",
minLength: 3,//search after three characters
dataType: 'json',
select: function(event,ui){
//do domething
}
It's the do something area I just can't get right. As I said, I've tried too many variations of code in that space to mention here, and all of them broke it completely.
search.php produces the following JSON output for input of 'bra':
[{"txt_CLIENTNAME":"Braedon"},{"txt_CLIENTNAME":"Bradly"}]
from the following PHP source (borrowed and modified from another web source):
<?php
require_once 'includes/dbiconnect.php';
require_once 'includes/sqlfunctions.php';
$term = trim(strip_tags(addslashes($_GET['term']))); //retrieve the search term that autocomplete sends
$qstring = "SELECT `txt_CLIENTNAME` FROM `tbl_client_details` WHERE `txt_CLIENTNAME` LIKE '%".$term."%'";
$result = mysqli_query($db_link,$qstring); //query the database for entries containing the term
while ($row = mysqli_fetch_assoc($result)) {//loop through the retrieved values
$row['txt_CLIENTNAME']=htmlentities(stripslashes($row['txt_CLIENTNAME']));
$row_set[] = $row; //build an array
}
echo json_encode($row_set); //format the array into json data
?>
I simply would like it to display what it finds and plonk the one I select into the value of the text field. I can then update the other fields I want to populate (company, phone # & e-mail) using $.POST triggered by the onchange event for that field (I'm sure there are better ways to do that, but I understand how to do that for the moment).
I'm using jQuery 1.7.2 and jQuery UI 1.8.22. I have the latest jquery toolbox loading as well without the tabs component, but removing it has made no difference.
Thanks in advance,
Braedon
As per Jquery UI guide,
your JSON needs to contain label or value (or both)
You need to change your json as below
while ($row = mysqli_fetch_assoc($result)) {//loop through the retrieved values
$row['txt_CLIENTNAME']=htmlentities(stripslashes($row['txt_CLIENTNAME']));
$row_set[] = array('label'=>'txt_CLIENTNAME','value'=>$row['txt_CLIENTNAME']); //build an array
}

Best way to pass data from PHP to JavaScript for my particular case

I've built an online community in Drupal with a homepage that is kind of like the Facebook wall. You see the 25 most recent posts, with the two most recent comments below those posts. There is also a textarea right below those comments so that you can quickly post a new comment on a particular post.
These Facebook-style posts have a lot of functionality built into them via JavaScript. Clicking a "view all comments" link directly below a post makes an AJAX call that grabs all the comments for that post and displays them right below it. You can also mark posts as helpful, as the solution to your question, edit comments inline, etc. All of these actions require AJAX requests, which means that the JavaScript making the request needs to know essential information such as the Node ID (the unique identifier of the post), the comment ID (unique identifier of the comment), etc.
My initial implementation had these pieces of essential data sprinkled all over the posts, making it more complicated to write the JS that needed to find it. So my second implementation simply output all this data into a JSON-compatible string in the main wrapping element of each post. While this made it much easier for the JS to find the data it needed, writing JSON as a string is a pain (escaping quotes, no line breaks).
So now I have a third idea, and I'm looking for feedback on it prior to implementation. The idea is to create a single global JS Array for all these posts that contains within it objects that hold the data for each post. Each element in that array would hold the necessary data needed for the AJAX calls. So it would look something like this:
Facebook-style post template
<div class="post" data-postindex="<?php echo $post->index; ?>">
<!-- lots of other HTML for the post -->
</div>
<script type="text/javascript">
globalPostArray.push({
nid: <?php echo $post->nid; ?>,
authorID: <?php $post->authorID; ?>,
//etc. etc. etc.
});
</script>
The result of the above code is that when a link gets clicked that requires an AJAX request, the JS would simply traverse the DOM upwards from that link until it finds the main .post element. It would then grab the value of data-postindex in order to know which element in globalPostArray holds the data it needs.
Thoughts? I feel like there must be some standard, accepted way of accomplishing something like this.
I've never heard of a standard way to "pass" information between PHP and Javascript, as they are a server-side and client-side language, respectively. I would personally use a hybrid of your second and third solutions.
Store the post id in a data-postindex attribute (data attributes are newish, and the "right" way to store small amounts of data). But I would still just use a JSON array for the rest, as storing lots of data in data-attributes (and escaping them!) is potentially problematic. PHP has a json_encode function that takes care of all the escaping and such for you - just build a PHP array (say, $postdata) like you normally would, and then throw this in your post template:
<script type="text/javascript">
globalPostArray.push(<?php echo json_encode($postdata) ?>);
</script>
Where $postdata is something like the following:
$postdata = array(
'nid' => 5,
'authorId' => 45
...etc...
);
It should be easy enough to generate such an array from your existing code.
I wrote a blog post a while back about my implementation of this kind of thing, but it sounds like all you need is a pointer at json_encode.
The most reliable way to pass any PHP variable to JavaScript is json_encode.
<script type="text/javascript">
var something = <?php echo json_encode($var); ?>;
</script>
You can't pass closures and resources, but otherwise anything's game for being passed.
I would store the data inside the element:
<div class="post" data-postindex="<?php echo $post->index; ?>"
data-nid="<?php echo $post->nid; ?>"
data-authorID="<?php echo $post->authorID; ?>">
...or storing a complete JSON-string in 1 data-attribute:
<div data-data="<?php echo htmlentities(json_encode($somedata));?>">
My answer is about the same as the other guys but more detailed. I usually do it like this and i think is the best approach: (of course you can grab the data using ajax, but depends on the context)
somefile.html
<html>
<head>..</head>
<body>
html code
<script>
window.my_data = <?php echo json_encode($my_php_var); ?>
</script>
</body>
</html>
somefile.js
$(function() {
window.myitem = new myClass(window.my_data);
});
var MyClass = function(init_data) {...}

Populating a form using a url - multiple input types

Hi I'm trying to create a form that is pre-populated partially by form on the page before. This information is then posted to this new page which is then populated into the form on that page ready to be submitted to a database.
I'm not a developer so I'm a little out of my depth here but this is what I've got so far..
<?php
$amount = $_GET['text-386'];
$covermultiple = $_GET['radio-30'];
$coverdobd = $_GET['d-o-b-d'];
$coverdobm = $_GET['d-o-b-m'];
$coverdoby = $_GET['d-o-b-y'];
?>
<script type="text/javascript">
document.getElementById('text-386').value = "<?=$amount ?>";
document.getElementByName('radio-30').checked = "checked";
document.getElementById('d-o-b-d').value = "<?=$coverdobd ?>";
document.getElementById('d-o-b-m').value = "<?=$coverdobm ?>";
document.getElementById('d-o-b-y').value = "<?=$coverdoby ?>";
</script>
I'm getting the values out of the URL ok and can echo these out on the page fine, I've even managed to get text-386 appearing in the right place.. so thats one down! The problem is the other elements are a radio button with two options (radio-30) and a 3 select boxes with the days, months and year of a persons d-o-b. These two bits are populating.
So in a nutshell..
How can I use javascript (if that is the right way) alongside php to populate the radio and select tags on this form using information in the url? In a preferably straight forward way as possible?
The url if it helps is..
http://localhost/datacapture/form-page/radio-30=Just+for+me&text-386=%C2%A340%2C000&d-o-b-d=11&d-o-b-m=05&d-o-b-y=1977
Thats obviously on the local build I'm using so that URL wouldn't work for you. I can see when googling lots of help posting information using radio/select etc but I want the opposite, how do you populate these from a url?
Any help would be a lifesaver
I would just use an if statement.
if( $covermultiple == "Just for me" ) {
// Echo the field here
echo "<input type='radio' name='radio-30' value='Just for me' checked />";
}
else {
// Check for the next case
}
Put this block right where you want the radio buttons to be.
I think something like that will work fine. I don't think you really need javascript in this case unless you really want to use it.
Im not 100% I have an answer, but I cant find comment anywhere so I will joust post here.
You cant access PHP variables from Javascript. PHP is running on the server, and Javascript is inside users browser.
Javascript cant get $_GET and $_POST variables like PHP.
Now what you can do is this, with JavaScript you can get document.location string that holds your current URL. And you can brake that URL into parts. To do that use this function:
<script>
var $_GET = {};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
function decode(s) {
return decodeURIComponent(s.split("+").join(" "));
}
$_GET[decode(arguments[1])] = decode(arguments[2]);
});
alert($_GET['someVar']); // This will alert content of someVar
Now you can use $_GET['vars'] to get your URL vars.
And then you dont use PHP to echo variable content, you joust prepare your URL so it holds variables you want to insert into your form.
So you do something like this:
<script type="text/javascript">
document.getElementById('text-386').value = $_GET['urlVar'];
document.getElementByName('radio-30').checked = "checked";
document.getElementById('d-o-b-d').value = $_GET['urlVar'];
document.getElementById('d-o-b-m').value = $_GET['urlVar'];
document.getElementById('d-o-b-y').value = $_GET['urlVar'];
</script>
So as you can see, JavaScript takes variables from URL, using function $_GET you wrote and it dosent needs PHP. And you can use PHP to generate URLs you need, so they contain variables you can get using $_GET javascript function.
Hope this answers your question.

How to get an array of all checkboxes passed to the next page via _POST using JQuery

How to get an array of all checkboxes selected on the page, and then passing it to the next page (in this case php, so it can be picked up by php _POST function). I have come up with this :
<script type="text/javascript">
var selected = new Array();
$(document).ready(function() {
$("input:checkbox:checked").each(function() {
selected.push($(this).val());
});
$('#od').submit(function() {
alert(this.selected); // *See note below
$.post('receiver.php', {'registration': selected});
return false;
});
});
</script>
But is does not seem to work :( It returns null, as if no checkboxes would have been added to the array, or maybe the post function is wrong. Can you point me in the right direction here?
I've found the following of issues:
You read the checked items on page load, thus ignoring all changes made by the user. Move that code to the submit() handler.
Your debugging code (alert(this.selected)) tries to display the value of the selected property for the form node. It isn't a reference to your JavaScript global variable selected. I suggest you use a proper debugging tool such as Firebug; alerts are highly unsuitable.
You sucessfully send the values of checked items. You just ignore the field name and rename everything to registration. That looks intended, otherwise report back:
{'registration': selected}
I suppose you can make jQuery serialize the values for you but fixing these little details in your code should do the trick anyway.
I think $("input:checkbox:checked") should be `$("input[type="checkbox"]:checked")
Or simply: $('input:checked', '#form-container');
$('#od').submit(function() {
var selected = $('input[type="checkbox"]:checked').toArray();
$.post('receiver.php', {'registration': selected});
return false;
});
The Data being posted might need to be split up.....

grabbing POST values with javascript

Forgive me for asking a seemingly obvious question, but all of my searching is turning up guides on how to create POST values with JS, not how to grab (and utilize) them.
What I want to do:
step1.php -- form POSTing to step2.php
step2.php -- also a form, JS grabs one particular POST value and does some work with it, then updates this new form accordingly
for reasons not worth getting into, the process needs to be a 2 step//2 page process.
The obvious solution is just to do something like:
<script type="text/javascript">
function damn_ugly () {
var shameful = <?php echo $_POST['desiredDatum']; ?>;
do more stuff...
}
</script>
but that seems a bit dirty to me.
Is there a better way? or is that really how I'm supposed to do it?
var postData = <?php echo json_encode($_POST); ?>;
You can obviously change that to include only certain fields from $_POST by passing a custom array to json_encode.
var desiredDatum = <?php echo json_encode($_POST['desiredDatum']); ?>;
There is no nicer way to do it - and using json_encode ensures no matter what's contained in the POST variable nothing will break (at least not during the assignment).
That is how you are supposed to do it, JavaScript cannot access the POST values in another way.
Offcourse you can make it a bit more beautiful: have your php-script put the POST variables in an array, and print the array in JSON format. Now your javascript has the array.
POST values are being sent to the server. Once submitted only the server can work with those values. Your example is pretty much the only option you have to "access" POST values that have been sent to the server in the previous request.
JS has no access to POST values, it can only retrieve GET values. However, since you're using a PHP script and you're able to pass the data to JS - why not give your JS functions data in JSON format? You can use PHP's json_encode function to encode all POST values to JSON that you can use then easily in your JS code.
Try this
On second step Page 2:
Set hidden text box on page:
<input type='hidden' name='text1' id = 'text1' value='<?php echo $_POST['desiredDatum']; ?>' />
Now if you use jQuery the wirite below given code
$(document).ready(function() {
var shameful = $('#text1').val();
});
if not using jQuery Then
var shameful = document.getElementById('text1').value;
I hope this is what you are looking for.

Categories