POST method with ajax and express - ajax

I want to send and object model to my server
$.getJSON(request, function(data){
$.ajax({
type: "POST",
data: {data},
contentType: "application/json",
url: "/movie",
success: function(){
console.log("Movie data send");
}
});
express:
app.post("/movie", function(req, res){
console.log(req.body.data);
});
The error i'm getting on the console browser is:
POST http://localhost:8888/movie 400 (Bad Request)
send # jquery.min.js:4
ajax # jquery.min.js:4
(anonymous) # session:47
i # jquery.min.js:2
fireWith # jquery.min.js:2
A # jquery.min.js:4
(anonymous) # jquery.min.js:4
and in my server console:
SyntaxError: Unexpected token d
What am I doing wrong? I checked other similar questions but I don't know how to apply their solutions to my case
EDIT: I changed the code, now it looks like this:
var movie = JSON.stringify(data);
$.ajax({
type: "POST",
data: movie,
dataType: "json",
url: "/session/movie",
success: function(){
console.log("Movie data send");
}
});
server:
app.post("/session/movie", function(req, res){
console.log(req.body.movie);
});
And now I'm getting undefined on the server console ...

Related

django ajax MultiValueDictKeyError

I am receiving this error:
MultiValueDictKeyError at /orders/ajax/add_order_line
"'cart'"
Here is my script
var cart = {
0: {
id: "1",
quantity: 50
}
}
$.ajax({
url: myURL,
type: "post",
data: {cart: cart},
success: function() {},
error: function(){}
});
Meanwhile in my django views, the error was found in this line:
def something(request):
cart = request.POST['cart']
Use get method of multivaluedict
request.POST.get('cart')
Your data is a nested array, so you can't send it using the default default application/x-www-form-urlencoded content type.
You can send the data as json:
$.ajax({
url: myURL,
type: "post",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({cart: cart}),
success: function() {},
error: function(){}
});
Then in your view, you have to load the json string from request.body instead of using request.POST (which is for form-encoded data only).
import json
def my_view(reqest):
data = json.loads(request.body.decode('utf-8'))
cart = data.get('cart')

jquery ajax success not working

I got simple ajax call i could not get why it is not running success method despite the fact that chrome developer tools show that it is getting the response for the request.
$( document ).ready(function() {
var url_API="http://moviesapi.herokuapp.com/cinemas/find/"+"PL15RH";
$.ajax({
type: 'GET',
url: url_API,
dataType: "jsonp",
crossDomain:true,
success: function (response) {
alert(1);
}
});
});
The API doesn't support jsonp. You're getting 500 (Internal Server Error).
It does support JSON, but you're getting the classic No 'Access-Control-Allow-Origin' header is present on the requested resource CORS error. You need to explicitly send the Access-Control-Allow-Origin header on your heroku API:
Header property:
Access-Control-Allow-Origin: *
A more verbose solution: "No 'Access-Control-Allow-Origin' header is present on the requested resource"
try this:
jQuery(document).ready(function($) {
var url_API="http://moviesapi.herokuapp.com/cinemas/find/"+"PL15RH";
$.ajax({
type: 'GET',
url: url_API,
dataType: "json",
crossDomain:true,
success: function (response) {
alert(response);
}
});
});

Sneak out JSON data from failed JSONP AJAX call

When I make this AJAX call
var inputText = $('#job-search-field').val(); //for example "CSS"
$.ajax({
url: 'http://api.arbetsformedlingen.se/platsannons/matchning',
type: 'GET',
dataType: 'json',
crossDomain: true,
data: {nyckelord: inputText}, //searches arbetsformedlingen.se for jobs containing the keyword "CSS".
success: getAPIResponse,
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
}
I get this error in the console
"XMLHttpRequest cannot load http://api.arbetsformedlingen.se/platsannons/matchning?nyckelord=CSS. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin http://localhost is therefore not allowed access."
When I make this AJAX call (http://jsfiddle.net/MSCbP/)
var inputText = $('#job-search-field').val();
$.ajax({
url: 'http://api.arbetsformedlingen.se/platsannons/matchning',
type: 'GET',
dataType: 'jsonp', //jsonp, not json
crossDomain: true,
data: {nyckelord: inputText},
success: getAPIResponse,
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
}
I get this error in the console
"Uncaught SyntaxError: Unexpected token : "
The first error tells me I don't have permission to retrieve the data, right? Since I find no information on how to gain access to the API I'm very interested in getting the response from the second call, which seems to work. Although I get the console error, I see the json data I want in the Network>Response tab in Chrome's dev-tool.
I can't seem to get the JSON data from "success: function()", is there any other way to get it?
Thanks!

Ajax JSONP Express parseError from Safari Extension

First, I've read many posts here but haven't found the issue in my own code, including this one $.ajax and JSONP. ParseError and Uncaught SyntaxError: Unexpected token :
I'm building a Safari extension and need to post/get to my server and handle the response. Safari is throwing this error:
SyntaxError: Unexpected token ':'
and this message
"handle was not called"
where 'handle' is the callback in this Extension code:
var server="http://localhost:3001/api/login";
$.ajax({
type : "GET",
url : server,
data: {"something" : "else"}
dataType: 'jsonp',
jsonp:false,
jsonpCallback: 'handle',
success: function(data, text){
var json = $.parseJSON(data);
console.log(json)
},
error: function (request, status, error) {
console.log(error );
}
});
and the Express.js (2.5.5) code is:
//in the config
app.set( "jsonp callback", true )
app.all('/', function(req, res, next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.get('/api/login', function(req, res){
res.json(
{
"success": {"that":"this"}
}
);
});
NOTES: I've tried res.jsonp, setting content types, etc, with same response. I've learned a TON about CORS and Ajax in the process, but my eyes are clearly bleary. Clicking my heels three times hasn't helped either.
Clues? Thanks!
By setting dataType: 'jsonp', it will already parse the JSON for you. jsonp: true is incorrect. This combo should work:
JSONP
$.ajax({
url : "http://localhost:3001/api/login",
data: {"something" : "else"},
dataType: 'jsonp',
success: function(data){
// It is already an object, don't parse it again.
console.log(data)
},
error: function (request, status, error) {
console.log(error );
}
});
with
app.get('/api/login', function(req, res){
res.jsonp({
"success": {"that":"this"}
});
});
// Remove this:
app.set( "jsonp callback", true )
CORS browsers and JSON:
$.ajax({
url : "http://localhost:3001/api/login",
data: {"something" : "else"},
dataType: 'json',
success: function(data){
// It is already an object, don't parse it again.
console.log(data)
},
error: function (request, status, error) {
console.log(error );
}
});
and
// This is 'app.use', not 'app.all'.
app.use('/', function(req, res, next){
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
});
app.get('/api/login', function(req, res){
res.json({
"success": {"that":"this"}
});
});

JQuery Ajax call

I have a url like:
http://localhost:8080/myapp/discussions/voteup?id=1
which returns the following json:
{"vote":{"value":"100"}}
I am trying to make a JQuery Ajax Call to post a vote to the url.
$(function(){
$(".vote-up-post").click(function() {
var postId = $("#postId");
alert("Post Value" + postId.val());
$.ajax({
type: "GET",
url: "/myapp/discussions/voteup",
data: {'id': postId.val()},
dataType: "json",
success: function(response){
$(".post-votes-count").text("100");
},
error: function(response){
alert("Error:" + response);
}
});
});
});
I get the the following pop up for the second alert message:
Error:[object XMLHttpRequest]
Any idea what I am missing?
Your error function should be:
error: function(req, response) {
alert("Error:" + response);
}
The first argument of the error function is the XMLHttpRequest object that was used to make the ajax request. The second argument will give you the status of the object: "timeout", "error", "notmodified" or "parsererror."

Resources