in my controller I've some json:
votes_controller.rb:
def create
...
vote_status = current_user.user_votes.pluck(:recipient_uid).include?(#user.uid)
render json: vote_status
end
I need to get vote_status in javascript file
votes.js:
jQuery(function($) {
$(".doWant").click( function () {
var status = vote_status.evalJSON();
var uid = $(this).parents("#dialog")[0];
var username = $(this).parents("#dialog")[0];
if(confirm("Are you sure?")) {
$.ajax({
url: '/votes' + "?uid=" + $(uid).attr("data-user-uid") + "&username=" + $(username).attr("data-user-username"),
type: 'POST',
success: function(data) {
console.log(data)
}
});
};
});
});
But there is an error Uncaught ReferenceError: vote_status is not defined. What am I doing wrong?
Thanks!
You're not defining this variable:
var status = vote_status.evalJSON();
You must define that variable.
It seems likely that you intended for that code to go into the success function, which returns the data from the ajax call as the first argument in that function:
success: function(data) {
console.log(data)
}
The vote_status is returned in success json callback, init the status there
$.ajax({
url: '/votes' + "?uid=" + $(uid).attr("data-user-uid") + "&username=" + $(username).attr("data-user-username"),
type: 'POST',
success: function(data) {
var status = JSON.parse(data);
}
});
Related
I'm trying to merge the results of two jQuery AJAX calls. I've looked at other similar questions here, but none of them seem to help. For each ajax call (2 of them), I have a success that calls the function createStatusView and it passes it the results. The good part is that the results work for both of the AJAX calls. The bad news is that my $.when call returns undefined for both res1 and res2, which then send undefined for the results to my createStatusView. So, I really don't want to invoke the createStatusView for both of the AJAX calls, only the $.when. Any recommendations would be greatly appreciated.
function getSpecifiedList(listName, userId){
var url = SP.PageContextInfo.get_webServerRelativeUrl() + "/_vti_bin/listdata.svc/" + listName;
var url1 = url + "?$select=ParentOrg,ORG,URL,Site_Status&$inlinecount=allpages";
var call1 = $.ajax({
url: url1,
type: "GET",
headers:{"accept":"application/json;odata=verbose",
},
success: function(results){createStatusView(results, listName);},
error:function(error){
console.log("Error in getting List: " + listName);
$(_options.container).html("Error retrieving your " + listName + ". " +
SP.PageContextInfo.get_webServerRelativeUrl());
}
});
var url2 = url + "?$select=ParentOrg,ORG,URL,Site_Status&$inlinecount=allpages&$skiptoken=1000";
var call2 = $.ajax({
url: url2,
type: "GET",
headers:{"accept":"application/json;odata=verbose",
},
success: function(results){createStatusView(results, listName);},
error:function(error){
console.log("Error in getting List: " + listName);
$(_options.container).html("Error retrieving your " + listName + ". " +
SP.PageContextInfo.get_webServerRelativeUrl());
}
});
//the res1 and res2 come back undefined
//call1 and call2 are objects as shown in F12 debug
$.when(call1,call2).done(function(res1,res2){
var results = res1[0].d.results.concat(res2[0].d.results);
createStatusView(results,listName);
});
}
Try adding some object detection to your $.when callback function. It will keep the undefined values out of your list.
$.when(call1,call2).done(function(res1,res2){
var results = res1[0].d.results.concat(res2[0].d.results);
if (results) {
createStatusView(results,listName);
}
});
Another example:
$.when(call1,call2).done(function(res1,res2){
if (!res1 && !res2) return;
var results = res1[0].d.results.concat(res2[0].d.results);
if (results) {
createStatusView(results,listName);
}
});
Which is the same as this:
$.when(call1,call2).done(function(res1,res2){
if (res1 && res2) {
var results = res1[0].d.results.concat(res2[0].d.results);
if (results) {
createStatusView(results,listName);
}
}
});
Have you tried moving the ajax calls to separate functions then calling those from the when?
function getSpecifiedList(listName, userId){
$.when(call1(listName),call2(listName)).then(function(res1,res2){
var results = res1[0].d.results.concat(res2[0].d.results);
createStatusView(results,listName);
});
}
function call1(listName){
var url = SP.PageContextInfo.get_webServerRelativeUrl() + "/_vti_bin/listdata.svc/" + listName;
var url1 = url + "?$select=ParentOrg,ORG,URL,Site_Status&$inlinecount=allpages";
return $.ajax({
url: url1,
type: "GET",
headers:{
"accept":"application/json;odata=verbose",
}
});
};
function call2(listName){
var url = SP.PageContextInfo.get_webServerRelativeUrl() + "/_vti_bin/listdata.svc/" + listName;
var url2 = url + "?$select=ParentOrg,ORG,URL,Site_Status&$inlinecount=allpages&$skiptoken=1000";
return $.ajax({
url: url2,
type: "GET",
headers:{
"accept":"application/json;odata=verbose",
}
});
};
This is jQuery code snippet is not getting valid data through AJAX and keeps updating data in divs as undefined. I don't know what the problem is.
function success(data) {
alert(data.amount);
$('#summary').html(data.count + "|" + data.amount);
};
$(document).ready(function () {
$("#button1").click(function (evt) {
evt.preventDefault();
var $form = $("#form1");
$.ajax({
type: $form.prop('method'),
url: $form.prop('action'),
data: $form.serialize() ,
datatype: "json",
tradition: true,
success: function(data) {
success(data);
}
});
});
});
If I modify following success function to simply load a new page that shows the correct results that Action returns
function success(data) {
$('#summary').html(data);
};
This is the controller action code snippet that receives the form fields data (id and quantity) from the view and returns count and amount:
public JsonResult AddtoCartDt(string id,string quantity)
{
int id2 = int.Parse(id);
Product pro = Data.Products.Single(c => c.Id == id2);
var cart = ShoppingCart_BusinessLayer.GetCart(this.HttpContext);
int l = int.Parse(quantity);
for (int i = 0; i < l; i++)
{
cart.AddToCart(pro);
}
var Cart = ShoppingCart_BusinessLayer.GetCart(this.HttpContext);
cartSummary summ = new cartSummary()
{
amount = Cart.GetTotal(),
count = Cart.GetCount()
};
return Json(summ, JsonRequestBehavior.AllowGet);
}
Your code looks fine, but you should add some debug statements to check the response.
For starters, you could pass the success method directly as your ajax success handler, and add an error handler to log out any error:
$.ajax({
type: $form.prop('method'),
url: $form.prop('action'),
data: $form.serialize() ,
datatype: "json",
traditional: true,
// no need for the function()...
success: success,
error: console.log
});
// Alternatively, you could chain it:
$.ajax(/*...*/).done(success).fail(console.log);
That will call pass the JSON response as your success method parameter.
Then, try to add a console.log() statement to debug the response in the console:
function success(data) {
console.log(data);
$('#summary').html(data.count + "|" + data.amount);
};
Edit
Check the tradition parameters in your ajax call. In the doc it's called traditional.
Also, check the route name and http method in your controler.
You may want to add something like this in your controller:
[Route("~/myroute"), HttpPost]
public JsonResult AddtoCartDt(string id,string quantity)
{
/*
*/
}
I've got one ajax call after two previous. I need to pass results of those calls to the new one, so I do the following
$.when(getRespData(), getAxisComponents()).done(function (respData, axisData) {
var a = respData; //everything is ok
var b = axisData; //everything is ok
$.ajax({
dataType: "json",
url: '/rest/visualization/' + taskName + '/workload?runName=' + runName+ '&type=' + 'VAL',
success: (function (data) {
var c = respData; //everything is ok
var d = axisData; // Uncaught ReferenceError: axisData is not defined
}
but I've got Uncaught ReferenceError when I try to get my axisData inside my new ajax call, although operations with respData are ok.
My first 2 ajax calls look like
function getRespData() {
return $.ajax({
dataType: "json",
url: '/rest/visualization/' + taskName + '/workload?runName=' + runName + '&type=' + 'RESP',
success: (function (data) {
return data;
})
});
}
function getAxisComponents() {
return $.ajax({
dataType: "json",
url: '/rest/visualization/' + taskName + '/workload/axis?runName=' + runName,
success: (function (data) {
return data;
})
});
}
where runName, type, taskName are some params of function which contains all these ajax calls.
How can I fix this error, so that I would be able to access both respData and axisData ind my inner ajax call?
i solved it putting async false and declaring an array out of ajax call, like this
let array = [];
$.ajax({
url: path,
type: 'GET',
async: false,
dataType: 'json',
success: function(response){
array = response;
}
});
return array;
You're calling data in your success function but data isn't set before this.
In a jQuery .ajax function, data is the data that is sent to the server when performing the Ajax request, which is why you may think it is lost (because it was never there).
Consider the following:
$.ajax({
data: {"data": data},
dataType: "json",
url: 'yourURl',
success: function(data){
return data;
}
I am making a web application using Jersey and JQuery for client-side.
I have the following URL that returns a JSON string:
http://localhost:8080/messenger/webapi/messages/1
returns:
{"author":"Joe","created":"2015-07-28T22:33:34.667","id":1,"message":"Hello World"}
when typed into the browser.
Now I am attempting to get this data client-side using the following JQuery functions:
var rootURL = "http://localhost:8080/messenger/webapi/messages";
$(function() {
$('#btnRegister').click(function() {
var username = $('#username').val();
addMessage();
});
function addMessage() {
var url = rootURL;
$.ajax({
type: 'GET',
url: rootURL +"/1",
dataType: "json", // data type of response
success: (function(data) {
var obj = jQuery.parseJSON(data);
alert('ID: ' + obj.id);
})
});
}
});
EDIT: When the "btnRegister" is pressed nothing is displayed at all
which just doesn't make sense to me.
There is some unwanted $ wrapping in success callback function, also there is no need to parse the response as you set dataType:'json'. For better understanding of $.ajax() read documentation here.
$(function() {
$('#btnRegister').click(function() {
var username = $('#username').val();
addMessage();
});
function addMessage() {
var url = rootURL;
$.ajax({
type: 'GET',
url: rootURL + "/1",
dataType: "json", // data type of response
success: function(data) {
//----^----------- remove the $ sign
alert('ID: ' + data);
}
});
}
});
You can access the value using obj.prop or obj['prop']
var obj= {"author":"Joe","created":"2015-07-28T22:33:34.667","id":1,"message":"Hello World"};
alert(obj.author);
alert(obj['author']);
I am using the sample code (slightly modified) to implement a JSONP adapter found here: http://coenraets.org/blog/2013/04/building-pluggable-and-mock-data-adapters-for-web-and-phonegap-applications/
My modified in-memory adapter works, but when I try to change from using the mock data, to a JSONP data object from a remote server, it doesn't work. Below is my memory adapter:
var JSONPAdapter = function() {
this.initialize = function(data) {
var deferred = $.Deferred();
url = data;
deferred.resolve();
return deferred.promise();
}
this.findById = function(id) {
return $.ajax({url: url + "/" + id, dataType: "jsonp"});
}
this.findByName = function(searchKey) {
return $.ajax(
{
url: url + "?Name=" + searchKey,
dataType: "jsonp",
success: function (data) { },
error: function (XHR, textStatus, errorThrown) { alert("error: " + errorThrown + '\nurl: ' + url + "?Name=" + searchKey);
}
});
}
this.getAll = function getAll() {
return $.ajax({ url: url, dataType: "jsonp" });
}
var url;
}
You don't need the /callback=? appended to the end of the url. This is taken care of automatically because the dataType is set to 'jsonp'.
I suspect this is due to the scope of your JSONData variable.
It is not initialised correctly if there is an error within the getJSONData() call. Try declaring the JSONData variable before the function is defined.