I'm trying to POST a comment to a using AJAX in Rails (without using remote: true and am having difficulty understanding why my myJSON variable is returning as undefined, when data is returning as expected.
Here's my code:
function submitViaAjax() {
$("#new_comment_button").on("click", function (e) {
e.preventDefault();
url = $(this.form).attr('action')
data = {
'comment': {
'content': $("#comment_body").val()
}
};
var myJSON = JSON.stringify(data);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: url,
data: myJSON,
// headers: { 'Content-Type': 'application/json' },
success: function (response) {
var $ul = $("div.comments_section ul");
$ul.append(response)
}
}).done(function(response){
debugger
var $ul = $("div.comments_section ul");
$ul.append(response)
})
})
};
I can run var myJSON = JSON.stringify(data); in the browser console just fine, so I'm not sure why it's not doing anything in my code.
Any help would be appreciated.
I found out why I wasn't getting the response I expected. It's a jQuery function, but I was using JavaScript variable declaration to define myJSON.
In short, I need to remove var from var myJSON = JSON.stringify(data);
EDIT:
Implementing 'use strict'; within that function renders those variables undefined, which may mean that I was originally overwriting them - causing the 400 and/or 422 error.
EDIT 2:
I was getting the 422 error because my data object had a key of content when my param was looking for body.
Related
$(document).ready(function () {
$.ajax({
url: "/file_lines",
type: 'GET',
// contentType: 'application/json', // format of Data to be sent to the server
// data: 'json',//Data to be sent to the server
dataType: 'text', //The type of data that you're expecting back from the server.
success: function (lines) {
document.getElementById("tmp").innerHTML = lines
**console.log(document.getElementById("tmp").innerHTML)**
},
error: function (){
alert("get debug log's lines failed");
return false;
}
});
})
// console.log($('#tmp').html())
**var num = document.getElementById("tmp").innerHTML
console.log(num)**
I am so confuse that why I can get innerHtml value of "tmp" in the $(document).ready() but can not get this value outside $(document).ready()! I thought DOM object should be global. So I am quite confuse about this result. Could somebody help me?
I am trying to fetch data from local network IP. It works fine if I am in the local network. It fails when accessed from outside, which is understandable. But the jquery error block is not getting executed, it just breaks the code and the page is stuck forever. Here is the code:
var url = "http://10.0.0.1:8080/status";
$.ajax({
url: url,
dataType:"jsonp",
crossDomain: true,
data : {},
success: function(response){
var clientState = response.clientState;
$(".clientstate-input").val(clientState);
document.loginform.submit();
},
error: function(response){
console.error(response);
$(".clientstate-input").val("0");
document.loginform.submit();
}
});
Error:
Try converting it to use a Promise:
var url = "http://10.0.0.1:8080/status";
$.ajax({
url: url,
dataType:"jsonp",
crossDomain: true,
data : {}
})
.then(response => {
var clientState = response.clientState;
$(".clientstate-input").val(clientState);
document.loginform.submit();
})
.catch(response => {
console.error(response);
$(".clientstate-input").val("0");
document.loginform.submit();
});
The issue was because of using older version of jQuery. Updated the library and everything was working fine.
I am using Angular Js with JQuery in a noodles way. See my code below.
Code
app.controller('ClassController', function ($scope) {
$scope.ShowHideNoRecords = false;
var credentials = new Object();
credentials.SourceName = "###";
credentials.SourcePassword = "###";
credentials.UserName = "###";
credentials.UserPassword = "##";
credentials.SiteId = [-99];
var locationIds = [1];
var startDate = Date.today();
var endDate = startDate;
var dto = { credentials: credentials, startDate: startDate, endDate: endDate, locationId: locationIds };
$.ajax({
type: "POST",
url: 'MbApiConnector.asmx/GetAllClasses',
data: JSON.stringify(dto),
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (response) {
alert(response.d);
},
complete: function (msg) {
$scope.$apply(function () {
$scope.Classes = JSON.parse(JSON.parse(msg.responseText).d);
if ($scope.Classes.length > 0) {
$scope.checkin = function (id) {
dto = { credentials: credentials, classId: id };
$.ajax({
type: "POST",
url: 'MbApiConnector.asmx/Checkin',
data: JSON.stringify(dto),
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
complete: function (msg) {
alert(msg.responseText);
}
});
}
}
else {
$scope.ShowHideNoRecords = true;
}
});
}
});
});
Everything is working fine with this code. I knew its a bad idea mixing the two but my app was already developed in Jquery Ajax and we are upgrading with Angular JS but with lesser changes. So I came up with this solution.
Anyways, my issues is that jquery ajax success function is not get called. I am able to receive data from the webservice , but inside the complete method, as you can see in the code above.
Can you explain me why its behaving so?
May be Jquery fails to parse it as the result may not be in JSON format, try to find the error using error callback function. You could try with dataType : 'json'.
error: function (err) { alert(err) }
Basically I am trying to extract JSON returned from servlet in JavaScript. I have tested my servlet class already and it did returned some JSON so I guess I no need to post the code for that class. Here is my returned JSON format:
[{"mrtpopAmt":"7000","mrtpopX":"17854.99820","mrtpopY":"35056.35003"},{"mrtpopAmt":"6300","mrtpopX":"29798.58427","mrtpopY":"37036.56434"}]
And in my JavaScript, I am trying to extract mrtpopAmt, mrtpopX and mrtpopY as one object. Then I will add all object into an array:
function getAllMRTPop(time){
var jsonArray;
var Data = JSON.stringify({ time: time });
$.ajax({
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time="+ Data + "",
type: "GET",
data: Data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var parsed = JSON.parse(data.d);
console.log(data.d);
$.each(parsed, function (i, jsondata) {
var jsonObject;
jsonObject.put("mrtpopAmt", jsondata.mrtpopAmt);
jsonObject.put("mrtstationX", jsondata.mrtstationX);
jsonObject.put("mrtstationY", jsondata.mrtstationY);
alert(jsonObject);
jsonArray.push(jsonObject);
});;
},
error: function (request, state, errors) {
}
});
}
However, I am getting error message like Unexpected token: u at this line:
var parsed = JSON.parse(data.d);
My URL for the servlet contains two parameter, one is action and the other one is time:
http://localhost:8080/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time=8:00
So I wonder am I passing the parameter correctly by passing it in url and as well as data from the code above?
I wonder which part went wrong? Thanks in advance.
EDIT
So I have updated my JavaScript part to this:
function getAllMRTPop(time){
var jsonArray = [];
$.ajax({
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time=8:00",
type: "GET",
data: time,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
//var parsed = JSON.parse(data.d);
$.each(data, function (i, jsondata) {
var jsonObject;
console.log(mrtpopAmt);
jsonObject.put("mrtpopAmt", jsondata.mrtpopAmt);
jsonObject.put("mrtstationX", jsondata.mrtstationX);
jsonObject.put("mrtstationY", jsondata.mrtstationY);
jsonArray.push(jsonObject);
});;
},
error: function (request, state, errors) {
}
});
}
I tried to print out the mrtpopAmt and it did returned something. But there is an error message:
Cannot call method 'put' of undefined
Any ideas?
By specifying dataType: "json", jQuery already knows you will be getting a JSON response, there is no no need to do var parsed = JSON.parse(data.d)
Just do:
var parsed = data.d
Edit:
function getAllMRTPop(time){
var jsonArray = [];
$.ajax({
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time=8:00",
type: "GET",
data: time,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
$.each(data, function (i, jsondata) {
var jsonObject = {};
jsonObject.mrtpopAmt = jsondata.mrtpopAmt;
jsonObject.mrtstationX = jsondata.mrtstationX;
jsonObject.mrtstationY = jsondata.mrtstationY;
jsonArray.push(jsonObject);
});;
},
error: function (request, state, errors) {
}
});
}
I think what is happening is that data.d is undefined, so you are getting the odd message about unexpected u.
Try this instead:
var parsed = JSON.parse(data);
Edit And I think you are probably not formatting your request right:
var Data = JSON.stringify({ time: time });
$.ajax({
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time="+ Data + "",
Seems to me that would make the final bit: &time={"time":"time"}, so you probably want to look at how you construct Data. Maybe just pass time directly?
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time="+ time + "",
I'm trying to understand how to build a JSON object in JavaScript. This JSON object will get passed to a JQuery ajax call. Currently, I'm hard-coding my JSON and making my JQuery call as shown here:
$.ajax({
url: "/services/myService.svc/PostComment",
type: "POST",
contentType: "application/json; charset=utf-8",
data: '{"comments":"test","priority":"1"}',
dataType: "json",
success: function (res) {
alert("Thank you!");
},
error: function (req, msg, obj) {
alert("There was an error");
}
});
This approach works. But, I need to dynamically build my JSON and pass it onto the JQuery call. However, I cannot figure out how to dynamically build the JSON object. Currently, I'm trying the following without any luck:
var comments = $("#commentText").val();
var priority = $("#priority").val();
var json = { "comments":comments,"priority":priority };
$.ajax({
url: "/services/myService.svc/PostComment",
type: "POST",
contentType: "application/json; charset=utf-8",
data: json,
dataType: "json",
success: function (res) {
alert("Thank you!");
},
error: function (req, msg, obj) {
alert("There was an error");
}
});
Can someone please tell me what I am doing wrong? I noticed that with the second version, my service is not even getting reached.
Thank you
You may want to look at the JSON JavaScript library. It has a stringify() function which I think will do exactly what you need.
Your code:
var comments = $("#commentText").val();
var priority = $("#priority").val();
var json = { "comments":comments,"priority":priority };
Take out the quotes ( line 3 ):
var comments = $("#commentText").val();
var priority = $("#priority").val();
var json = { comments: comments, priority: priority };
Remove the quotes
data: '{"comments":"test","priority":"1"}',
becomes
data: {"comments":"test","priority":"1"},
JSONs are objects not strings.
This should work
var json = { comments: "comments",priority: "priority" };
this works for me.
var json = "{ 'comments': '" + *comments* +"','priority:' '" + *priority* +"' }";
italics are the variables.