AJAX Post failing despite data existing - javascript

I am trying to send some data to my server using an AJAX Post call. However, whenever I run the function containing the ajax call I get a server error. Here is my AJAX call (I am trying to send a string and put it inside json for the purposes of this call):
function sendFileName(){
data_to_send={"name": scriptName};
data_to_send=JSON.stringify(data_to_send);
$.ajax({
url: '/filename',
type: 'POST',
dataType: 'json',
data: data_to_send,
error: function(resp){
console.log("Oh no...");
console.log(scriptName);
console.log(resp);
},
success: function(resp){
console.log('Sent file name!');
console.log(resp);
}
});
}
When I log the scriptName I get it in the console, so the data exists. I'm assuming the issue has to do with the way in which I'm sending it?
Here is the server-side code as well, where when I log the req it shows up as undefined:
app.post("/filename", function(req,res) {
file = req.body.name;
console.log(file);
});
Would really appreciate any help I can get with this!

Related

Jquery: Probably a syntax Issue in ajax() method - Value not getting sent

I'm able to dump value of the variable message in console .
But im not able to send it off in POST Request.
AJAX call:
chat.throwmsg = function(message) {
if ($.trim(message).length != 0) {
console.log(message);
$.ajax({
url: 'ajax/chat.php',
type: 'post',
data: { method: 'throw', message: message} ,
success: function(data) {
chat.fetchmsgs();
$('textarea#entry').val('');
}
});
}
}
This maybe due to wrong syntax, but I've tried both single and double quotes, and combination as well .
With a wild assumption, you are not having any error messages in developer console and chat.php has a post handler forthese parameters
Since your data is JSON, please change the code as this way and have a try..
var temp={ method: 'throw', message: message};
var param=JSON.stringify(temp);
$.ajax({
url: 'ajax/chat.php',
type: 'post',
data: param ,
dataType: "json",
success: function(data) {
chat.fetchmsgs();
$('textarea#entry').val('');
}
});
after reviewing the code I could not find any issues that restrict the data to be sent along with ajax request,if you are having any syntax errors you should have been warned prior the request initialization, however I recommend you to check the request header in the network tab of browser console and see your sending data along with the request if it's there you probably need to check the code of getting the post data in your server-side implementations

$.AJAX Post not working in JS but works in Advanced Rest Client

I'm having an issue with my JavaScript being able to contact the HttpPost service. I can access the same signature using the "Advance Rest Client Application" for chrome. However when I run my code in Console in Chrome I am unable to reach the service. Any thoughts? What am I missing from the signature on one vs the other? Please let me know if you need any more information.
JS AJAX Request (Stuck in Pending status)
$.ajax({
type: 'POST',
url: 'http://local/r/GetSettings',
data: '[{"SourceId":7,"DataType":0},{"SourceId":5,"DataType":1}]',
dataType: "json",
success: function(data){
alert(data)
},
error : function (error) {
alert("Error: " + error);
console.log("ERROR. not working", error);
}
});
C# Service
[HttpPost]
public ActionResult GetSettings(List<Source> sources)
{
return new ContentResult
{
Content = "{}",
ContentType = "application/json"
};
}
Advanced Rest Client Application (Success in returning {})
http://local/r/GetSettings
Content-Type: application/x-www-form-urlencoded
Payload::: [{"SourceId":7,"DataType":0},{"SourceId":5,"DataType":1}]
Change your URL for ajax request
AppContextRootName: Your application context root
$.ajax({
type : 'POST',
url : '/AppContextRootName/GetSettings',
dataType : 'json'
});
Thanks for the answers. I found out my issue why the Ajax call was not executing. I found out you can execute a AJAX statement while paused in the debugger!!! So don't try! It will execute and return and object but it will show pending in the network. Once you unpause the actual call is executed. You should just use Alert("Hello world") in the success and error and you will see it come back once you unpause.

Call post on external Rest API with Ajax

I am new to angular, and I'm trying to make a call to a Rest API and get its response. My issue is that my JavaScript keeps getting stuck on the Ajax call. I'm not sure if it's the data I am sending or the syntax of the Ajax call. I tried to alert 'Hello world' and that worked, then I alerted the JSON array and that was formatted correctly, but when I do the Ajax post, I don't get any response at all.
Any insight would be nice, thank you.
test.html
<button onclick="myFunction()">Post it</button>
test.js
function myFunction() {
var postData = [{"logintype":"1","user":"Administrator","password":"12345","controlid":"999","host":"192.168.2.164"}
];
$.ajax({
url: '192.168.2.164/isapi/rip.dll/rest/session',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify( postData ),
success: function(){
alert('hello');
},
error: function(){
alert('error');
}
});
};
You have specified a relative URL, where I think you intended to specify an absolute URL. If the current page URL is http://localhost/myapp/, and you request 192.168.2.164/isapi/rip.dll/rest/session, that URL is resolved as http://localhost/myapp/192.168.2.164/isapi/rip.dll/rest/session.
If 192.168.2.164 is the ip address of the server you are trying to hit (and not a directory relative to your current path on your server), you will need to add // to the beginning of the URL to make it absolute (well, schema-relative at least):
$.ajax({
url: '//192.168.2.164/isapi/rip.dll/rest/session',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify( postData ),
success: function(){
alert('hello');
},
error: function(){
alert('error');
}
});
Your issue has nothing to do with angular. What I will refer you to is the angular docs description of how to do a POST request and a small example of the syntax taken from the docs.
Learn to use $http or something similar if you want to develop with angular. https://docs.angularjs.org/api/ng/service/$http
Small example:
// Simple POST request example (passing data) :
$http.post('/someUrl', {msg:'hello word!'}).
then(function(response) {
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

How to post data from DOM to nodejs via AJAX

I use POST method to send JSON data to the URL and I am utilizing from this data in order to render the page and I am rendering page via underscorejs. Is there any way to retrieve that data (in JSON format) and assigned them in another var in AJAX and send it as a data ?
I am trying to send data to the nodejs server in order to update Mongo DB. But there is no luck...
$(document).ready(function(){
$("#addContact").click(function(){
var responseArea = $('.actionArea');
$.ajax({
url: '/account/:id/added',
type: 'POST',
cache: false,
data: { contactId: this.model.get('_id') },
function onSuccess() {
$responseArea.text('Contact Added');
}, function onError() {
$responseArea.text('Could not add contact');
}
});
});
});
The error I am getting "Cannot call method 'get' of undefined"

jQuery $.getJSON not working

I am try to get a URL from a one server and using that URL to get contents of another server.
$.ajax({url : 'http://localhost:8080/geturl.jsp?A=1&B=2,C=3',
success : function (data)
{
alert(data);
$.getJSON(data, function (mydata)
{
alert(mydata);
});
},
error : function (data, status, xhr)
{
}
});
I know that we cannot make cross-domain requests in through ajax call, thats why i am using getJSON, i have the following problems
When i simply pass the data to the url part of getJSON (as shown in the code), the alert-box show the correct URL but no get request is being performed ( get requests were monitored from FireBug).
When a hard-code the data to be "http://www.google.com" then the get request is being performed but the no response comes, although the response headers comes and response code is 200 (but it was marked as RED in the Firebug (Dont know why :( )
When I tries to fetch a webpage host in localhost domain, then it is fetched correctly although the response was not JSON.
I have the following doubts
If the getJSON function accecpts only JSON objects as reponse then why no error came when perform above 3.
Whats the correct code to perform my the required functionality.
Suggestions to what happened in each case
Thanks in advance for the answers :)
The getJSON function can only be used across domains to fetch JSONP.
It does not magically evade any security restrictions.
http://api.jquery.com/jQuery.ajax/
This should be a working example for jsonp:
var request = jQuery.ajax(
{
url: "http://Your url",
success: function (data) { console.log('success!'); console.log(data); },
error: function (data) { console.log('error!'); console.log(data); },
dataType: "jsonp",
type: "GET",
data: { key: 'value' }
});

Categories

Resources