how to use json data sent from backend - javascript

$.ajax({
url: '{{ URL('reports/groupsUsersGet') }}',
dataType: "json",
data: {
group_id : $('#group').val(),
},
success: function(data) {
<li>"i want to insert variable here"<li>
},
error: function (data) {
console.log('Error:', data);
}
});
controller returns this
return Response::json($results);
and it gives this
{"results":[{"id":1,"name":"user","nick":"user1"}]}
how can i acces this in ajax part

You can use the data in ajax, sent from controller like this:
$.ajax({
url: '{{ URL('reports/groupsUsersGet') }}',
dataType: "json",
data: {
group_id : $('#group').val(),
},
success: function(data) { // <-------- here data is your variable having json received from backend
$.each(data.results, function(key, val) {
// Use your results array here...
$('li.data').each(function(i) {
$(this).find('span.id').text(val.id);
$(this).find('span.name').text(val.name);
$(this).find('span.nick').text(val.nick);
});
});
},
error: function (data) {
console.log('Error:', data);
}
});
You'll get json inside the data variable under the success section of your ajax call
Hope this helps!

In your success method you can access the data returned from the server as:
success: function(data) {
var users = data.results;
var temptale = '';
for (var i = users.length - 1; i >= 0; i--) {
temptale += "<li>Name - " + users[i]['name'] + "<li>"
}
// use temptale to insert in your DOM
},

var queryInfoById= function (id) {
var params = {
"id": id,
};
$.getJSON(prefix + "/queryById.do", params, function (data) {
$("#name").val(data.name);
$("#age").val(data.age);
});
};

$.ajax({
url: '{{ URL('reports/groupsUsersGet') }}',
dataType: "json",
data: {
group_id : $('#group').val(),
},
success: function(data) {
var array = data.results;
for (var i=0; i < array.length; i++){
var obj = array[i];
var id = obj.id;
var name= obj.name;
var nick= obj.nick;
//Add here the data in your UL>LI elements.
}
},
error: function (data) {
console.log('Error:', data);
}
});

Related

Using Wikipedia's API to fetch results from search query

I am trying to use Wikipedia's API to make a search query, then append those results to my page. This is what I have so far :
"use strict";
$(document).ready(function(){
function searchWikipedia(searchCriteria){
$.getJSON('https://en.wikipedia.org/w/api.php?action=query&format=json&limit=15&callback=?&titles=' + searchCriteria, processResult);
}
$('#btn').click(function searchCriteria() {
var searchCriteria = $("input[name=Wikipedia]").val();
searchWikipedia(searchCriteria);
})
function processResult(apiResult){
if (apiResult.query.pages[-1]){
console.log("No results");
} else {
for (var i = 0; i < apiResult.length; i++){
$('#display-result').append('<p>'+apiResult+'</p>');
}
}
}
});
So far nothing appends to my html and there's no errors in my console.
#Ali Mamedov's answer is the way to go (it's from Wikipedia)
But the wikipedia link is missing the http:. Also, you can handle the response on your function:
$(document).ready(function(){
$('#btn').click(function() {
$.ajax({
url: 'http://en.wikipedia.org/w/api.php',
data: { action: 'query', list: 'search', srsearch: $("input[name=Wikipedia]").val(), format: 'json' },
dataType: 'jsonp',
success: processResult
});
});
});
function processResult(apiResult){
for (var i = 0; i < apiResult.query.search.length; i++){
$('#display-result').append('<p>'+apiResult.query.search[i].title+'</p>');
}
}
<script type="text/javascript">
$.ajax({
type: "GET",
url: "http://en.wikipedia.org/w/api.php?action=opensearch&search=" + txt + "&callback=?",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data, textStatus, jqXHR) {
$.each(data, function (i, item) {
if (i == 1) {
var searchData = item[0];
WikipediaAPIGetContent(searchData);
}
});
},
error: function (errorMessage) {
alert(errorMessage);
}
});
}
function WikipediaAPIGetContent(search) {
$.ajax({
type: "GET",
url: "http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text&section=0&page=" + search + "&callback=?",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data, textStatus, jqXHR) {
var markup = data.parse.text["*"];
var blurb = $('<div></div>').html(markup);
// remove links as they will not work
blurb.find('a').each(function () { $(this).replaceWith($(this).html()); });
// remove any references
blurb.find('sup').remove();
// remove cite error
blurb.find('.mw-ext-cite-error').remove();
$('#results').html($(blurb).find('p'));
$('#results').html(blurb);
},
error: function (errorMessage) {
alert(errorMessage);
}
});
}
</script>
Try this sample:
$(document).ready(function(){
$('#btn').click(function() {
$.ajax({
url: '//en.wikipedia.org/w/api.php',
data: { action: 'query', list: 'search', srsearch: $("input[name=Wikipedia]").val(), format: 'json' },
dataType: 'jsonp',
success: function (x) {
console.log('title', x.query.search[0].title);
}
});
});
});
Source
This will show the query result with image:
$(document).ready(function(){
$('#btn').click(function() {
var search_text = $("input[name=Wikipedia]").val();
var url = 'https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=';
$.getJSON( url + search_text +'&callback=?',function(data){
for(var key in data.query.pages){
var titleArt = data.query.pages[key].title;
var extractArt = data.query.pages[key].extract;
var linkArt = 'https://en.wikipedia.org/?curid=' + data.query.pages[key].pageid;
var imgArt;
if(data.query.pages[key].hasOwnProperty('thumbnail')){
imgArt = data.query.pages[key].thumbnail.source;
} else {
imgArt = 'http://www.wallpaperup.com/uploads/wallpapers/2014/04/02/319530/big_thumb_e96d0c33f97706bc093572bc613cb23d.jpg';
}
var contentHTML = '<div class="col-md-4"><div class="box-result"><div class="bg-result"></div><div class="box-content center-block"><div class="article-thumbnail"><img src="' + imgArt + '" alt="" /></div><h1>'+ titleArt +'</h1><p>' + extractArt + '</p></div></div></div>';
$('#display-result').append(contentHTML);
}
});
});
});
function Wiki(lang) {
this.lang = lang || "fr";
this.inuse = false;
}
Wiki.prototype.research = function(s, callback) {
if (this.inuse) {
console.error("Wiki est déjà en cours d'utilisation !");
} else {
this.inuse = true;
var r = new XMLHttpRequest();
r.onload = function() {
Wiki.prototype.inuse = false;
var j = JSON.parse(r.responseText);
callback(j);
}
r.open('GET', "https://" + this.lang + ".wikipedia.org/w/api.php?%20action=opensearch&format=json&origin=*&profile=normal&search=" + encodeURIComponent(s));
r.send();
}
}
var c = new Wiki();
c.research("Victor Hugo", function(result) {
console.log(result);
});
//EXEMPLE
var c = new Wiki("en");
c.research("Victor Hugo", function(result) {
console.log(result);
}

Jquery list passes values null in controller side [duplicate]

I want to pass list through AJAX. How can I do this and assign value on runtime. I am doing it, but it pass null value. Here is my code.
JQuery:
for (var i = 0; i < 5; i++) {
aabc += { id: i, color: 'Level' + i } + ",";
}
var str2 = aabc.replace(/,$/, " ")
JSONString3 = [str2];
$.ajax({
url: '#Url.Action("test123", "ConfigurableTradeLane")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(JSONString3),
success: function (data) {
//alert("success");
},
error: function (jqXHR, exception) {
alert('Error message.');
}
});
Controller:
public void test123(List<TradelaneDetailViewModel> viewmodel)
{
//nothing
}
It send "item value is null". Please help me.
Assuming TradelaneDetailViewModel contains properties id and color, then the script needs to be
var items = [];
for (var i = 0; i < 5; i++) {
items.push({ id: i, color: 'Level' + i });
}
$.ajax({
url: '#Url.Action("test123", "ConfigurableTradeLane")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ viewmodel: items }),
success: function (data) {
//alert("success");
},
error: function (jqXHR, exception) {
alert('Error message.');
}
});

Fill Variable with Web Service Results

I have a javascript function that is executed onClick via jquery. Within this function I am calling a Web Service "getTestConnection" which returns a True or False and I have confirmed it is working but keeps returning variable undefined.
$("#btnNext2").click(function() {
var postData = {}; {
postData['user'] = user;
postData['password'] = password;
postData['serviceurl'] = serviceurl;
postData['datasource'] = datasource;
};
//Converts object to string and formats to JSON
var json = JSON.stringify(postData);
//connTest keeps getting returned as 'Undefined'
var connTest = getTestConnection(json);
});
< script type = "text/javascript" >
function getDocType(json, rowcount) {
$.ajax({
type: "POST",
url: "http://localhost:64580/Web_Services/WebServiceLibrary.asmx/GetDocTypes",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
//*****************************************************************************
//This is being called immediately after getTestConnection is executed
//******************************************************************************
for (i = 0; i < data.d.length; i++) {
$('#SelectDocType' + rowcount + '')
.append($("<option></option>")
.attr("value", data.d[i].docTypeID)
.text(data.d[i].docTypeName));
}
var firstDocTypeID = data.d[0].docTypeID;
var jsonUnstringify = JSON.parse(json);
var postDataNew = {}; {
postDataNew['user'] = jsonUnstringify.user;
postDataNew['password'] = jsonUnstringify.password;
postDataNew['serviceurl'] = jsonUnstringify.serviceurl;
postDataNew['datasource'] = jsonUnstringify.datasource;
postDataNew['docTypeID'] = firstDocTypeID;
};
var jsonnew = JSON.stringify(postDataNew);
getKeywords(jsonnew, rowcount);
},
error: function(data) {
alert("***********Error***********" + data.responseText);
},
failure: function(data) {
alert("***********Failure***********" + data.responseText);
}
});
//Test Connection Web Service
function getTestConnection(json) {
$.ajax({
type: "POST",
url: "http://localhost:64580/Web_Services/WebServiceLibrary.asmx/TestConnection",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
if (data.d == 'True') {
return true;
} else {
return false;
}
},
error: function(data) {
alert("***********Error***********" + data.responseText);
},
failure: function(data) {
alert("***********Failure***********" + data.responseText);
}
});
}
< /script>
You have multiples errors:
You have a <script type = "text/javascript"> tag inside another <script> tag
You define a new function inside another function:
function getDocType(json, rowcount) {
$.ajax({
.....
});
function getTestConnection(json) {
....
}
}
which should be
function getDocType(json, rowcount) {
$.ajax({
.....
});
}
function getTestConnection(json) {
....
}
You forgot to get returned data from the AJAX call in your getTestConnection function :
$.ajax({
type: "POST",
url: "http://localhost...",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
if (data.d == 'True') {
return true;
} else {
return false;
}
},
error: function(data) {
....
}
});

Send extra parameters with ajax chosen

I'm currently using the chosen JQuery plugin :
http://harvesthq.github.io/chosen/
with this complement (to add an Ajax request) :
https://github.com/meltingice/ajax-chosen
I would like to know if anyone has ever been able to send extra parameters to the ajax function.
For now it only sends the letters in the input, but I would like to send an extra id.
Here's what i'm doing:
$("#mySelect").ajaxChosen({
minTermLength: 2,
type: "GET",
url: "/Orders/ajax_getBundleItems",
dataType: "json",
error: onItemChosenFail
},
function (data)
{
var terms = {};
$.each(data, function (i, val) {
terms[i] = val;
});
return terms;
});
I'm using the CakePHP Framework, here's my ajax function:
public function ajax_getBundleItems($term = null) {
$this->layout = false;
echo "<pre>";
var_dump($this->request->data);
var_dump($this->params['url']['term']);
echo "</pre>";
}
$this->params['url']['term'] gives me the letters in the input, and I would like $this->request->data to be an id.
Regards
you can pass it in url parameter like this:
var id = 123;
$("#mySelect").ajaxChosen({
minTermLength: 2,
type: "GET",
url: "/Orders/ajax_getBundleItems?Id="+id,
dataType: "json",
error: onItemChosenFail
},
function (data)
{
var terms = {};
$.each(data, function (i, val) {
terms[i] = val;
});
return terms;
});
or
var MyId = 23;
$("#mySelect").ajaxChosen({
minTermLength: 2,
type: "GET",
url: "/Orders/ajax_getBundleItems",
dataType: "json",
data: { id:MyId },
error: onItemChosenFail
},
function (data)
{
var terms = {};
$.each(data, function (i, val) {
terms[i] = val;
});
return terms;
});
you can pass here you Id from some variable
This is the actual answer, using the BeforeSend option:
$('select[name=element_id]', '#f-load-tc').ajaxChosen({
type: 'GET',
url: 'dynamic_url',
dataType: 'json',
afterTypeDelay: 300,
allow_single_deselect: true,
no_results_text: "No results matched",
beforeSend: function(xhr, opts) {
opts.url += '&category_id='+$category.val();
},
},
function (data) {
console.log(data);
var terms = {};
$.each(data, function (i, val) {
terms[i] = val;
});
return terms;
});

jQuery $.ajax(), pass success data into separate function

I am using the jQuery $.ajax() function. I have put this into a parent function, which passes some values into the ajax function. What I would like to do, is have a user defined callback function, which gets the data param passed in from the ajax success function.
Here is what I was thinking would work, but it is not:
testFunc = function(str, callback) {
// Send our params
var data = 'some data to send';
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: data,
success: callback
});
}
Then I want to be able to call that function, and pass in my custom function so that I can use the success functions data from inside that function:
testFunc('my string data', function(data){
alert(data);
});
I am wanting this to be the same as:
testFunc = function(str, callback) {
// Send our params
var data = 'some data to send';
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: data,
success: function(data) {
alert(data);
}
});
}
Works fine for me:
<script src="/jquery.js"></script>
<script>
var callback = function(data, textStatus, xhr)
{
alert(data + "\t" + textStatus);
}
var test = function(str, cb) {
var data = 'Input values';
$.ajax({
type: 'post',
url: 'http://www.mydomain.com/ajaxscript',
data: data,
success: cb
});
}
test('Hello, world', callback);
</script>
You can use this keyword to access custom data, passed to $.ajax() function:
$.ajax({
// ... // --> put ajax configuration parameters here
yourCustomData: {param1: 'any value', time: '1h24'}, // put your custom key/value pair here
success: successHandler
});
function successHandler(data, textStatus, jqXHR) {
alert(this.yourCustomData.param1); // shows "any value"
console.log(this.yourCustomData.time);
}
this is how I do it
function run_ajax(obj) {
$.ajax({
type:"POST",
url: prefix,
data: obj.pdata,
dataType: 'json',
error: function(data) {
//do error stuff
},
success: function(data) {
if(obj.func){
obj.func(data);
}
}
});
}
alert_func(data){
//do what you want with data
}
var obj= {};
obj.pdata = {sumbit:"somevalue"}; // post variable data
obj.func = alert_func;
run_ajax(obj);
In the first code block, you're never using the str parameter. Did you mean to say the following?
testFunc = function(str, callback) {
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: str,
success: callback
});
}
I believe your problem is that you are passing testFunct a string, and not a function object, (is that even possible?)
Although I am not 100% sure what you want (probably my brain is slow today), here is an example of a similar use to what you describe:
function GetProcedureById(procedureId)
{
var includeMaster = true;
pString = '{"procedureId":"' + procedureId.toString() + '","includeMaster":"' + includeMaster.toString() + '"}';
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: pString,
datatype: "json",
dataFilter: function(data)
{
var msg;
if (typeof (JSON) !== 'undefined' &&
typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
url: "webservice/ProcedureCodesService.asmx/GetProcedureById",
success: function(msg)
{
LoadProcedure(msg);
},
failure: function(msg)
{
// $("#sometextplace").text("Procedure did not load");
}
});
};
/* build the Procedure option list */
function LoadProcedure(jdata)
{
if (jdata.length < 10)
{
$("select#cptIcdProcedureSelect").attr('size', jdata.length);
}
else
{
$("select#cptIcdProcedureSelect").attr('size', '10');
};
var options = '';
for (var i = 0; i < jdata.length; i++)
{
options += '<option value="' + jdata[i].Description + '">' + jdata[i].Description + ' (' + jdata[i].ProcedureCode + ')' + '</option>';
};
$("select#cptIcdProcedureSelect").html(options);
};

Categories

Resources