Chained Select2 whith ajax json values - ajax

Have some problems to populate a Select2 with json data retrieved by ajax.
I check all samples from Select2-Github-AjaxData and other from StackOverFlow so always have same problem... the Json retrieved can't update next select2.
Some tries i use Jquery.Ajax to retrieve and assign:
function loadvariedad() {
var productIDVal= $("#frb_producto").val();
$.ajax ({
url: "http://www.fruitbull.info/api/json/es/v",
data: {idv: productIDVal, key:"123456"},
delay: 250,
dataType: 'json',
success: function(theResponse) {
$("#frb_variedad").select2({
data: theResponse.items
});
}
});
};
Other solution checked was the sample on Github form Ajax:
var productIDVal= $("#frb_producto").val();
$('#frb_variedad').select2({
ajax: {
url: 'http://www.fruitbull.info/api/json/es/v?key=123&idv='+productIDVal,
processResults: function (data) {
return {
results: data.items
};
}
}
});
Any idea or help to check?
My sample and tries on Fiddle
Solved by json origin data was formatted incorrectly

Related

Can Js and Model.findAll() unable to display data in UI

I have this code where i am trying to retrieve data from model.findall() and display in UI as table
model.js
define(['jquery', 'can'], function ($, can) {
var serviceModel = can.Model.extend({
findAll: function (params,servicename) {
return $.ajax({
type: 'POST',
dataType: 'JSON',
contentType: 'application/json',
url: 'data/+ servicename',
success: function (data) {
console.log("Success ");
},
error: function () {
console.log("Error");
}
});
}
}, {});
return serviceModel;
});
controller.js
serviceModel.findAll(params,"SP_table", function(data) {
if (data.status === "success") {
$('#idtable').dataTable().fnClearTable();
$('#idtable').dataTable().fnAddData(data.result);
}else{
alert("inside alert");
}
});
issue is in serviceModel.findAll() i am unable to get data inside serviceModel.findAll() because data is in the form of stored procedure or macro, which i am getting using "servicename" from function above
please let me know how to resolve this issue.
You can access the raw xhr data from the ajax call and convert it to an appropriate format by overriding the parseModels method:
https://canjs.com/docs/can.Model.parseModels.html
Overwriting parseModels If your service returns data like:
{ thingsToDo: [{name: "dishes", id: 5}] } You will want to overwrite
parseModels to pass the models what it expects like:
Task = can.Model.extend({ parseModels: function(data){ return
data.thingsToDo; } },{}); You could also do this like:
Task = can.Model.extend({ parseModels: "thingsToDo" },{});
can.Model.models passes each instance's data to can.Model.model to
create the individual instances.
In their example above, the response is a nested JSON: in yours, it is your procedure or macro. You have the opportunity here in parseModels to rewrite the response in the appropriate format.

fetching json data using ajax

Somebody please advice on why $.Ajax that am trying to use fetching webApi data is not working but $.getJSON one is working.I would wish to use $.Ajax instead of $.getJSON.
Both codes are here below.
This one works
var uri = 'api/products';
// Send an AJAX request
$(document).ready(function () {
// Send an AJAX request
$.getJSON(uri)
.done(function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (key, item) {
// Add a list item for the product.
$('<li>', { text: formatItem(item) }).appendTo($('#products'));
});
});
...........................................
This does not work.
var uri = 'api/products';
// Send an AJAX request
$(document).ready(function () {
$.ajax({
url: 'api/products',
type: 'GET',
datatype: 'json',
cache: 'false',
success:function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (key, item) {
// Add a list item for the product.
$('<li>', { text: formatItem(item) }).appendTo($('#products'));
});
}
});
});

Ajax request type POST returning GET

I'm currently trying to make an ajax POST request to send a testimonial simple form to a Django view. The problem is this request is returning a GET instead of a POST.
This is my ajax:
<script>
$(document).ready(function(){
$("form.testimonial-form").submit(function(e){
e.preventDefault();
var dataString = $(this).serialize();
$.ajax({
type: "POST",
url: "/testimonials",
data: dataString,
success: function(_data) {
if (_data[0]){
$('.modal-text').css({display: "none"});
}
else{
$('.unsuccess').css({display: "block"});
}
}
});
});
});
</script>
Any idea what could I be doing wrong?
replace type by method
method: 'post',
also you may need send headers:
headers: {
'X-CSRFToken': getCSRFToken()
},
where getCSRFToken is:
function getCSRFToken() {
return $('input[name="csrfmiddlewaretoken"]').val();
}
I am not really sure why this is happening, but i would write the function in a bit different way. since ajax();'s default type is "GET", i suspect somewhere it is being set to default.
first set the type="button" of submit button (whose id is e.g. "submit_button_id"), so it doesnot submits if you click on it. or put the button outside of <form>
then try this code
<script>
$(function(){ // same as "$(document).ready(function()"..
$("#submit_button_id").on('click',function(){
var dataString = $('form.testimonial-form').serialize();
$.ajax({
type: "POST",
url: "/testimonials",
data: dataString,
success: function(_data) {
if (_data[0]){
$('.modal-text').css({display: "none"});
}
else{
$('.unsuccess').css({display: "block"});
}
}
});
});
});
</script>

Is it possible to make multiple calls using Jsonp with deferred objects?

I'm trying to make two or more requests all at once if that's even possible? I'm concerned about speed since after the first request is made I want to display that info onto a web page and then do the same for each additional url.
I've been reading about deferred objects and trying some examples, and so far I've tried to do this,
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script >
$(document).ready(function($) {
// - 1st link in chain - var url = 'https://www.sciencebase.gov/
catalog/items?parentId=504108e5e4b07a90c5ec62d4&max=60&offset=0&format=jsonp';
// - 2nd link in chain - var url = 'https://www.sciencebase.gov/
catalog/itemLink/504216b6e4b04b508bfd333b?format=jsonp&max=10';
// - 3rd (and last) link in chain - var url = 'https://www.sciencebase.gov/
catalog/item/4f4e4b19e4b07f02db6a7f04?format=jsonp';
// parentId url
function parentId() {
//var url = 'https://www.sciencebase.gov/catalog/items?parentId=
504108e5e4b07a90c5ec62d4&max=3&offset=0&format=jsonp';
return $.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/items?parentId=
504108e5e4b07a90c5ec62d4&max=3&offset=0&format=jsonp',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {},
error: function(e) {
console.log(e.message);
}
});
}
// itemLink url
function itemLink() {
//var url = 'https://www.sciencebase.gov/catalog/itemLink
/504216b6e4b04b508bfd333b?format=jsonp&max=10';
return $.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/itemLink
/504216b6e4b04b508bfd333b?format=jsonp&max=10',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {},
error: function(e) {
console.log(e.message);
}
});
}
// Multiple Ajax Requests
$.when( parentId(), itemLink()).done(function(parentId_data, itemLink_data) {
console.log("parentId_data.items[0].title");
});
});
But it doesn't seem like the functions are functioning. I was expecting to be able to put some stuff after the .when() method inside the function to tell my program what to do, but I'm not getting anything displayed??
Thanks for the help!
Part of the problem is that in the done handler for $.when, the arguments that are passed to the callback are the array of arguments for each request, not simply the data that you want to use. You can get around this by using .pipe as in the example below.
Also, don't specify jsonpCallback unless you have a very good reason, most of the time you want to let jQuery manage that internally for you.
Here's a working example tested on JSFiddle
jQuery(function($) {
function parentId() {
return $.ajax({
url: 'https://www.sciencebase.gov/catalog/items?parentId=504108e5e4b07a90c5ec62d4&max=3&offset=0&format=jsonp',
dataType: 'jsonp',
error: function(e) {
console.log(e.message);
}
// We'll use pipe here so that rather than the value being passed to our $.when handler
// is simply our data rather than an array in the form of [ data, statusText, jqXHR ]
}).pipe(function( data, statusText, jqXHR ) {
return data;
});
}
function itemLink() {
return $.ajax({
url: 'https://www.sciencebase.gov/catalog/itemLink/504216b6e4b04b508bfd333b?format=jsonp&max=10',
dataType: 'jsonp',
error: function(e) {
console.log(e.message);
}
}).pipe(function(data) {
return data;
});
}
// Multiple Ajax Requests
$.when( parentId(), itemLink()).done(function(parentId_data, itemLink_data) {
console.log( parentId_data, itemLink_data );
});
});

asp.net mvc ajax driving me mad

how come when I send ajax request like this everything works
$(".btnDeleteSong").click(function () {
var songId = $(this).attr('name');
$.ajax({
type: 'POST',
url: "/Home/DeleteSong/",
data: { id: songId },
success: ShowMsg("Song deleted successfully"),
error: ShowMsg("There was an error therefore song could not be deleted, please try again"),
dataType: "json"
});
});
But when I add the anonymous function to the success It always showes me the error message although the song is still deleted
$(".btnDeleteSong").click(function () {
var songId = $(this).attr('name');
$.ajax({
type: 'POST',
url: "/Home/DeleteSong/",
data: { id: songId },
success: function () { ShowMsg("Song deleted successfully"); },
error: function () {
ShowMsg("There was an error therefore song could not be deleted, please try again");
},
dataType: "json"
});
});
what if i wanted few things on success of the ajax call, I need to be able to use the anonymous function and I know that's how it should be done, but what am I doing wrong?
I want the success message to show not the error one.
function ShowMsg(parameter) {
$("#msg").find("span").replaceWith(parameter);
$("#msg").css("display", "inline");
$("#msg").fadeOut(2000);
return false;
}
Make sure your action is returning Json data.
"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
http://api.jquery.com/jQuery.ajax/
Your action method should surely return Json data. I have the similar code see if that helps.
public ActionResult GetAllByFilter(Student student)
{
return Json(new { data = this.RenderPartialViewToString("PartialStudentList", _studentViewModel.GetBySearchFilter(student).ToList()) });
}
$("#btnSearch").live('click',function () {
var student = {
Name: $("#txtSearchByName").val(),
CourseID: $("#txtSearchByCourseID").val()
};
$.ajax({
url: '/StudentRep/GetAllByFilter',
type: "POST",
data: JSON.stringify(student),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(result) {
$("#dialog-modal").dialog("close");
RefreshPartialView(result.data);
}
, error: function() { alert('some error occured!!'); }
});
});
Above code is used to reload a partial view. in your case it should be straight forward.
Thanks,
Praveen

Resources