selectize.js doesn't work with remote url - javascript

I'm using selectize like this:
$('#category_field').selectize({
valueField: 'name',
searchField: 'name',
delimiter: "/",
options: [],
load: function(query,callback)
{
if(!query.length) return callback();
$.ajax({
url: '/categories/autocomplete',
type: 'GET',
dataType: 'jsonp',
data: {
},
error: function() {
callback();
},
success: function(res) {
callback(res.movies);
}
});
}
}
);
"#category_field" is just a form input of type text.
I verified that the ajax request is being made and the response from the server looks like this:
[
{
"_id": {
"$oid": "568bee09421aa908fe000009"
},
"depth": 0,
"name": "math",
"parent_id": null,
"parent_ids": [],
"picture": {
"url": "/uploads/category/picture/568bee09421aa908fe000009/Screenshot________________.png",
"thumb": {
"url": "/uploads/category/picture/568bee09421aa908fe000009/thumb_Screenshot________________.png"
}
}
}
]
My problem is that the autocomplete dropdown menu doesn't even show, what to do ?
Edit
I just wanted to mention that I'm using bootstrap 3 , the input field and the label for it are wrapped inside <div class=field>...</div>, this div is wrapped inside the form which is wrapped inside container inside panel.
Does this relate to the problem ?

This response not looks like a valid JSON. Check console, or/and use trycatch
try { $.ajax(...) } catch (err) { console.error(err); }
And JSONP is crossDomain method, maybe you can try delete it.

What i noticed
You are not passing any query to the service
You have to set preLoad true to load the options or have to set preLoad in focus to set the options initially
or
You have to initialize the option with the array as like your response

Related

Datatable returning 0 results

I need to load a datatable with a JSON dataset. I don't want to do server side processing. but I do want to retrieve the full set of data from a URL. I got to the point where there's no error on load but for some reason, the table stays empty with 0 results.
I am building the JSON on the server side like this:
public static function datatableOutput($array){
foreach($array as $key=>$line){
$output[] = [
"href"=>$line['href'],
"code"=>$line['code'],
"time"=>$line['time'],
"img_count"=>$line['img_count'],
"int_count"=>$line['int_count'],
"ext_count"=>$line['ext_count']
];
}
return array('data'=> $output);
}
Later in the code it returns a json string like this:
return response()->json($this::datatableOutput($links));
And in the view my script looks like this:
$.ajax({
url: '/crawl',
type: "post",
data: {
url: $("#url").val(),
pages: $("#pages").val(),
_token:"{{ csrf_token() }}"
},
dataType : 'json',
success: function(data){
// Done state
$('#iamarobotnotaslave').hide();
$('#justasecdude').hide();
$('#crawl').hide();
$('#report_section').show();
$('#report').DataTable( {
data: data,
columns: [
{ title: "href" },
{ title: "code" },
{ title: "time" },
{ title: "img_count" },
{ title: "int_count" },
{ title: "ext_count" }
]
} );
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// Error state
$('#iamarobotnotaslave').hide();
$('#justasecdude').hide();
$('#goaheaddude').show();
$('#error').show();
}
});
The JSON data set returned looks like this:
{
"data":[
{
"href":"\/",
"code":200,
"time":0.2746608257293701,
"img_count":6,
"int_count":204,
"ext_count":6
},
{
"href":"\/feature\/automated-marketing-reports",
"code":200,
"time":0.1753251552581787,
"img_count":7,
"int_count":72,
"ext_count":6
},
{
"href":"\/feature\/marketing-dashboard-2",
"code":200,
"time":0.15781521797180176,
"img_count":8,
"int_count":73,
"ext_count":6
}
]
}
Everything seems to be valid but for some reason I still get 0 results ... I am probably missing something obvious thought. I tried the JSON with and with out the "data" array.

Select2: Creating tags with ajax

I am using the select2 library.
My select2 element can search the database for each tag via the ajax and that works fine.
My issue is, I want the user to also be able to create a new tag. Looking at their documentation I should use the createTag option; however, this fires as soon as I click into the element and on each key press.
Can anyone offer any guidance on how I can achieve my goal?
here is my code thus far
I am using ajax top search for tags but I would also like to create new tags to the database. I have tried doing this via createTag but this seems to be firing as soon as I click in the HTML element and on each key press.
Here is my code:
$('.tags').select2({
tags: true,
placeholder: "These tags will apply to all lines",
tokenSeparators: [','],
ajax: {
url: '/api/tags/find',
dataType: 'json',
data: function (params) {
return {
q: $.trim(params.term)
};
},
processResults: function (data) {
return {
results: data
}
},
cache: true,
},
createTag: function(params) {
alert('tag created') // This is were I would put my ajax POST.
}
});
After reading the documentation again, I can see I should have been using the events https://select2.org/programmatic-control/events
I used the createTag option to assign newTag: true to newly created tags and used the select2:selected event which checked if a new tag had been selected and, if it was, sent an ajax request to the server to create that tag.
$('.tags').select2({
tags: true,
placeholder: "These tags will apply to all lines",
minimumInputLength: 3,
tokenSeparators: [','],
ajax: {
url: '/api/tags/find',
dataType: 'json',
data: function (params) {
return {
q: $.trim(params.term)
};
},
processResults: function (data) {
return {
results: data
}
},
// cache: true,
},
createTag: function(params) {
let term = $.trim(params.term);
if (term.length < 3)
{
return null
}
return {
id: term,
text: term,
newTag: true,
}
},
});
$('.tags').on('select2:select', function (e) {
let tag = e.params.data;
if (tag.newTag === true)
{
axios.post('/api/newtag', {
name: tag.text,
type: 'default',
})
}
});

JSONP ajax callback failing

I have following script running on my local test drive. It imports a JSON file and builds a webpage, but for some reason, there is an error in handling the data. No data is shown...
But whenever I use (the same) data hard-coded, I get the result I want. So this made me think it has something to do with the way I handle the JSON import...
This is my AJAX callback:
getGames: function(fn) {
$.ajax({
type: "GET",
url: App.Config('webserviceurl')+'games-payed.js',
dataType: "jsonp",
success: function (data) {
console.log('streets', data);
if(fn){
fn(data);
}
},
error: function (msg) {
if(fn){
fn({status:400});
}
}
});
}
And this code isn't working, nor am I getting any errors in my console...
When I load the data hard coded, it works perfectly:
getGames: function(fn) {
var games = App.Config('dummyGames');
if(fn){
fn(games);
}
}
Is there something wrong with my AJAX callback?
EDIT:
The JSON file looks like this:
jsonp1({
"status": "200",
"data": [
{
"id": "1",
"title": "Title 1",
"publishDate": "2013-03-27T15:25:53.430Z",
"thumbnail": "images/thumbs/image_game1.png",
"html5": "http://mysite.com/index.html"
},
{
"id": "2",
"title": "Title 2",
"publishDate": "2013-03-20T15:25:53.430Z",
"thumbnail": "images/thumbs/image_game2.png",
"html5": "http://mysite.com/index.html"
},
{
"id": "3",
"title": "Title 3",
"publishDate": "2013-03-18T15:25:53.430Z",
"thumbnail": "images/thumbs/image_game3.png",
"html5": "http://mysite.com/index.html"
}
]
});
In your example, I see that you wrap your json data inside jsonp1. I suppose that is a fixed name. If that's the case, try this:
getGames: function(fn) {
$.ajax({
type: "GET",
url: App.Config('webserviceurl')+'games-payed.js',
jsonp: false,
jsonpCallback:"jsonp1",
dataType: "jsonp",
success: function (data) {
console.log('streets', data);
if(fn){
fn(data);
}
},
error: function (msg) {
if(fn){
fn({status:400});
}
}
});
}
Notice the jsonpCallback:"jsonp1" and jsonp: false. The reason for this is: by default, jquery will generate the callback function name automatically and randomly and append ?callback=generatedFunctionName to the end of your url. Thanks to the callback parameter, the code on server side could use the same function name to call the callback on browser.
In your case, you're using fixed function name (jsonp1), so you have to:
Specify your function name explicitly using jsonpCallback="jsonp1"
Set jsonp = false to prevent jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation.

How to send data to a web Service Using Winj.xhr

I am new in Winjs coding I have data in a list .
and i want to send that data to my json Web Service .
I have a success to call to web service and i have the response so the web service is
working but the data doesn't seem to be sent. I dont know how to declare the data.
I have many data to sent like(username,first_name,last_name,password) to my Register.json
The Register.json have this response after the execution:
{
"format":
"json",
"success":
false,
"errors":
["User name is empty"],
"result":
null
}
so i m sure that data doesnt be sent
function Register() {
var dataArray = [
{
username: "Marley",
first_name: "dog",
last_name: "ded",
password: "pdre4252d"
}];
WinJS.xhr({
url: "my_Base_URL/Register.json",
type: "post",
headers: { "Content-type": "application /x-www-form-urlencoded" },
data: dataArray
// data:JSON.stringify(dataArray)
}).done(
function complete(result) {
if (result.status === 200) {
console.log("Success: Response Text: " + result.responseText);
}
else {
console.log("Fail:Response Text: " + result.responseText);
}
},
function error(error) {
console.log("error");
},
function progress(result) {
}
);
}
I will be thinkful if someone give me some help.
The WinJS.xhr() is a promise wrapper around XMLHttpRequest, which means it delegates your parameters to an XMLHttpRequest object and returns a WinJS.Promise object. The parameters may not be delegated correctly so play with adding and empty string for a username and such. Otherwise you can mimic the same functionality by creating your own WinJS.Promise with an XMLHttpRequest inside.

Sending a multi-level javascript object to the server with AJAX fails

I have a javascript object that looks somthing like this:
var obj = {
"name": "username",
"userid": "9999",
"object1": {
"subObject1": {
"subArray1": [],
"subArray2": []
},
"subObject2": {
"subArray3": [],
"subArray4": []
}
},
"object2": {
"subObject3": {
"subArray5": [],
"subArray6": []
}
},
"array1": [],
"array2": []
};
I have tried to use a jQuery ajax call like this:
$.ajax({
url: "test.php",
type: "POST",
dataType: "text",
processData: false,
data: obj,
success: function(data, status) {
alert("Sucsess");
}
});
The problem is that PHP doesn't receive anything. The $_POST variable is empty. I'm not sure what I'm doing wrong.
Thanks
First, include JSON2.js (Link at bottom of that page) on the page, then change your call to this:
$.post(
"test.php",
data: JSON.stringify( obj ),
function(data, status) {
alert("Sucsess");
});
Try out jQuery 1.4.1 the $.param function was completely rewritten to support things like this.
Why not send it by using something like the json2 library to serialize the whole object as JSON, then send that via a single parameter? I don't know PHP but I would be stunned if there weren't dozens of alternative JSON parsers available.
I don't believe it is possible to send a data object like that.
If you wanted to do something like that you would have to serialize it before you send the data and then unserialize at the server. HTTP has it's limits.

Categories

Resources