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...
Related
When my page opens I call a PHP file and output a form in the form of an echo.
A simplified example below:
echo "<table id='results'>";
echo "<form method = 'post'><input id='".$row['batchname']."'><button class='btn1'>Query this record</button></form>";
</table>
There will be many versions of the above form as table rows are pulled from the database.
I am usin AJAX to handle the output:
$(document).ready(function(){
$(".btn1").click(function(e){
e.preventDefault();
var bname = ("#<?php echo $row['batchname'];?>").val();
$post(
"somephp.php",
{name : bname},
function(response, status){
$("#results").replaceWith(response);
}
);
});
});
When I input an non PHP ID into the jQuery the AJAX work but I always post the first returned row for every form produced as the ids output in the PHP are the same. Can I echo PHP variable into jQuery like this? Is there a better way of getting dynamic ID's into jQuery.
Rather than hacking about like this, do it properly.
$(".btn1").click(function(e) {
e.preventDefault();
var form = $(this).parents("form");
var value = form.find("input")[0].value; // or something else here
});
This is what I'm trying to achieve, but my Googling hasn't helped:
I have a button that adds a new row to a table dynamically. I also add a select component to a cell with the same action all in javascript. I'd like for that select component to populate with values from a sql select statement. Of course I don't want to define the connection to the DB in the JavaScript. So I was wondering if there was a way I could call a PHP function to retrieve the values then store it in variable within JavaScript.
PS I understand that PHP is server side as opposed to JS. But surely this is possible.
here's a simple implementation of such a thing using jQuery's ajax and php.
html
<select data-source-url="/category/list"></select>
javascript using jQuery
$("select[data-source-url]").each(function(){
var url = $(this).attr("data-source-url");
var el = $(this);
$.get(url, function(data){
for (i=0;i<data.length;i++){
el.append("<option>" + data[i] + "</option>");
}
},"json");
});
category/list endpoint (a php script)
$list = array();
$list[0] = "category 1";
$list[1] = "category 2";
$list[2] = "category 3";
$list[3] = "category 4";
$list[4] = "category 5";
echo json_encode($list);
a little explanation: what happens is a request being made via the JavaScript client to a php script, which returns an array of values in JSON (which is basically a javascript data-structure), those values are added to the select box dynamically.
Please note that on initial load of the page, the select box will be empty.
yes ofcourse you can. for storing s php variable in a js ariable you can do like this.
before storing it into js variable store the required value in your php variable
var value = '<?php echo $value;?>';
Javascript cannot connect directly to a database.
You want AJAX. A basic flow for this functionality looks like this.
Create a PHP script that connects to the database and gets the options for your select element (let's call it options.php). This script should fetch the options from the database and output them as a JSON array.
In your javascript, you would create an ajax request to options.php. With the JSON data returned from that script, you would loop over each element and create and append a corresponding option element to the dom inside of your select element.
Also consider using jQuery. It greatly simplifies ajax and provides a cross-browser solution.
Option 1
Pass a php array with all possible values to the client side using something like this on the client side:
var opt_values = [<?php echo $php_values; ?>]; //javascript array
or
var opt_values = <?php echo json_encode($php_values); ?>; //json object
Option 2
Another way is making an ajax request. Write a php function that return a JSON object and then you can manipulate the result using jQuery ajax method:
PHP function:
$json = array();
$result = mysqli_query ($connection, $query);
while($row = mysqli_fetch_array ($result))
{
$bus = array(
'id' => $row['id'],
'text' => $row['name']
);
array_push($json, $bus);
}
return = json_encode($json)
Jquery
$('#button-id').click(function(){
//adds a new row to a table dynamically
$.ajax({
type: "get",
dataType: "json",
url: "/get_values.php",
success: function (response) {
var $el = $("#myselect"); //get the select
$el.empty(); // remove old options
//Append the new values
$.each(response, function(key, value) {
$el.append($("<option></option>")
.attr("value", value.id).text(value.text));
});
}
});
});
Just thought i'd put it out there since w3schools is my friend and i kinda follow what they're saying in this post.
W3Schools PHP & AJAX communication
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 :)
I HAVE modified my code, i used firebug console.log to detect weather the the php gets the array passed or not. and firebug displays this - rescheck[]=2&rescheck=1&rescheck=3
I think php gets the array if THATS what an array in php supposed to be like.
SO guys, if thats correct how to insert that array in database? or how to loop it? the foreach loop ive made didnt work.
JQUERY CODE:
$('#res-button').click(function (){
var room_id=$('[name=rescheck[]]:checked').serialize().replace(/%5B%5D/g,'[]');
alert(room_id);
$.ajax({
type: "POST",
url: "reservation-valid.php",
data: {name_r:name_r, email_r:email_r,contact_r:contact_r,prop_id:p_id,cvalue:room_id},
success: function(data) {
console.log(data);
}
});
});
<input type="checkbox" name="rescheck[]" value="<?php echo $roomid; ?>" />
PHP CODE:
$c_array=$_POST['cvalue'];
echo $c_array;
//foreach($c_array as $ch)
//{
//$sql=mysql_query("INSERT INTO reservation VALUES('','$prop_id','$ch','$name_r','$contact_r','$email_r','')");
//}
I think I managed my jquery code to be right, but I don't know how to fetch that with PHP.
room_id is an array, so if you want to get the value for each, you need to get all value together first.
var room_id_string = '';
for(i=0;i<room_id.length;i++){
room_id_string += room_id.eq(i).val() + ',';
}
your below code will only pass Array jquery object of [name=rescheck[]]:checked to room_id
Instead of this you will have to create a array and push values in it like this
var room_id = Array();
$('[name=rescheck[]]:checked').each(function(){
room_id.push($(this).val());
});
In jQuery it might be easier for you to just use the serialize function to get all the form data. jQuery passes the form to the server so you don't have to worry about getting all the values. If you use it in conjunction with the validate plugin you might find it a little easier!
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
This is what I do ibn my site for saving to a db a list of checkboxes with jquery and ajax call. It make an array and pass it to the ajax call and the php script handle the array.
If you get any error here you should debug the js array with firebug for be sure that is formed correctly.
js script:
var $checkBox = $('[name=rescheck[]]:checked');
$checkBox.each(function() {
if ($(this).is(":checked")){
valuesCheck[this.value] = 1;
}else{
valuesCheck[this.value] = 0;
}
and the PHP script:
$checkTab = $_POST['cvalue'];
foreach ($checkTab as $idChkTab => $checkedOrNot){
if ($checkedOrNot== "0"){
//do something if isn't checked
}
Okey, this is what I've got.
<?php
$options[1] = 'jQuery';
$options[2] = 'Ext JS';
$options[3] = 'Dojo';
$options[4] = 'Prototype';
$options[5] = 'YUI';
$options[6] = 'mootools';
That is my array, but I'd like to make it a bit more dynamic so that the array is built according to input id, so he won't have to change the php-code whenever he want's another poll. How would I import those input id's and push them into an array?
To the extent I can understand your question, you could use JSON to pass the data from the client to the server like this:
JAVASCRIPT (using jQuery):
var arr = [];
arr.push("option1");
arr.push("option2"); // and so on..
//Use AJAX to send the data across ..
$.ajax({
url: 'poll.php?jsondata=' + encodeURIComponent(JSON.stringify(arr)),
success: function(data) {
// response..
}
});
});
I think that PHP script will put those options into a database or something for using it later on.
Now, in PHP(poll.php):
<?php
$options = json_decode($_GET['jsondata']);
//...
?>