Get json file result dynamically by url parameter - javascript

if have a json file like this example
market.json
{ topads:
[ { id: 114
, advert_type: 11
, cat_main_id: 5932
, cat_market: 1
, subcat1_id: 12
, endcat: 'Sneakers'
, description: 'Nike Air Jordan 1 '
} ] }
with php i will get the json file and show all entries with eg subcat1_id 12,15 and 23 (and max. 4 entries)
<?php
$url_json = $baseurl . 'json/market.json';
$response = file_get_contents( $url_json );
$obj = json_decode( $response, true );
//subcat1_id
$ad_types = array( 12,15,23);
$Count = 0;
shuffle($obj[ 'topads' ]);
foreach ( $obj[ 'topads' ] as $result ) {
if ( in_array( $result[ 'subcat1_id' ], $ad_types ) ) {
?>
<div class="col-xl-3 col-lg-3 col-md-4">
//some html and php content to show the output eg. echo $result[ 'description' ]
</div>
<?php
$Count++;
if ($Count == 4){
break; //stop foreach loop after 4th loop
}
}
}
?>
ok this works perfectly in php but I want a url parameter (e.g. & subcat1 = 12), instead of the hard coded $ad_types.
So every time the URL parameter changes, the json file entries should also be displayed dynamically.
But how?
js/jquery
<script>
const subcat1= urlParams.get('subcat1')
</script>
to get the url parameter subcat1
and then? Result via Ajax to show the results dynamically?
function getresults() {
$.ajax({
url: "myphpfile.php",
method: "POST",
data: subcat1,
success: function (data) {
// ...
}
});
}

Update getresults function with below:
function getresults() {
$.ajax({
url: "myphpfile.php",
method: "POST",
data: {subcat1: subcat1},
success: function (data) {
}
});
}
and get in php code like this-
$_POST["subcat1"];

Ajax data needs to contain key/value pairs, you are only sending a value
Try :
data: {subcat1 : subcat1 }
Then access it in php with:
$_POST['subcat1']

I have solved it.
Thanks for the hints on the solution!
The JS file to get the url parameter dynamically.
<script>
// get parameter from url
var queryString = window.location.search;
var urlParams = new URLSearchParams(queryString);
var subcat = urlParams.get('subcat1');
//console.log(subcat);
getresult(subcat);
// ajax call
function getresult(subcat) {
$.ajax({
url: "myphpfile.php",
method: "post",
data: {
"subcat": subcat
},
success: function (data) {
$('#ad_content').html(data);
},
error: function () {
$('#ad_content').html('error');
}
});
}
</script>
and the php file to show the
myphpfile.php
<section class="mt-1 mb-1 d-none d-lg-block">
<div class="col-xl-12 col-lg-12 col-md-12 pl-0 pr-0">
<div class="row">
<?php
$url_json = '/json/market.json';
$response = file_get_contents( $url_json );
$obj = json_decode( $response, true );
if ( isset( $_POST[ 'subcat' ] ) && !empty( $_POST[ 'subcat' ] ) ) {
// this is the value from the url parameter
$adcat = array( $_POST[ 'subcat' ] );
$Count = 0;
shuffle( $obj[ 'topads' ] );
foreach ( $obj[ 'topads' ] as $result ) {
if ( in_array( $result[ 'subcat1_id' ], $adcat ) ) {
?>
<div class="col-xl-3 col-lg-3 col-md-4">
<div class="item">
<div class="card mb-0">
<?php echo $result[ 'description' ]; ?>
</div>
</div>
</div>
<?php
$Count++;
if ( $Count == 4 ) {
break; //stop foreach loop after 4th loop
}
}
}
}
?>
</div>
</div>
</section>
and of course the place to show the result
<div id="ad_content"></div>

Related

PHP not running with ajax POST

I have a form in a modal:
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Add user
</button>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="" method="post" id="saveperson">
<label for="newcat">Project Name</label>
<input type="text" name="newcat" value="">
<label for="description">Description</label>
<input type="text" name="description" value="">
<input type="submit" name="user" value="Submit">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
On submit I run the js:
$(document).ready(function() {
$('#saveperson').submit(function(event) { //Trigger on form submit
var postForm = { //Fetch form data
'name' : $('input[name=newcat]').val(),
'desc' : $('input[name=description]').val() //Store name fields value
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'process.php',
data : postForm, //Forms name
dataType : 'json',
success : function(data) {
$('.modal-body').html("Done!");
}
else {
$('.modal-body').html("Error!");
}
}
});
event.preventDefault();
});
});
And then this should run in process.php
<?php
header ( "Content-Type: application/json");
$cat_ID = get_cat_ID( sanitize_title_for_query($_POST['newcat']) );
// Check if category exists
if($cat_ID == 0) {
$cat_name = sanitize_text_field($_POST['newcat']);
$cat_desc = sanitize_text_field($_POST['description']);
$cat_slug = sanitize_title_with_dashes($cat_name);
$my_cat = array(
'cat_name' => $cat_name,
'category_description' => $cat_desc,
'category_nicename' => $cat_slug,
'category_parent' => 0
);
if( wp_insert_category( $my_cat ) ) {
// Category added successfully
die ( json_encode ( array ( "success" => 1)));
} else {
// Error while creating new category
die ( json_encode ( array ( "success" => 0)));
}
} else {
// That category already exists
die ( json_encode ( array ( "success" => 0)));
}
?>
But after the submit, nothing happens and the data isn't saved in the db, meaning isn't working. If I use this php tho in a standard php without ajax, it works and saves the data in the db
<?php
header ( "Content-Type: application/json");
if( isset( $_POST['user'] ) ) {
if( !empty( $_REQUEST['newcat'] ) ) {
$cat_ID = get_cat_ID( sanitize_title_for_query($_POST['newcat']) );
// Check if category exists
if($cat_ID == 0) {
$cat_name = sanitize_text_field($_POST['newcat']);
$cat_desc = sanitize_text_field($_POST['description']);
$cat_slug = sanitize_title_with_dashes($cat_name);
$my_cat = array(
'cat_name' => $cat_name,
'category_description' => $cat_desc,
'category_nicename' => $cat_slug,
'category_parent' => 0
);
wp_insert_category( $my_cat );
}
}
}
?>
There is an error in the browser console:
$(document).ready(function() {
$('#saveperson').submit(function(event) { //Trigger on form submit
var postForm = { //Fetch form data
'name' : $('input[name=newcat]').val(),
'desc' : $('input[name=description]').val() //Store name fields value
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'process.php',
data : postForm, //Forms name
dataType : 'json',
success : function(data) {
$('.modal-body').html("Done!");
}
else {
$('.modal-body').html("Error!");
}
}
});
event.preventDefault();
});
});
Notice the
else {
$('.modal-body').html("Error!");
}
Error:
Uncaught SyntaxError: Unexpected token else
Remove the else block, it should work
It should be:
$(document).ready(function() {
$('#saveperson').submit(function(event) { //Trigger on form submit
var postForm = { //Fetch form data
'name' : $('input[name=newcat]').val(),
'desc' : $('input[name=description]').val() //Store name fields value
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'process.php',
data : postForm, //Forms name
dataType : 'json',
success : function(data) {
$('.modal-body').html("Done!");
}
});
event.preventDefault();
});
});
Here is the fiddle
Did u try this?
$( "#saveperson" ).submit(function( event ) {
let form = $( this );
let formData = new FormData(form[0]);
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'process.php',
data : formData,
success : function(data) {
$('.modal-body').html("Done!");
}
});
event.preventDefault();
});
The issue was I was running wordpress standard functions from an external php file and it doesn't work. In order to achieve what i was doing, I had to use
function.php and wordpress ajax
add_action( 'wp_footer', 'ajax_Person' );
function ajax_Person() { ?>
<script type="text/javascript">
jQuery("#createCat").on("click", function(e){
e.preventDefault();
person();
});
function person(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_person', catName: jQuery('#newCat').val(), catDesc: jQuery('#descRiption').val() },
success: function(data) {
}
});
}
</script>
<?php }
add_action('wp_ajax_data_person' , 'data_person');
add_action('wp_ajax_nopriv_data_person','data_person');
function data_person(){
$catname = $_POST['catName'];
$catdesc = $_POST["catDesc"];
$cat_ID = get_cat_ID( sanitize_title_for_query($catname) );
// Check if category exists
if($cat_ID == 0) {
$cat_name = $catname;
$cat_desc = $catdesc;
$cat_slug = sanitize_title_with_dashes($cat_name);
$my_cat = array(
'cat_name' => $cat_name,
'category_description' => $cat_desc,
'category_nicename' => $cat_slug,
'category_parent' => 0
);
if( wp_insert_category( $my_cat ) ) {
echo 'Category added successfully';
} else {
echo 'Error while creating new category';
}
} else {
echo 'That category already exists';
}
}

"You did not select a file to upload. " get this error while uploading image using ajax

I am working with CodeIgniter and jQuery ajax. I want to upload image using ajax. But it shows an error like You did not select a file to upload.
Here,I have write jQuery :
jQuery(document).on('submit', '#signup_form', function()
{
//debugger;
var data = jQuery(this).serialize();
jQuery.ajax({
type : 'POST',
url : '<?php echo base_url()."front/ajax_register"; ?>',
data : data,
success : function(data)
{
jQuery(".result").html(data);
}
});
return false;
});
<form id="signup_form" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-md-3">Upload Photo</div>
<div class="col-md-4">
<input type="file" name="pic" accept="image/*">
</div>
</div>
<div class="row">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
And My function looks like this :
function ajax_register()
{
if($this->input->post())
{
$this->form_validation->set_rules('pass', 'Password', 'required|matches[cpass]');
$this->form_validation->set_rules('cpass', 'Password Confirmation', 'required');
if($this->form_validation->run() == true)
{
$img = "";
$config['upload_path'] = './uploads/user/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('pic'))
{
$data['error'] = array('error' => $this->upload->display_errors());
print_r($data['error']);exit;
$data['flash_message'] = "Record is not inserted";
}
else
{
$upload = $this->upload->data();
//print_r($upload);exit;
$data = array(
'ip_address' =>$this->input->ip_address(),
'first_name' =>$this->input->post('firstname'),
'last_name' =>$this->input->post('lastname'),
'phone' =>$this->input->post('phone'),
'email' =>$this->input->post('email'),
'group_id' =>$this->input->post('role'),
'password' =>$this->input->post('password'),
'image' =>$upload['file_name'],
'date_of_registration' =>date('Y-m-d')
);
print_r($data);exit;
$user_id = $this->admin_model->insert_user($data);
$user_group = array(
'user_id' => $user_id,
'group_id' => $this->input->post('role')
);
$this->admin_model->insert_group_user($user_group);
echo "<p style='color:red;'>You are successfully registerd.</p>";
}
}
else
{
echo "<p style='color:red;'>".validation_errors()."</p>";
}
}
}
So how to resolve this issue?What should I have to change in my code?
As I said, the problem is probably in the data you send to backend. If you want to submit AJAX with input file, use FormData.
Try this:
jQuery(document).on('submit', '#signup_form', function()
{
//debugger;
var data = new FormData($('#signup_form')[0]);
jQuery.ajax({
type : 'POST',
url : '<?php echo base_url()."front/ajax_register"; ?>',
data : data,
processData: false,
contentType: false,
success : function(data)
{
jQuery(".result").html(data);
}
});
return false;
});
Try this:
$('#upload').on('click', function() {
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url : 'upload.php', // point to server-side PHP script
dataType : 'text', // what to expect back from the PHP script, if anything
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
success : function(output){
alert(output); // display response from the PHP script, if any
}
});
$('#pic').val(''); /* Clear the file container */
});
Php :
<?php
if ( $_FILES['file']['error'] > 0 ){
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
{
echo "File Uploaded Successfully";
}
}
?>
This will upload the file.
P.S.: Change the code as per CI method.
var data = jQuery(this).serialize();
this refers to document

Get json data stored as text from mysql

First I have html - bootstrap tab:
<ul class="nav nav-tabs">
<li class="active">Opsti podaci</li>
<li><a id="mapa1" href="#mapa" data-toggle="tab">Mapa parcele</a></li>
<li>Dokumenti</li>
<li>Komentari</li>
</ul>
and below:
<div class="tab-pane" id="mapa">
<div id="myMap" style="height:500px;"></div>
</div>
In database I have this:
Now I write this jquery/ajax code to get json stored as text from mySql database:
$( document ).ready(function() {
$('a#mapa1').click(function (e) {
$.ajax({
url: "getMap.php",
type: "POST",
async: true,
data: { ajdi:ajdi}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
console.log(data);
BlitzMap.setMap( 'myMap', true, 'data' );
BlitzMap.init();
},
error: function(data) {
console.log(data);
}
});
});
but when I click on a#mapa1 notning happend... also when I manualy add this code to execude in console i get error: SyntaxError: Unexpected end of input
What can be a problem here? I dont see! Please help! Thanks!
UPDATE:
try {
$result = $db->prepare("SELECT json FROM map WHERE id_parcele=:ajdi AND user_id=:user_id");
$result->execute(array(':ajdi' => $_POST['ajdi'], ':user_id' => $user_id));
$result = $result->fetchAll();
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo $result;
}
this produce me just Array when I chenge echo $result to echo json_encode($result) again dont work... how to get just plain text ?
With print_r I get this code:
Array
(
[0] => Array
(
[json] => {"zoom":7,"tilt":0,"mapTypeId":"hybrid","center":{"lat":20.487486793750797,"lng":74.22363281640626},"overlays":[{"type":"polygon","title":"","content":"","fillColor":"#000000","fillOpacity":0.3,"strokeColor":"#000000","strokeOpacity":0.9,"strokeWeight":3,"paths":[[{"lat":"21.329035778926478","lng":"73.46008301171878"},{"lat":"21.40065516914794","lng":"78.30505371484378"},{"lat":"20.106233605369603","lng":"77.37121582421878"},{"lat":"20.14749530904506","lng":"72.65808105859378"}]]}]}
[0] => {"zoom":7,"tilt":0,"mapTypeId":"hybrid","center":{"lat":20.487486793750797,"lng":74.22363281640626},"overlays":[{"type":"polygon","title":"","content":"","fillColor":"#000000","fillOpacity":0.3,"strokeColor":"#000000","strokeOpacity":0.9,"strokeWeight":3,"paths":[[{"lat":"21.329035778926478","lng":"73.46008301171878"},{"lat":"21.40065516914794","lng":"78.30505371484378"},{"lat":"20.106233605369603","lng":"77.37121582421878"},{"lat":"20.14749530904506","lng":"72.65808105859378"}]]}]}
)
)
but I need to get just this:
{"zoom":13,"tilt":0,"mapTypeId":"hybrid","center":{"lat":45.38591280296377,"lng":19.93632316979983},"overlays":[{"type":"polygon","title":"Polje 1","content":"Vojvodina","fillColor":"#ffbf1a","fillOpacity":0.3,"strokeColor":"#000","strokeOpacity":0.8,"strokeWeight":3,"paths":[[{"lat":"45.37867863632308","lng":"19.948768615722656"},{"lat":"45.370719925928746","lng":"19.941558837890625"},{"lat":"45.36227764550136","lng":"19.92816925048828"},{"lat":"45.359262240003495","lng":"19.942245483398438"},{"lat":"45.35588479505299","lng":"19.955806732177734"},{"lat":"45.35974471568275","lng":"19.958553314208984"},{"lat":"45.36312193024184","lng":"19.959583282470703"},{"lat":"45.365534102931655","lng":"19.960613250732422"},{"lat":"45.36529289029106","lng":"19.96490478515625"},{"lat":"45.37084052080666","lng":"19.970226287841797"}]]}]}
How I can do that?

Wordpress: get terms by ajax

I'm new in wordpress, but i need to collect all photos in posts, and group by categories. My Js is
function get_photos(elem)
{
$.ajax({
cache: true,
type: "GET",
timeout: 20000,
url: 'wp-content/themes/wp_theme/photos.php',
success: function(msg)
{
$(elem).append(msg);
},
error: function(msg)
{
get_photos(elem);
return false;
}
});
}
And the photos.php is the :
<?php
require('../../../wp-load.php');
$tax_terms = get_terms('media_category', 'orderby=count&order=DESC&hide_empty=0');
foreach ( $tax_terms as $tax_term ) {
?>
<div class="news">
<img src="./wp-content/themes/wp_theme/img/plus.png" class="plus">
<div class="titleNews2"><?php echo $tax_term->name; ?></div>
</div>
<?php
$posts = get_posts(array(
"post_type" => "attachment",
"post_mime_type" => "image",
"taxonomy" => $tax_term->taxonomy,
"term" => $tax_term->slug,
"numberposts" => 100,
"posts_per_page" => 100));
?>
<div class="photoRace">
<?php
$ua = #getenv( HTTP_USER_AGENT );
$touchPadApple = stripos( strtolower( $ua ), "iphone" ) !== false || stripos( strtolower( $ua ), "ipad" ) !== false ? true : false;
foreach($posts as $post){
setup_postdata($post);
$img = get_post_meta($post->ID, "_wp_attachment_metadata", true);
$dir = explode("/", $img['file']);
$link = get_bloginfo('siteurl')."/wp-content/uploads/{$dir[0]}/{$dir[1]}/";
?>
<a <?php echo !$touchPadApple ? "rel=\"photos\" " : "target=_BLANK "; ?>href="<?php echo get_bloginfo('siteurl')."/wp-content/uploads/".$img['file'];?>">
<img src="<?php echo $link.$img['sizes']['thumbnail']['file'];?>" height="<?php echo $img['sizes']['thumbnail']['height']; ?>" width="<?php echo $img['sizes']['thumbnail']['width']; ?>">
</a>
<?php } ?>
</div>
<?php } ?>
Im working on mobile interface, and this script (not via ajax) works well on non-mobile static pages of theme. But when i using it via ajax, im getting only some photos, and if i call var_dump($tax_terms); the result is
object(WP_Error)#4418 (2) { ["errors"]=> array(1) {
["invalid_taxonomy"]=> array(1)
What should i include to use terms?
You should use wp_ajax in the first place, and then you can skip the first require.

Trying to get tag-it to work with an AJAX call

Trying to get tag-it to work with an ajax call.
Everything works so far. Except, I am unable to assign a tagSource via an ajax call.
In firebug, the 'data' is returning:
["Ruby","Ruby On Rails"]
But its not showing up as I type into the input box.
$('.tags ul').tagit({
itemName: 'question',
fieldName: 'tags',
removeConfirmation: true,
availableTags: ["c++", "java", "php", "javascript", "ruby", "python", "c"],
allowSpaces: true,
// tagSource: ['foo', 'bar']
tagSource: function() {
$.ajax({
url: "/autocomplete_tags.json",
dataType: "json",
data: { term: 'ruby' },
success: function(data) {
console.log(data);
return data;
}
});
}
});
console.log(data) returns ["Ruby", "Ruby On Rails"].
Am I missing something here? Anyone else got this to work?
Seems this question hasn't been answered for a long time, I bet you have already found a solution but for those who haven't here is my answer:
The indention got all messed up when i copied from my code ;)
<input type="hidden" name="tags" id="mySingleField" value="Apple, Orange" disabled="true">
Tags:<br>
<ul id="mytags"></ul>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#mytags").tagit({
singleField: true,
singleFieldNode: $('#mySingleField'),
allowSpaces: true,
minLength: 2,
removeConfirmation: true,
tagSource: function( request, response ) {
//console.log("1");
$.ajax({
url: "search.php",
data: { term:request.term },
dataType: "json",
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.label+" ("+ item.id +")",
value: item.value
}
}));
}
});
}});
});
and the "search.php" you can find this in some autocomplete jQuery examples actually.
<?php
$q = strtolower($_GET["term"]);
if (!$q) return;
$items = array(
"Great Bittern"=>"Botaurus stellaris",
"Little Grebe"=>"Tachybaptus ruficollis",
"Black-necked Grebe"=>"Podiceps nigricollis",
"Little Bittern"=>"Ixobrychus minutus",
"Black-crowned Night Heron"=>"Nycticorax nycticorax",
"Heuglin's Gull"=>"Larus heuglini"
);
function array_to_json( $array ){
if( !is_array( $array ) ){
return false;
}
$associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));
if( $associative ){
$construct = array();
foreach( $array as $key => $value ){
// We first copy each key/value pair into a staging array,
// formatting each key and value properly as we go.
// Format the key:
if( is_numeric($key) ){
$key = "key_$key";
}
$key = "\"".addslashes($key)."\"";
// Format the value:
if( is_array( $value )){
$value = array_to_json( $value );
} else if( !is_numeric( $value ) || is_string( $value ) ){
$value = "\"".addslashes($value)."\"";
}
// Add to staging array:
$construct[] = "$key: $value";
}
// Then we collapse the staging array into the JSON form:
$result = "{ " . implode( ", ", $construct ) . " }";
} else { // If the array is a vector (not associative):
$construct = array();
foreach( $array as $value ){
// Format the value:
if( is_array( $value )){
$value = array_to_json( $value );
} else if( !is_numeric( $value ) || is_string( $value ) ){
$value = "'".addslashes($value)."'";
}
// Add to staging array:
$construct[] = $value;
}
// Then we collapse the staging array into the JSON form:
$result = "[ " . implode( ", ", $construct ) . " ]";
}
return $result;
}
$result = array();
foreach ($items as $key=>$value) {
if (strpos(strtolower($key), $q) !== false) {
array_push($result, array("id"=>$value, "label"=>$key, "value" => strip_tags($key)));
}
if (count($result) > 11)
break;
}
echo array_to_json($result);
?>
check this out:
How to get tagSource to work with $.ajax()? (from tag-it's github issue list).
this is an example:
HTML file:
<!doctype html>
<html lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/tag-it.js" type="text/javascript" charset="utf-8"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/flick/jquery-ui.css">
<link href="css/jquery.tagit.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
$(document).ready(function() {
$("#mytags").tagit({
tagSource: function(search, showChoices) {
$.ajax({
url: "auto.php",
data: {search: search.term},
success: function(choices) {
showChoices(choices);
}
});
}
});
});
</script>
</head>
<body>
<ul id="mytags">
<li>Tag1</li>
</ul>
</body>
</html>
(get tag-it.js file from [here][1])
and this is the PHP file:
<?php
header('Content-type: application/json');
$q = $_GET["search"];
//check $q, get results from your database and put them in $arr
$arr[] = 'tag1';
$arr[] = 'tag2';
$arr[] = $q;
echo json_encode($arr);
?>
None of these answers worked as is for me, so I thought I would come back and post my code that does work.
var tagThis = $(".tagit");
tagThis.tagit({
tagSource: function(search, showChoices) {
$.ajax({
url: "/tags/search",
data: { search: search.term },
dataType: "json",
success: function(data) {
var assigned = tagThis.tagit("assignedTags");
var filtered = [];
for (var i = 0; i < data.length; i++) {
if ($.inArray(data[i], assigned) == -1) {
filtered.push(data[i]);
}
}
showChoices(filtered);
}
});
}
});
This code assumes the URL returns a JSON encoded string (an array of strings). It will then filter out any tags that have already been selected in the input. So they aren't repeated in the list. Otherwise, this works for me.
Thanks to the others for sending me on the right path.
tagSource has been depreciated.
Just use:
<script>
$(document).ready(function(){
$("#tagit").tagit({
autocomplete: {
source: "your-php-file.php",
}
});
});
</script>
You can add all the attributes to this:
<script>
$(document).ready(function(){
$("#tagit").tagit({
allowSpaces: true,
singleFieldDelimiter: ';',
allowDuplicates: true,
autocomplete: {
source: "your-php-file.php",
}
});
});
</script>
You should remove your availableTags, as you are overloading tagSource, which is used as source for the autocompletion.
Also that may be a typo, but it "return", and not "eturn".
Edit:
I think the problem is that the function you provided to tagSource doesn't seems to return anything. However my javascript knowledge seems to end here :/
I think that you can overwrite the autocomplete method from jquery UI :
$('.tags ul').tagit({
itemName: 'question',
fieldName: 'tags',
removeConfirmation: true,
//availableTags: ["c++", "java", "php", "javascript", "ruby", "python", "c"]
allowSpaces: true,
// tagSource: ['foo', 'bar']
tagSource: function () {
$.ajax({
url: "/autocomplete_tags.json",
dataType: "json",
data: {
term: 'ruby'
},
success: function (data) {
console.log(data);
return data;
}
});
},
autocomplete: {
delay: 0,
minLength: 2,
source: this.tagSource()
}
});
Just to add
Assuming your script page looks like
<script>
$(document).ready(function(){
$("#myULTags").tagit({
allowSpaces: true,
singleFieldDelimiter: ';',
allowDuplicates: true,
autocomplete: {
source: "searchtag.php",
}
});
});
</script>
Your simple php page if you are fetching values from database would look like
<?php $link = mysqli_connect("localhost","root","dbpassword","dbname") or die("Couldn't make connection."); ?>
<?php
$q = strtolower($_GET["term"]);
if (!$q) return;
header('Content-type: application/json');
$query_tags = mysqli_query($link,"SELECT TagName FROM `tagstable` WHERE `TagName` LIKE '%".$q."%' LIMIT 10");
$items = array(); // create a variable to hold the information
while ($row = mysqli_fetch_array($query_tags)){
$items[] = $row['TagName']; // add the row in to the results (data) array
}
echo json_encode($items);
?>
Regards

Categories