select2 how to display data - symfony

I want to use select2 in my Symfony project but still do not know how to display results. My code for frontend is
$(".js_search").select2({
ajax: {
url: "{{ path('search') }}",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
console.log(data.items);
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) {
return markup;
}, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
});
function formatRepo (repo) {
if (repo.loading) return repo.text;
var markup = '<div class="clearfix">' +
'<div class="col-sm-1">' +
'<img src="' + repo.owner.avatar_url + '" style="max-width: 100%" />' +
'</div>' +
'<div clas="col-sm-10">' +
'<div class="clearfix">' +
'<div class="col-sm-6">' + repo.full_name + '</div>' +
'<div class="col-sm-3"><i class="fa fa-code-fork"></i> ' + repo.forks_count + '</div>' +
'<div class="col-sm-2"><i class="fa fa-star"></i> ' + repo.stargazers_count + '</div>' +
'</div>';
if (repo.description) {
markup += '<div>' + repo.description + '</div>';
}
markup += '</div></div>';
return markup;
}
function formatRepoSelection (repo) {
return repo.full_name || repo.text;
}
g
and for the backend
public function searchAction()
{
$response = new Response();
$response->setContent(json_encode(
[
'items' =>
[
'id' => 1,
'text' => 'test'
]
]
));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
I dont know how should $response looks like or how to show returned data in view.
Somebody know the answer ?
I am using this https://select2.github.io/

Your response should be a JSON array with the elements Select2 uses to create the option tags for the dropdown.
In your case the content in the reposnse to your AJAX request would be:
[{"id": 1, "text":"test"}]
Select2 will then update the element identifed by the JQuery Selector $(.js-search) with the options and values in your response.

Related

Autocomplete Text box in Asp.net MVC

I am working in asp.net MVC. I need a text box to autocomplete by ajax function.
Ajax function can't call values from the controller.
Here is the code:
$( "#birds" ).autocomplete({
source: function( request, response ) {
$.ajax( {
url: "search.php",
dataType: "jsonp",
data: {
term: request.term
},
success: function( data ) {
response( data );
}
} );
},
minLength: 2,
select: function( event, ui ) {
log( "Selected: " + ui.item.value + " aka " + ui.item.id );
}
} );
Here is the complete code:
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
var cache = {};
$( "#birds" ).autocomplete({
minLength: 2,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
$.getJSON( "Your Controller URL", request, function( data, status, xhr ) {
cache[ term ] = data;
response( data );
});
}
});
} );
</script>
Your Controller should response the data in JSON format like:
[{"id":"Locustella naevia","label":"Common Grasshopper Warbler","value":"Common Grasshopper Warbler"},{"id":"Locustella certhiola","label":"Pallas`s Grasshopper Warbler","value":"Pallas`s Grasshopper Warbler"}]
Your JSON should be dynamic, otherwise, it will respond you the same JSON. You should filter your data in your controller before responding back to the AJAX and the data always in the JSON format.
You can find more about autocomplete on https://jqueryui.com/autocomplete/
& https://jqueryui.com/autocomplete/#remote-with-cache

Include js files in Custom Wordpress Plugin

I'm trying to develop my own Wordpress Plugin, but somehow I can't include javascript files in it. Before I concidered to ask this question here, i've done a lot of research, but none of it was fixing my problem. I've read a lot about wp_register_script() and wp_enqueue_script(), and also that I don't have to include both, so I decided to only use wp_enqueue_script().
The javascript file is located in wp-content/snappy-list-plugin/js/public/snappy-wordpress-plugin.js, and the index file is located in wp-content/snappy-list-plugin/snappy-wordpress-plugin.php.
In the snappy-wordpress-plugin.php file I have:
function mslb_public_scripts(){
wp_enqueue_script('custom_js', plugins_url( '/snappy-list-plugin/js/public/snappy-wordpress-plugin.js', __FILE__ ), array('jquery'), '', true);
}
which seems to be oke, but it doesn't include the file.
On top of the file I have:
add_action('wp_enqueue_scripts', 'mslb_public_scripts');
Can somebody help me with this?!
I tried to add wp_register_script(), but it doesn't work
add_action('admin_enqueue_scripts', 'mslb_public_scripts');
function mslb_public_scripts(){
wp_enqueue_script('custom_js', plugins_url( '/snappy-list-plugin/js/public/snappy-wordpress-plugin.js', __FILE__ ), array('jquery'), '', true);
}
snappy-wordpress-plugin.js file:
jQuery(document).ready(function($) {
var wpajax_url = document.location.protocol + '//' + document.location.host + '/wp-admin/admin-ajax.php';
var email_capture_url = wpajax_url += '?action=swp_save_subscription';
$('form.swp_form').bind('submit', function(){
$form = $(this);
var form_data = $form.serialize();
$.ajax({
'method' : 'post',
'url' : email_capture_url,
'data' : form_data,
'dataType' : 'json',
'cache' : false,
'success' : function( data, textStatus){
if(data.status == 1){
$form[0].reset();
alert(data.message);
} else {
var msg = data.message + '\r' + data.error + '\r';
$.each(data.error, function(key, value){
msg += '\r';
msg += ' - ' + value;
});
alert( msg );
}
},
'error' : function(jqXHR, textStatus, errorThrown){
}
});
//stop the form from submitting normally
return false;
});
});```
The right action is wp_enqueue_scripts
add_action('wp_enqueue_scripts', 'mslb_public_scripts');
function mslb_public_scripts(){
wp_register_script('custom_js', plugins_url('/js/public/snappy-wordpress-plugin.js',__FILE__ ), array('jquery'), '', true);
wp_enqueue_script('custom_js');
}

getting always the default link with ajax

I need to change the above link from
Voucher to special action..
The new link is getting from 'Slink ' in the DB
So how can I change it so the page will be the link provided in 'Slink' and not the default link
$.ajax({
url: '/Newsletter/GetUserOrder?id=' + id,
type: "POST",
dataType: 'json',
data: id,
success: function (response)
{
if (response === "")
{
location.href = '/Newsletter/CardDetails'+ id;
}
else
{
var Bname='';
var itemsQuantity;
var name = '';
var Link="פירוט הטבה"
$.each(response, function (indexInArray, valueOfElement)
{
Bname += '<div class="card col-md-5">' + '<b>' + valueOfElement.shortNameVar + '</b>' + '<br/> ' + valueOfElement.BusnessName + '</div>' + '<br/>' + '<div class="chip">' + "כמות" + valueOfElement.MemberOrderQuntity + '</div>' +
'<b>' + '<div class="flx-aut text-center">' + '' + Link + '' + '<div>';
});

How To open thickbox, onclicking Tinymce Button with dynamic content from ajax

I have added a tinymce button to my tinymce editor.but instead of opening the tinymce default modal (editor.addCommand),I want to open Thickbox with ajax content.I have searched many answers on stackoverflow, but didn't make it out.
Here is my code
(function() {
tinymce.PluginManager.add('smart_event', function( editor, url ) {
var shortcode_tag = 'smart_event';
editor.addCommand('smart_event_panel_popup', function( ui, v ){
var columns = '4';
if(v.columns){
columns = v.columns;
}
var style = '';
if(v.style){
style = v.style;
}
editor.windowManager.open({
title: 'Smart Event Shortcode',
body: [
//...........
],
onsubmit: function(e){
// var scode = '[' + shortcode_tag +' columns="' + e.data.columns + '"' + ' style="' + e.data.style + '"' + ' posts_per_page"'+ e.data.posts_per_page +'"' + ' sortby="'+ e.data.sortby +'"' + ' range="'+ e.data.range +'"' + ' pagination="'+e.data.pagination + '"' +' filters="'+e.data.filters + '"' +']';
editor.insertContent( scode );
}
});
});
editor.addButton('smart_event', {
image: seventadmindata.imagesurl + 'icon.png',
tooltip: 'Insert Smart Event Shortcode',
onclick: function(){
editor.execCommand('smart_event_panel_popup','',{
columns : '4',
style : '1',
});
}
});
});
})();
How can I add Thickbox on click with an ajax callback?

MVC 4 - 500 error on JSON call

I have started using VS2012 (Yes about time). I have a MVC 4 app.
Im making a JSON call to get data from DB to render in html.
But Im getting a 500 Internal Server error I can see in Fiddler.
Im not sure how to debug this because I cant find where to
see the C# exception if that is what the issue is.
So Im calling getRecipe in javascript.
public JsonResult GetRecipe(int rid)
{
var recipe = _rep.GetRecipe(rid);
return Json(recipe, JsonRequestBehavior.AllowGet);
}
My script is
var dataService = new function () {
var serviceBase = '/Recipes/'
getRecipesList = function (callback) {
$.getJSON(serviceBase + 'GetRecipesList', {}, function (data) {
callback(data);
});
};
getRecipe = function (rid, callback) {
$.getJSON(serviceBase + 'GetRecipe', {rid:rid}, function (data) {
callback(data);
});
};
return {
getRecipesList: getRecipesList,
getRecipe: getRecipe
};
} ();
var renderer = new function () {
renderList = function () {
dataService.getRecipesList(renderListDiv);
},
renderListDiv = function (recipes) {
var listDiv = $('#listdiv');
listDiv.html("");
$(recipes).each(function (index) {
var table = '<table>';
table += ('<tr><td><a class="recipeLink" href="#recipeList-' + this.RecipeID + '">' + this.RecipeTitle + '</a></td></tr>');
table += '</table>';
listDiv.append(table);
});
},
selectedRecipe = function (anchor) {
var href = $(this).attr("href");
var rid = href.split("-")[1];
dataService.getRecipe(rid, renderRecipe);
};
renderRecipe = function (recipe) {
var recipeDiv = $('#recipediv');
var html = '<h1>' + recipe.RecipeTitle + ' (' + recipe.RecipeID + ')</h1>';
html += '<h4>Preparation Time: ' + getTimeString(recipe.PrepTime) + '</h4>';
html += '<h4>Cooking Time: ' + getTimeString(recipe.CookTime) + '</h4>';
var count = recipe.Ings.length;
var colmax = Math.ceil(count / 2);
var colleft = 0;
var colright = colmax;
html += '</br><table id="ingredientstable">';
for (colleft = 0; colleft < colmax; colleft++) {
html += '<tr>';
html += '<td>' + recipe.Ingredients[colleft].Units + ' ' + recipe.Ingredients[colleft].Measure + ' ' + recipe.Ingredients[colleft].IngredientName + '</td>';
if(colright < count)
html += '<td>' + recipe.Ingredients[colright].Units + ' ' + recipe.Ingredients[colright].Measure + ' ' + recipe.Ingredients[colright].IngredientName + '</td>';
colright += 1;
html += '</tr>';
}
html += '</table>';
html += '<h4>Method</h4>';
html += '<p>' + recipe.Method + '</p>';
recipeDiv.html(html);
numingredients = 0;
editorForm.loadEditor(recipe);
};
clearRecipe = function () {
$('#recipediv').html("");
};
getTimeString = function (time) {
if (time < 60)
return time + ' min';
return time / 60 + ' hours'
};
changeFont = function () {
$('body').css("font-family", "Comic Sans MS");
};
return {
renderList: renderList,
selectedRecipe: selectedRecipe,
changeFont: changeFont,
clearRecipe: clearRecipe,
};
}();
The browser's developer tools might be a good place to get some additional information. In Chrome you can press F12 to bring up the dev tools window. Click on the network tab and then fire off your ajax call. You will see the failed request highlighted in red. If you click on it you will see the error that has been returned from mvc.
I have provided a screenshot in this question: Ajax call with a 'failed to load resource : the server responded with a status of 500'

Resources