Pass Ajax variable value as response data name - ajax

Please I am trying to pass textbox value as Ajax response data name. But its not working. Is there anyway to achieve it ?
I want to pass var grp_id = $('#group_id').val(); variable into ajax response name $("#freight").val(data.grp_id); the sample values of grp_id will be Short
I want like var grp_id = Short; and in response $("#freight").val(data.Short);
$(document).on('change','#product_id',function () {
var prod_id=$(this).val();
var a=$(this).parent();
var grp_id = $('#group_id').val();
// console.log(dest_id);
$.ajax({
type:'get',
url:'{!!URL::to('findPrice')!!}',
data:{'prod_id':prod_id,'grp_id':grp_id},
dataType:'json',//return data will be json
success:function(data){
// console.log("title");
// console.log(data.title);
$("#freight").val(data.grp_id);
},
error:function(){
}
});
});

$(document).on('change','#product_id',function () {
var prod_id=$(this).val();
var a=$(this).parent();
var grp_id = $('#group_id').val();
$.ajax({
type:'get',
url:'{!!URL::to('findPrice')!!}',
data:{'prod_id':prod_id,'grp_id':grp_id},
dataType:'json',//return data will be json
success:function(data){
$("#freight").val(data[grp_id]);
},
error:function(){
}
});
});
$("#freight").val(data[grp_id]); should do the trick this will return the value of data.short if grp_id = "short". What you are doing is on the data object looking for a grp_id key that most likely does not exist and is returning undefined.

Related

Is there a way to show "Loading data.." option in Rally Grid(ext JS) while making the Ajax request to load the data?

I am trying to set the message to "Data Loading.." whenever the data is loading in the grid. It is working fine if I don't make an Ajax call. But, when I try to make Ajax Request, It is not showing up the message "Loading data..", when it is taking time to load the data. Can someone please try to help me with this.. Thanks in Advance.
_loadData: function(x){
var that = this;
if(this.project!=undefined) {
this.setLoading("Loading data..");
this.projectObjectID = this.project.value.split("/project/");
var that = this;
this._ajaxCall().then( function(content) {
console.log("assigned then:",content,this.pendingProjects, content.data);
that._createGrid(content);
})
}
},
_ajaxCall: function(){
var deferred = Ext.create('Deft.Deferred');
console.log("the project object ID is:",this.projectObjectID[1]);
var that = this;
console.log("User Reference:",that.userref,this.curLen);
var userObjID = that.userref.split("/user/");
Ext.Ajax.request({
url: 'https://rally1.rallydev.com/slm/webservice/v2.0/project/'+this.projectObjectID[1]+'/projectusers?fetch=true&start=1&pagesize=2000',
method: 'GET',
async: false,
headers:
{
'Content-Type': 'application/json'
},
success: function (response) {
console.log("entered the response:",response);
var jsonData = Ext.decode(response.responseText);
console.log("jsonData:",jsonData);
var blankdata = '';
var resultMessage = jsonData.QueryResult.Results;
console.log("entered the response:",resultMessage.length);
this.CurrentLength = resultMessage.length;
this.testCaseStore = Ext.create('Rally.data.custom.Store', {
data:resultMessage
});
this.pendingProjects = resultMessage.length
console.log("this testcase store:",resultMessage);
_.each(resultMessage, function (data) {
var objID = data.ObjectID;
var column1 = data.Permission;
console.log("this result message:",column1);
if(userObjID[1]==objID) {
console.log("obj id 1 is:",objID);
console.log("User Reference 2:",userObjID[1]);
if (data.Permission != 'Editor') {
deferred.resolve(this.testCaseStore);
}else{
this.testCaseStore = Ext.create('Rally.data.custom.Store', {
data:blankdata
});
deferred.resolve(this.testCaseStore);
}
}
},this)
},
failure: function (response) {
deferred.reject(response.status);
Ext.Msg.alert('Status', 'Request Failed.');
}
});
return deferred;
},
The main issue comes from your Ajax request which is using
async:false
This is blocking the javascript (unique) thread.
Consider removing it if possible. Note that there is no guarantee XMLHttpRequest synchronous requests will be supported in the future.
You'll also have to add in your success and failure callbacks:
that.setLoading(false);

How do I return the response from an ajax call to store in a variable?

I would like to store a response result from an ajax call. This is because the ajax is the main API call used by several functions to extract information from an API.
I call callAPI function more than 8 times in my app.
Of course, I can duplicate the function callAPI 8 times to properly get information but this is not cool way to code.
var result = callAPI("GET",url,'');
$('#status').val(result.success);
$('#output').val(result);
function callAPI(method_input, url_input, body_input){
var urli = url_input;
var datai = body_input;
var method = method_input;
$.ajax({
url: urli,
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("some header","some value");
},
type: method,
data: datai,
})
.done(function(data,status) {
console.log("success");
console.log(data);
return JSON.stringify(data);
})
.fail(function(data,status) {
console.log("error");
console.log(data);
return JSON.stringify(data);
});
}
I tried to store the return value using
var result = ajax(value);
but the result is empty
is there any way to store return value of a function to a variable?
EDIT
I Solved this problem by using callback function like below
function callbackResult(result){
$('#status').val(result.success);
$('#output').val(result);
}
function callAPI(method_input, url_input, body_input, callback){
var urli = url_input;
var datai = body_input;
var method = method_input;
$.ajax({
url: urli,
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("some header","some value");
},
type: method,
data: datai,
})
.done(function(data,status) {
console.log("success");
console.log(data);
return JSON.stringify(data);
callback(data);
})
.fail(function(data,status) {
console.log("error");
console.log(data);
return JSON.stringify(data);
callback(data);
});
}
This was my first function to use a callback function and now I know what the callback function is.
Thank you guys all.
You need 'async': false, so:
var result = $.ajax({
url: "https://api.github.com/users",
'async': false,
type: 'GET'
})
.done(function(data,status) {
console.log("success");
})
.fail(function(data,status) {
console.log("error");
});
console.log("result: " + result.responseText);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
A few things to note:
Instead of JSON.stringify() I think you want to use JSON.parse() to parse the JSON string that is probably been returned by your API.
You can use the $.ajax option dataType to automatically parse the JSON string into an object.
$.ajax() returns a promise which can be chained to add as many callbacks as needed.
A more elegant solution would be to return the promise from your function and chain your callbacks. Ex:
function callAPI(method_input, url_input, body_input) {
var urli = url_input;
var datai = body_input;
var method = method_input;
return $.ajax({
url: urli,
// Automatically parses JSON response
dataType: 'json',
beforeSend: function(xhrObj) {
xhrObj.setRequestHeader("some header", "some value");
},
type: method,
data: datai,
})
.done(function(data, status) {
console.log("success");
console.log(data);
})
.fail(function(data, status) {
console.log("error");
console.log(data);
});
}
callAPI('GET', '').then(function(result){
// Do something with my API result
});
If you plan on making all request at once, with this solution you can consider aggregating all the request into a single promise with $.when(). Ex:
$.when(
callAPI('GET', ''),
callAPI('GET', 'second'),
callAPI('GET', 'third')
).then(function(firstResult, secondResult, thirdResult){
// Do stuff with the result of all three requests
});

Ajax Infinite Recursive SQL Request using ID

I have an function that sends AJAX request. It's working fine. In my getimage.php, I'm getting 1 row at a time base on ID from 0 to last row of ID. on return, var counter is set to ID value. It all works fine. Only I want the counter to reset back to 0 after my request reaches the last row of table so that my ajax request will run infinitely. Please anyone can show me a simple solution.
var lastsrc = null;
var counter = 0;
var delay = 0;
function changeimage(){
$.ajax({
url: 'getimage.php',
type: 'post',
data: {
iddata : counter
},
dataType: 'json',
success: function(data){
var id=data['id'];
var title=data['title'];
var path=data['path'];
var s_d=data['start_date'];
var e_d=data['expiration_date'];
var duration=data['duration'];
var site=data['site'];
alert(id);
counter = id
setTimeout(changeimage, 1000);
}
});
};
changeimage()

Alert an array value that results from an AJAX call

I am having some difficulty trying to alert a value which is the result of an ajax call. The code below is working to the extent that grid.onClick will alert the value of row, but for the life of me I cannot figure out how to alert the value of latitude and/or longitude.
function showGridSalesResult(){
var data = [];
var r_from = $('#min_val').val();
var r_to = $('#max_val').val();
var p_from = $('#from_year').val();
var p_to = $('#to_year').val();
var type = $('#sf3').val();
var municipality = $('#SaleCity').val();
$(document).ready(function(){
jqXHR = $.ajax({
url: sURL + "search/ajaxSearchResult",
type: "POST",
data: 'r_from='+r_from+'&r_to='+r_to+'&p_from='+p_from+'&p_to='+p_to+'&type='+type+'&up_limit='+up_limit+'&low_limit='+low_limit+'&municipality='+municipality,
dataType: 'json',
success: function(json){
$.each(json, function(i,row){
data[i] = {
address: row.Address,
municipality: row.Municipality,
geoencoded: row.geoencoded,
latitude: parseFloat(row.geolat),
longitude: parseFloat(row.geolong)
};
});
grid = new Slick.Grid("#myGridMap", data, columns, options);
grid.invalidate();
grid.render();
grid.resizeCanvas();
grid.onClick = function (e, row, cell){
alert(row); // THIS WORKS
alert(data[row].latitude); // THIS DOES NOT WORK
}
setMarkers(map, data);
}
});
});
}
Can someone please help me to figure out how I can alert the latitude and longitude values?
Checking the documentation :
https://github.com/mleibman/SlickGrid/wiki/Slick.Grid#wiki-getCellFromEvent
you should use :
var cell = grid.getCellFromEvent(e);
var latitude = data[cell.row].latitude;
alert(latitude);

Reploting a JQplot chart using ajax

I have been trying to solve this in different ways, but haven't make it work as expected, I feel it isn't so big deal (I really hope so) but my experience and skills with Ajax and jQuery are kind of limited that's why I am appealing to your expertise!
I am working on a chart similar to the one here http://www.jqplot.com/tests/data-renderers.php. but in my case the json file is generated depending on a value that the user choses from a select box. I am using 2 files and ajax calls to accomplish this:
-AnnualB.html is the file where the select box is located and the chart should be displayed.
-Index.php is the file where the query to the database is made (using the value obtained from the selectbox in AnnualB.html) and the json array is generated.
In AnnualB.html I use the GET method to retrieve the value from the selectbox and send it to Index.php, which generates the json data. Based on that json data the chart has to be created in AnnualB... Here is where my problem comes. The function to generate the chart is working fine and the call to send the select value and return the json is also working (have checked with Firebug), but I know am missing something (but don't know what yet) because I don't manage to pass the json data to the function that generates the chart.
My codes in AnnualB.html goes like this (abbreviating some irrelevant information with ...):
Function to generate the chart (Is working ok if the json data is passed)
function CreateGraph() {
$(document).ready(function(){
var ajaxDataRenderer = function(url, plot) {
var ret = null;
$.ajax({
async: false,
url: url,
dataType:'json',
success: function(data) {
ret = data; }
});
return ret; };
$.jqplot.config.enablePlugins = true;
var jsonurl = "./index.php";
var plotData = ajaxDataRenderer(jsonurl);
var series = ...
plot1 = $.jqplot('Chart1', series,{...}}
Ajax Call (PROBABLY WHERE MY MISTAKE/OMISSION IS)
function LoadGraph(int)
{
if (window.XMLHttpRequest)
{xmlhttp=new XMLHttpRequest();}
else
{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.open("GET","index.php?tasel="+int,true);
xmlhttp.send();
xmlhttp.onreadystatechange=function()
{
CreateGraph(int)
}
}
Select box
<select name="tasel" size="1" onchange="LoadGraph(this.value)">
<option value="">Select accounts type:</option>
<option value="3">Tuloslaskelma</option>
<option value="2">Tasevastattava</option>
<option value="1">Tasevastaava</option>
</select>
The related code in Index.php goes like this (Is working ok when the value of the select box (tasel) is passed)):
$tasel = $_REQUEST['tasel'];
if ($tasel == ...2)
{...}
.
.
.
echo "[",$selite, ",";// These 2 variables create the json array
echo $finaljson, "]";
Thanks in advance for your patience and help!
I realized the answer to this question was simpler than what I was expecting.
Instead of making the whole function LoadGraph(int) ajax call, I just needed to call the tasel value ?tasel="+int in the function to generate the chart like this (which is already doing an ajax call):
function CreateGraph() {
$(document).ready(function(){
var ajaxDataRenderer = function(url, plot) {
var ret = null;
$.ajax({
async: false,
url: url,
dataType:'json',
success: function(data) {
ret = data;
}
});
return ret;
};
$.jqplot.config.enablePlugins = true;
var jsonurl = "./index.php?tasel="+int;
var plotData = ajaxDataRenderer(jsonurl);
var series = ...
plot1 = $.jqplot('Chart1', series,{...}
}
var plot1 = undefined;
var plotOptions = undefined;
function CreateGraph() {
$.ajax({
async: false,
url: "./index.php",
dataType:'json',
success: function(data) {
var series = fn... // Convert your json Data to array
if(plot1 != undefined)
{
plot1.destroy();
}
plot1 = $.jqplot('Chart1', series, plotOptions);
}
});
}
$(function(){
$.jqplot.config.enablePlugins = true;
plotOptions = {...}; // jqPlot options
CreateGraph();
});
Hope this might help you..

Resources