Jquery and PHP , autocomplete - javascript

So i just found out about the jquery auto complete and i would like to add it to my web-page. I want to hook it up to my php code so i can search my sql database. However Whenever i try to run my auto complete,it doesnt seem to find the php array im passing ( im just trying to get an array to work for now) . Can someone help?
Jquery Code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#tags" ).autocomplete({
source: "test.php"
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
PHP code
<?php
$data[] = array(
'c++','Java','JavScript',"c#" );
echo json_encode($data);
?>

This is an updated version of your answer which should resolve the deprecated SQL driver and the injection issue. You need to replace the SECOND_COLUMNNAME with your actual column's name. Aside from that I think this should work.
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=DB','username','password');
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
if(empty($_REQUEST['term']))
exit();
//require_once('connect.php'); connection to db is in this file so connection is not needed
$query = 'SELECT name, SECOND_COLUMNNAME FROM locations
WHERE name
LIKE ?
ORDER BY id ASC
LIMIT 0,10';
$stmt = $dbh->prepare($query);
$stmt->execute(array(ucfirst($_REQUEST['term']) . '%'));
$data = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = array(
'label' => $row['name'],
'value' => $row['SECOND_COLUMNNAME']
);
}
echo json_encode($data);
flush();
Links:
http://php.net/manual/en/pdo.prepared-statements.php
http://php.net/manual/en/pdo.connections.php
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
How can I prevent SQL injection in PHP?
Also not sure if there was anything else inside connect.php, you might need to bring that back.

The array pattern used here should be as below.
<?php
$data = array(
array("value"=>'C++'),
array("value"=>'Java'),
array("value"=>'Javascript'),
array("value"=>'C#'),
);
echo json_encode($data);

If you're using PHP >= 5.4:
$data = [
[ 'value' => 'C++' ],
[ 'value' => 'Java' ],
[ 'value' => 'Javascript' ],
[ 'value' => 'C#' ]
];
echo json_encode( $data );
Here's a working example of my autocomplete code:
function get_data(type, target, min_length )
{
$(target).autocomplete({
source: function( request, response ) {
var submit = {
term: request.term,
type: type
};
$.ajax({
url: '/request/get',
data: { thisRequest: submit},
dataType: "json",
method: "post",
success: function( data ) {
response($.map( data.Data, function( item ) {
return {
label: item.label,
value: item.label
}
}));
}
});
},
minLength: min_length
})
}

<?php
$data = array(
'c++',
'Java',
'JavScript',"c#" );
echo json_encode($data);
?>

So i want with Pratik Soni advice and did a search. Here is the php code if anyone wants to use it
<?php
// Connect to server and select databse.
$dblink = mysql_connect('localhost','username','password') or die(mysql_error());
mysql_select_db('DB');
?>
<?php
if(!isset($_REQUEST['term']))
exit();
require('connect.php');
$term =
$query = mysql_query('
SELECT * FROM locations
WHERE name
LIKE "'.ucfirst($_REQUEST['term']).'%"
ORDER BY id ASC
LIMIT 0,10', $dblink
);
$data = array();
while($row = mysql_fetch_array($query, MYSQL_ASSOC)){
$data[] = array(
'label' => $row['name'],
'value' => $row['name'],
);
}
echo json_encode($data);
flush();

Related

How to execute two actions with one ajax call - WordPress

I have a section for "tours" in my page.
The tours have 2 filters (select inputs). "destino" and "duracion" (location and duration)
So far I made one of the filter work with ajax, and update the "#result" id with the new tours once you select a "destino".
But i also want to update the "duracion" select with the new options (based on the destino selected).
Problem is, i have no idea how to execute two actions and have the response on two different places.
Html part: (here I have both actions, its only executing the last one)
<form class="filtros righter" action="**********/wp-admin/admin-ajax.php" method="POST" id="filtro">
<input type="hidden" name="action" value="filtertoursajax">
<input type="hidden" name="action" value="filterduracionajax">
<input type="hidden" name="filtrodestino" value="salar-de-uyuni">
<div class="select-holder">
<label class="">Categoría</label>
<select name="categoriafilter" id="categoriafilter">
<option disabled="" selected="" value="0"> </option>
<option value="0">Todas las categorías</option>
<option value="11">Clásicos</option>
<option value="33">Elite</option>
</select>
</div>
<div class="select-holder">
<label>Duración del viaje</label>
<select name="duracionfilter" id="resultselect">
<option disabled="" selected="" value="0"> </option>
<option value="0">Todas las duraciones</option>
</select>
</div>
</form>
Js part:
<script>
jQuery(function myFunction(){
$('#filtro').change(function(){
var filter = $('#filtro');
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
type:filter.attr('method'), // POST
beforeSend:function(xhr, data){
filter.find('button').text('Processing...'); // changing the button label
},
success:function(data){
filter.find('button').text('Apply filter'); // changing the button label back
$('#response').html(data); // insert data
console.log(data);
},
error: function(req, err){ console.log(err);
}
});
return false;
});
});
PHP action 1:
add_action('wp_ajax_filtertoursajax', 'filtertoursajax');
add_action('wp_ajax_nopriv_filtertoursajax', 'filtertoursajax');
function filtertoursajax(){
$args = array(
'post_type' => 'tours',
'orderby' => 'menu_order',
'order' => 'ASC',
'post_per_page' => -1,
);
if( isset($_POST['filtrodestino']) && $_POST['filtrodestino'] ) {
// for taxonomies / categoria
if( isset( $_POST['filtrodestino'] ) ) {
$args['tax_query'][] =
array(
'taxonomy' => 'destino',
'field' => 'slug',
'terms' => $_POST['filtrodestino']
);
}
}
if( isset($_POST['categoriafilter']) && $_POST['categoriafilter'] ) {
// for taxonomies / categoria
$args['tax_query'][] =
array(
'taxonomy' => 'categoria',
'field' => 'id',
'terms' => $_POST['categoriafilter']
);
}
$query = new WP_Query( $args );
if( $query->have_posts() ) :
print_r($args);
while( $query->have_posts() ): $query->the_post();
$postid = $query->post->ID;
$taxonomy = 'destino';
$terms = get_the_terms( get_the_ID(), $taxonomy );
if ( $terms && ! is_wp_error( $terms ) ) :
$term_links = array();
foreach ( $terms as $term ) {
$term_links[] = '' . __( $term->name ) . '';
}
$all_terms = join( ', ', $term_links );
$destinos = '<span class="terms-' . esc_attr( $term->slug ) . '">' . __( $all_terms ) . '</span>';
endif;
?>
<div class="box">
<div class="box__image flexer">
<?php echo wp_get_attachment_image( get_field( "foto_portada", $postid ), array('276', '180'), "", array( "class" => "img-responsive" ) ); ?>
</div>
<div class="box__content pz-1">
<span class="placeholder mb-1"><?php echo $destinos; ?></span>
<h6 class="long-title mb-2"><?php echo $query->post->post_title; ?></h6>
<div class="icon-btn"><?php $path = get_template_directory_uri().'/images/plane-icon.svg'; echo file_get_contents($path); ?>Duración: <?php echo get_field( "duracion_texto", $postid ); ?></div>
</div>
Ver ficha<?php $path = get_template_directory_uri().'/images/arrow-btn.svg'; echo file_get_contents($path); ?>
</div>
<?php endwhile;
wp_reset_postdata();
else:
echo 'Sin resultados';
print_r($args);
endif;
die();
}
PHP action 2:
add_action('wp_ajax_filterduracionajax', 'filterduracionajax'); //
add_action('wp_ajax_nopriv_filterduracionajax', 'filterduracionajax');
function filterduracionajax(){
if( $args = array(
'posts_per_page' => -1,
'hide_empty' => 1,
'post_type' => 'tours',
'meta_key' => 'dias',
'orderby' => 'meta_value',
'order' => 'ASC',
) ) :
// create $args['tax_query'] array if one of the following fields is filled
if( isset($_POST['filtrodestino']) && $_POST['filtrodestino'] ) {
// for taxonomies / categoria
if( isset( $_POST['filtrodestino'] ) ) {
$args['tax_query'][] =
array(
'taxonomy' => 'destino',
'field' => 'slug',
'terms' => $_POST['filtrodestino']
);
}
}
// create $args['tax_query'] array if one of the following fields is filled
if( isset($_POST['categoriafilter']) && $_POST['categoriafilter'] ) {
// for taxonomies / categoria
$args['tax_query'][] =
array(
'taxonomy' => 'categoria',
'field' => 'id',
'terms' => $_POST['categoriafilter']
);
}
// query
$the_query = new WP_Query( $args );
if( $the_query->have_posts() ): ?>
<div class="select-holder">
<label>Duración del viaje</label>
<select name="duracionfilter" id="resultselect">
<option disabled="" selected="" value="0"> </option>
<option value="0" >Todas las duraciones</option>
<?php $unique_dias = array();
while( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php $dias = get_field('dias');
if( ! in_array( $dias, $unique_dias ) ) :
$unique_dias[] = $dias; ?>
<?php endif;
endwhile;
natsort($unique_dias);
foreach ( $unique_dias as $duraciones ) :
echo '<option value="'.$duraciones.'">'.$duraciones.'</option>';
endforeach;
?>
</select></div>
<?php endif;
endif;
die();
}
Im very new with Ajax, this code is made by pieces of tutorials i found. The code is mostly made following this tutorial: https://rudrastyh.com/wordpress/ajax-post-filters.html
I just need both php actions to execute on "form" change and update the "tours" on #response div and also update the select input with #resultselect id.
Thanks!
Thanks to #lewis4you I'm able to get the data on the 2 divs at the same time. But i fail to understand how to execute both actions at the same time, but with different actions from functions.php
This
add_action('wp_ajax_filterduracionajax', 'filterduracionajax'); //
add_action('wp_ajax_nopriv_filterduracionajax', 'filterduracionajax');
has to return data to #resultselect
and
add_action('wp_ajax_filtertoursajax', 'filtertoursajax');
add_action('wp_ajax_nopriv_filtertoursajax', 'filtertoursajax');
has to return data to #response div
My main problem is that i dont know how to select the action i want to execute in
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
type:filter.attr('method'), // POST
I didn't read the question fully but I think you want something like this:
$('#filtro').change(function() {
var filter = $('#filtro');
ajax1(filter);
ajax2(filter);
});
function ajax1(filter) {
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
// ... further code
}
function ajax2(filter) {
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
// ... further code
}
The scenario where you send the data to the same controller from one $.ajax call:
$('#filtro').change(function() {
var filter = $('#filtro');
ajax1(filter);
});
in controller you have to store the data into array with keys so you can access it later in ajax success() function
public function someFunction($dataFromAjax) {
// do something with $dataFromAjax
$dataForDivs = [
'div1' => 'some data',
'div2' => 'some data2'
];
return $dataForDivs;
}
then in your $ajax in success:function(data) you can access that data with
success:function(data) {
let div1Data = data.responseJSON.div1;
let div2Data = data.responseJSON.div2;
filter.find('button').text(div1Data); // changing the button label back
$('#response').html(div2Data); // insert data
console.log(div1Data, div2Data);
},
Have you thought of using JS's Fetch API instead of jQuery's Ajax? Fetch returns a promise then it can execute a chain of .then() blocks where you can put another fetch() to your PHP url.
See an example here:
using a fetch inside another fetch in javascript

Saving kartik select2 widget data with a model

Am using kartik select2 widget and i would like it to save data to the database by passing it to the controller.
I have tried this
1. the select2 widget
<?php $form = ActiveForm::begin(['id'=>$model->formName()]); ?>
<?php
echo $form->field($model, 'unitid')->widget(Select2::classname(), [
'data' => ArrayHelper::map($model2,'unitid','unitname'),
'language' => 'de',
'options' => ['multiple' => true, 'placeholder' => 'Select a Unit '],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
<?php ActiveForm::end(); ?>
The javascript code to save data on form submit which is on the view:
<?php
$script = <<< JS
$('form#{$model->formName()}').on('beforeSubmit', function(e)
{
var \$form = $(this);
console.log(\$form.serialize());
$.post(
\$form.attr("action"),
\$form.serialize()
)
.done(function(result) {
console.log("Succesifully saved" + result);
}).fail(function(err)
{
console.log("failed to save" + err);
});
return false;
});
JS;
$this->registerJs($script);
?>
This generates this output on the console(for the serialized form output
_csrf=TGMzaDRINnEHFgM5RjIPICc2bBoZAWZAOBIGAnAeVSF4GUQteThUFw%
3D%3D&Unitslocation%5Bunitid%5D=&Unitslocation%5Bunitid%5D%5B%5D=9
the output is always passed as a string that is after trying
echo json_encode($model->unitid);
On the controller it returns a string instead of an integer
that is
["5"]
How can i convert ($model->unitid) to integer for the post params
Just use
$model->unitid = (int) $model->unitid;
Thats all.

Query custom post type with jQuery.load()

Im working on a site see here and I created a custom post type named "projects".
When the page initially loads, Everything works fine, all the post data is loaded. But when I use $.load() to load the same code from an external file nothing gets displayed. It only appears to be a problem with custom post types, if I subsitute "projects" with "post" (the default type) the "Hello World" post will be re-queried,but not the "projects".
How can I query a custom post type twice? Here's my code:
<?php
$args = array(
'post_type' => 'projects',
'tax_query' => array(
'taxonomy' => 'nonfiction'
)
);
$query = new WP_Query( $args );
if ( $query->have_posts() ):
while ( $query->have_posts() ):
$query->the_post();
$meta_data = array(
'author' => get_post_meta($post->ID, 'Author', true),
'publisher' => get_post_meta($post->ID, 'Publisher', true),
'year' => get_post_meta($post->ID, 'Year', true),
'role' => get_post_meta($post->ID, 'Role', true),
'location' => get_post_meta($post->ID, 'Location', true)
);
?>
<li>
<?php
echo $meta_data['author'];
echo ". ";
the_title();
echo " (" . $meta_data['location'] . ": " . $meta_data['publisher'] . ", " . $meta_data['year'] . "). " . $meta_data['role'];
?>
</li>
<?php
endwhile;
endif;
?>
$(document).ready(function(){
$('.tab').click(function(){
$('.publications').load('http://greyediting201.staging.wpengine.com/wp-content/themes/pp_boot/_nonfiction.php', null, console.log('finished'));
});
});
Yes in .load() function do not use server url but relative path such as ./path of js folder/js file.js. hope it will work for you
Just check the link here for jquery docs
i think .load work in relative urls only otherwise any cross-domain issuses

Retrieve PHP Array with JSON and use the array in javascript to populate a playlist

I try to understand how it work. At the beginning, I was using inside my html code a php array with db and after that I was extracting my array inside my playlist.
Here the example:
<?php
$fileinfo=array();
$count=0;
//SQL Query
$query = "select track, artiste, album, emplacement, duration, poster from tempo where genre like '%%' ORDER BY no_track";
$con=mysqli_connect("localhost","user","password","db_table");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$resultat = mysqli_query($con,$query);
while($row = mysqli_fetch_array($resultat))
{
$row['emplacement'] = str_replace("../", "../../", $row['emplacement']);
$row['poster'] = str_replace("../", "../../", $row['poster']);
$row['duration'] = str_replace("00:", "", $row['duration']);
$info = '{artist:"'.$row['artiste'].'", title:"'.$row['track'].'", album:"'.$row['album'].'", mp3:"'.$row['emplacement'].'", cover:"'.$row['poster'].'", duration:"'.$row['duration'].'"}';
array_push($fileinfo, $info);
}
mysqli_close($con);
?>
...
$('#player').ttwMusicPlayer(
[
<?php
//for each file in directory
$arrlength=count($fileinfo);
for($x=0;$x<$arrlength;$x++)
{
if ($x < ($arrlength - 1))
{
echo $fileinfo[$x].",\n\t\t";
}else
{
echo $fileinfo[$x]."\n\t\t";
}
}
//the result look like this:
//{artist:"Boy Sets Fire", title:"After the Eulogy", album:"After The Eulogy",
mp3:"../../music/Punk/Hardcore_Punk/Boy_Sets_Fire_-_After_the_Eulogy-2000-
JAH/01_After_the_Eulogy-JAH.mp3",
cover:"../../music/Punk/Hardcore_Punk/Boy_Sets_Fire_-_After_the_Eulogy-2000-
JAH/Folder.jpg", duration:"03:31"},
?>
],
To use everything more dynamically, I try to use JSON with PHP inside my javascript
And my code look like this:
var sourceplayer =
{
datatype: "json",
datafields: [
{ name: 'artiste' },
{ name: 'title' },
{ name: 'album' },
{ name: 'mp3' },
{ name: 'cover' },
{ name: 'duration' }
],
url: 'player.php'
};
$('#player').ttwMusicPlayer(
[
],
So afert url: 'player.php', I don't know how to work with result. It's an array of data like this: "Rows":[{"no_track":"1","track":"Grandma Dynamite","artiste":"24-7 Spyz","album":"Harder Than You","genre":"Alternative","year":"1989","duration":"00:03:44"}
And I want to use it inside the bracket of $('#player').ttwMusicPlayer(
Please give me a cue or an simple example to help me with this. I'm not using pure jplayer but a similar one.
Thanks in advance
Regards,
Eric
PHP json_encode - http://us2.php.net/json_encode
<?php
$fileinfo=array();
$count=0;
//SQL Query
$query = "select track, artiste, album, emplacement, duration, poster from tempo where genre like '%%' ORDER BY no_track";
$con=mysqli_connect("localhost","user","password","db_table");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$resultat = mysqli_query($con,$query);
while($row = mysqli_fetch_array($resultat))
{
$fileinfo[] = array(
'mp3' => str_replace("../", "../../", $row['emplacement']),
'cover' => str_replace("../", "../../", $row['poster']),
'duration' => str_replace("00:", "", $row['duration']),
'artist' => $row['artiste'],
'title' => $row['track'],
'album' => $row['album']
);
}
mysqli_close($con);
?>
...
$('#player').ttwMusicPlayer(<?php echo json_encode($fileinfo); ?>);

Count and list all posts user has posted in all categories

I have just discovered this awesome wordpress function
<?php echo 'Number of posts published by user: ' . count_user_posts( ); ?>
Im busy making a graph which displays on a pie chart how many posts the user has done per category. (chars.js)
Is there any way to make a loop almost where i could get the values for each category the user has posted in.
Id like to future proof it so if more categories are added i dont have to go and write something like this
<?php echo 'Number of posts published by user: ' . count_user_posts( 5 ); ?>
<?php echo 'Number of posts published by user: ' . count_user_posts( 7 ); ?>
<?php echo 'Number of posts published by user: ' . count_user_posts( 8 ); ?>
Is there a way where i can just get a category breakdown of how many posts a user has posted in all categories
Thanks for any help
Try this code:
Just set which type of user's do you want at array:
<?php $args = array(
'blog_id' => $GLOBALS['blog_id'],
'role' => 'subscriber',//"Super Admin" or "Administrator" or "Editor" or "Author" or "Contributor"
'meta_key' => '',
'meta_value' => '',
'meta_compare' => '',
'meta_query' => array(),
'include' => array(),
'exclude' => array(),
'orderby' => 'login',
'order' => 'ASC',
'offset' => '',
'search' => '',
'number' => '',
'count_total' => false,
'fields' => 'all',
'who' => ''
);
php get_users( $args );
foreach ($blogusers as $user) { ?>
<li>
<?php $user_id = $user->ID ?>
<?php echo 'Number of posts published by user: ' . count_user_posts( $user_id ); ?>
</li>
<?php } ?>
Thanks.
I think you are misunderstanding the count_user_posts function. It's argument is for user id and not for category id.
Anyways, once you have the desired user id (if i understood well, you want to display the post count for every category where the user was the post author) you can do something like this:
$user_id = 124;
/* Get all categories */
$categories = get_terms("category");
/* Loop for each category to count the posts of the user */
foreach($categories as $category)
{
$cat_name = $category->name;
$cat_id = $category->term_id;
$post_count = count(get_posts("cat=$cat_id&post_author=$user_id"));
echo "The user $user_id has $post_count posts in the $cat_name category";
}
Here is the completed code, thanks for the help everyone
<script type="text/javascript">
var pieData = [
<?php
$user_id = get_query_var('author');
$rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
//get all posts from author
$args = array(
'post_type' => 'post',
'author'=> $queried_object->ID
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
//put categories in array
$cat = get_the_category( get_the_ID() );
$terms[] = $cat[0]->term_id;
endwhile;
wp_reset_query();
endif;
//count matching categories (array vals)
$countVal = array_count_values($terms);
foreach($countVal as $count){
$color = '#'.$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)];
echo " {
value: ".$count.",
color:'".$color."'
},";
}
?>
]
var myPie = new Chart(document.getElementById("piec").getContext("2d")).Pie(pieData);
</script>

Categories

Resources