How to append params to ajax request in Select2? - javascript

i'm building a web app using Laravel, and i have to implement tag selection, like this one used by stackoverflow, loading options via ajax and if is not exist create it, i did choose Select2 jquery plugin, the problem i have with it, is cant get it to append parameters to the ajax url,
Route :
/tags/{tag}
how can i append the term of select to my url ?

In Select2 3.x, you can pass a function as the ajax.url option. It will be passed the current search term as the first parameter, which sounds like what you are looking for.
$element.select2({
...
ajax: {
url: function (term) {
return '/tags/' + term;
},
...
}
});

Related

Add a HTML Page To WordPress Site Using Javascript

I'm creating a plugin that will add a custom page to the website (with no template).
I'm struggling to work out how talk to WordPress from inside the Jquery part of my plugin.
At present, there is a variable called res that contains all the HTML for the page.
$.post( templateUrl + "templates/template2.html", function( data ) {
tinyMCE.triggerSave();
var res = data.replace("[([PREHEADER])]", $("#peg-newsletter-preheader").val())
res = res.replace("[([HEADING])]", $("#peg-newsletter-heading").val());
});
Any help is appreciated.
Thanks.
You are using post incorrectly.
This section of the function
function( data ) {
tinyMCE.triggerSave();
var res = data.replace("[([PREHEADER])]", $("#peg-newsletter-preheader").val())
res = res.replace("[([HEADING])]", $("#peg-newsletter-heading").val());
})
is a call back (meaning this is a response you get from WP after you make a successful post). Changing values here only changes the values that you receive rather than wp.
To 'talk' to wp you need to post the data in the body: http://api.jquery.com/jquery.post/
So your jquery post will look like this:
$.post( templateUrl + "templates/template2.html",
{ preHeader: "something", Header: "something" },
function( data ) {
alert("Post successful");
});
However this would assume that your end point allow for a post request to do what you want.
I am not sure what you are trying to achieve though. It looks like you want to change the HTML template of WP? If so I don't know of any rest api that would allow you to do that, as these api's are primarily for pulling WP Posts/Blog data from WP. HTH

How to pass a link value from a HTML page to rest web service

If I have a HTML or a JSP page having list of sports like below.
Tennis
Football
Hockey
Cricket
All these 4 should be a Link. If I click on any of them it should return some details wherever clicked. For this I need to pass this sport name to a REST client which will pass this as a parameter to a rest service.
My question is how to pass the value of a link whichever clicked from HTML page to a Java application like we pass text box or check box values from HTML using the form action? Or is there any better approach, please suggest
I suggest you to look at jQuery.ajax. Basically you'll want to create an XHR (GET, POST etc depending on the rest client configuration) and send your data.
Here is a very crude example on the subject;
$('.sports').on('click', function() {
var clickedElementText = $(this).text();
$.ajax({
url: "/your/endpoint/url",
method: "POST",
data: {
sportName : clickedElementText;
},
}).success(function( response ) {
/* success callback */
}).failure(function( jqXHR, textStatus ) {
/* failure callback */
});
}
Ajax is a good way or you can just define the element
<a href="/sports/detail?sportName=tennis">

Using jquery ajax load() to transfer multiple data fields

I have an HTML form that I am trying to convert to submitting using the Jquery load() function. I have it working for a single field, but I have spent hours trying to get it to work for multiple fields, including some checkboxes.
I have looked at many examples and there seems to be about three of four ways of approaching this:
Jquery .load()
jquery .ajax()
jquery .submit()
and some others. I am not sure what the merits of each approach is but the first example I was following used the .load(), so that is what I have persisted with. The overall object is to submit some search criterion and return the database search results.
What I have at present:
<code>
// react to click on Search Button
$("#SearchButt").click(function(e){
var Options = '\"'+$("#SearchText").val()+'\"' ;
var TitleChk = $("#TitleChk").prop('checked');
if (TitleChk) Options += ', \"TitleChk\": \"1\"';
// load returned data into results element
$("#results").load("search.php", {'SearchText': Options});
return false; //prevent going to href link
});
</code>
What I get is the second parameter appended to the first.
Is there a way to get each parameter sent as a separate POST item or do I have to pull it apart at the PHP end?
It would seem as if you're stumbling over the wrapper, let's go ahead and just use the raw $.ajax() and this will become more clear.
$("#SearchButt").click(function(e){
var Options = {};
Options.text = $('#SearchText').val();
Options.title = $('#Titlechk').prop('checked')) ? 1: 0; //ternary with a default of 0
$.ajax({
url: 'search.php',
type: 'POST',
data: Options
}).done(function(data){
$('#results').html(data); //inject the result container with the server response HTML.
});
return false;
});
Now in the server side, we know that the $_POST has been populated with 2 key value pairs, which are text and title respectively.

jquery mobile - how to pass a parameter when moving from one data-role page to another?

I'm writing a small and simple jquery-mobile app.
The first page is a list view of categories, which is populated by json retrieved from an ajax request.
The second page should be called when the user clicks on one of the categories.
It should open with a list of items that will also be retrieved by an ajax request. The request should get a category_id as a parameter.
I'm planning on using the multi page pattern (multiple pages in the same html).
This is my js code:
$(function() {
initListByUrl($("#categories_ul"), 'http://localhost:3000/categories');
});
function initListByUrl(id, requestUrl) {
$.ajax({
url: requestUrl,
type:'GET',
dataType:'json',
success: function(data) {
var items = []
$.each(data, function(i, elem) {
items.push('<li id="cat_li_'+i+'">' + elem.name + '</li>');
});
id.html(items).listview('refresh');
}
});
}
and the id of the category is another field in elem, lets assume - elem.id.
How can i pass this id as a parameter to the code that will build the second page?
Should I use session storage?
You can use javascript stack to push and pop the data required for every page, like for instance you can push the elem.id in the calee and then pop and use the elem.id in the page called or viewed.
var stack = [];
stack.push(3);
var data = stack.pop();
alert(data);
I've created a plug-in under the MIT license which is compatible with jQuery Mobile 1.4+. The plug-in allows you to use URL parameters to communicate between pages. In addition, since the data is in the URL, it handles page refreshes as well as the user going directly to a specific jQuery Mobile page in your app. You can find it here on GitHub.

Convert many GET values to AJAX functionality

I have built a calendar in php. It currently can be controlled by GET values ​​from the URL. Now I want the calendar to be managed and displayed using AJAX instead. So that the page not need to be reloaded.
How do I do this best with AJAX? More specifically, I wonder how I do with all GET values​​? There are quite a few. The only solution I find out is that each link in the calendar must have an onclick-statement to a great many attributes (the GET attributes)? Feels like the wrong way.
Please help me.
Edit: How should this code be changed to work out?
$('a.cal_update').bind("click", function ()
{
event.preventDefault();
update_url = $(this).attr("href");
$.ajax({
type : "GET"
, dataType : 'json'
, url : update_url
, async : false
, success : function(data)
{
$('#calendar').html(data.html);
}
});
return false;
});
Keep the existing links and forms, build on things that work
You have existing views of the data. Keep the same data but add additional views that provide it in a clean data format (such as JSON) instead of a document format (like HTML). Add a query string parameter or HTTP header that you use to decide which view to return.
Use a library (such as YUI 3, jQuery, etc) to bind event handlers to your existing links and forms to override the normal activation functionality and replace it with an Ajax call to the alternative view.
Use pushState to keep your URLs bookmarkable.
You can return a JSON string from the server and handle it with Ajax on the client side.

Categories