It seems like I've tried everything and I finally just switched to using the CORS npm module:
var cors = require('cors');
And my one route I want to use CORS on:
app.post('/hangouts', cors(), hangoutsController.hangouts); // user CORS
I'm implementing a custom app in Google Hangouts, but need to post to my server, and the Hangout is run from a Google server. I put the AJAX call on a loop so that it will keep trying - this post going through is crucial to my app.
Here's the relevant AJAX call in the Hangout app:
var shouldpostHangoutId = true;
/* Post the Hangout ID to server */
var postHangoutId = function(hangoutId) {
var startData = gapi.hangout.getStartData();
$.ajax({
type: 'POST',
url: rootURL + "/hangouts",
crossDomain: true,
dataType: "json",
data: {
"hangouts_id" : hangoutId,
"start_data" : startData
},
success: function( response ) {
console.log( "postHangoutId -- success" ); // server response
console.log( response ); // server response
shouldpostHangoutId = false;
},
error: function(xhr, textStatus, error){
console.log( "postHangoutId -- error" ); // server response
console.log(xhr.statusText);
console.log(textStatus);
console.log("error = " + error);
// Try again
if (shouldpostHangoutId) {
postHangoutId(hangoutId); // Try again
};
}
});
};
What's driving me crazy is that sometimes it goes through on the first go, sometimes it takes 5 times. And the whole process is super slow. Here's the log I get when it doesn't come through:
XMLHttpRequest cannot load https://www.foo.bar/hangouts. No 'Access-Control-Allow-Origin' header
is present on the requested resource. Origin 'https://ts6d5n5om59gt6cin9c39faccjf890k5-a-hangout-
opensocial.googleusercontent.com' is therefore not allowed access.
I'm using Node + Express ~4 on Heroku.
I think the problem had something to do with pre-flight requests. I changed the AJAX call to the following:
$.ajax({
type: 'POST',
url: rootURL + "/hangouts",
dataType: "json",
data: {
"hangouts_id" : hangoutId,
"start_data" : startData
},
error: function( error ){
// Log any error.
console.log( "ERROR:", error );
// Try again
if (shouldpostHangoutId) {
postHangoutId(hangoutId); // Try again
};
},
complete: function(){
console.log( "postHangoutId -- success" ); // server response
shouldpostHangoutId = false;
}
});
And it goes right through, first time without delay.
Related
I am trying to send data via an Ajax request from the DOMContentLoaded listener in my global.js
The following code produces error 400 (Bad request), and I'm not clear why. If I submit the same payload using Postman to that Url, I get success.
Global.js
document.addEventListener('DOMContentLoaded', function() {
var obj1 = document.getElementById('myObject');
// A bunch of logic to retrieve data to be sent to the server
// that if successful triggers a callback function
ProcessEvent: function (info){
// Update the database record here
//
alert("Making an AJAX call");
var xcall = $.ajax({
url: "http://127.0.0.1:3000/cashiers/jsonset",
type: 'post',
contentType: 'application/json',
data: obj1.items,
dataType: "json",
success: function(json) {
alert('Success : '+ json.reponse);
},
error: function(res){
alert("Error "+res.status+" with "+res.statusText);
}
}).done(function( msg ){
alert( "Data Saved: " + msg );
});
}
});
I have the following Ajax but it needs to handle a 422 error being returned (which means Out of Stock). I've tried a few ways around but it error's and refuses to POST stating:
Failed to load resource: the server responded with a status of 422 ()
I'm unsure how to catch the 422 error and return something to the user displaying that it's out of stock.
Shopify.moveAlong = function() {
// If we still have requests in the queue, let's process the next one.
if (Shopify.queue.length) {
var request = Shopify.queue.shift();
var data = 'id='+ request.variant_id + '&quantity='+request.quantity_id;
$.ajax({
type: 'POST',
url: '/cart/add.js',
dataType: 'json',
data: data,
success: function(res){
Shopify.moveAlong();
},
error: function(){
// if it's not last one Move Along else update the cart number with the current quantity
if (Shopify.queue.length){
Shopify.moveAlong()
}
}
});
}
else {
window.location.href = "/cart";
}
};
Shopify.moveAlong();
I've tried a few ways around but it error's and refuses to POST.
What I have understood is, you are seeing this error in Browser console. It cannot be prevented, but it does not mean that you request is not going through. The POST request is recieved by Shopify and a response with status 422 is sent, so that is treated as an error (Non 2xx response codes are treated as error).
To handle the error and display error message, adapt the code accordingly. Check updated code and code comments.
Shopify.moveAlong = function() {
// If we still have requests in the queue, let's process the next one.
if (Shopify.queue.length) {
var request = Shopify.queue.shift();
var data = 'id=' + request.variant_id + '&quantity=' + request.quantity_id;
$.ajax({
type: 'POST',
url: '/cart/add.js',
dataType: 'json',
data: data,
success: function(res) {
Shopify.moveAlong();
},
error: function(jqXHR, textStatus, errorThrown) {
// Check status code
if (jqXHR.status === 422) {
// display error wherever you want to
console.log(jqXHR.responseText);
}
// if it's not last one Move Along else update the cart number with the current quantity
if (Shopify.queue.length) {
Shopify.moveAlong()
}
}
});
} else {
window.location.href = "/cart";
}
};
Shopify.moveAlong();
AJAX Error Docs
Hello I have one registration form of users as soon as user register in next browser tab i will get that registered user details without page refresh for this i got code from github project and tested that which is working perfectly and I have loaded jquery,socket.js file in both pages (data post,retrieving page)as they mentioned in that still i am not getting latest registered users without page refresh ,so please tell me where the code need to be correct.below is my code
code to post data(register users)
$("#submit").click(function(event){
event.preventDefault();
var dataString = {
name : $("#name").val(),
email : $("#wickets").val()
};
$.ajax({
url: "<?= base_url('User/register') ?>",
type: "POST",
data: dataString,
dataType: "json",
cache : false,
success: function (data) {
if (data.success == true) {
var socket = io.connect( 'http://'+window.location.hostname +':3000' );
socket.emit('registered_users', {
name: data.name,
email: data.email
});
}
}, error: function (xhr, status, error) {
alert(error);
},
});
});
code to get name and email of user who have just register by socket
html div tags to print user name and email
<div id="user_name"></div>
<div id="user_email"></div>
script for socket
var socket = io.connect( 'http://'+window.location.hostname+':3000' );
socket.on( 'registered_users', function( data ) {
$( "#user_name" ).prepend( data.name );
$( "#user_email" ).prepend( data.email );
});
Here is my two ajax requests:
$.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded ",
url: "https://example.com/j_spring_security_check",
data: { j_username: "mmm#mmmm.com", j_password: "mmmm" },
error: function (request, status, error) {
alert("POST LOG IN REQUEST:\t" + request + "\nSTATUS:\t" + status +
"\nERROR:\t" + error);
}
});
$.ajax({
type: "GET",
dataType: "json",
xhrFields: {
withCredentials: true
},
url: "https://mmm.com/rest/xxx/",
success: function(output, status, xhr) {
var flight = output;
alert(flight[0].flight.toAirport.name);
//return flight;
},
error: function (request, status, error) {
alert("GET ALL FLIGHTS REQUEST:\t" + request + "\nSTATUS:\t" + status +
"\nERROR:\t" + error);
}
});
When I run the code and use firebug - the second request keeps using the same old cookie in every new session. What I want to happen is that the second request will use the cookie from my first POST(login) request. I have tried several variations of withCredentials: true/false and crossDomain: true/false on both requests.
When i clear the cookies, the get request will create it's own cookie. Then I refresh the page to let the script run again. The POST request will create a new cookie(as it should), but the get request will re-use the cookie it made before.
I´m trying to write a small ajax live search for node.js. First of all here is my Clientside code:
$('#words').bind('keyup', function(){
getMatchingWords($('#words').val(), function (data){
console.log('recieved data');
console.log(data);
$('#ajaxresults').show();
});
});
function getMatchingWords(value, callback) {
$.ajax('http://127.0.0.1:3000/matchword/' + value + '/', {
type: 'GET',
dataType: 'json',
success: function(data) { if ( callback ) callback(data); },
error : function() { if ( callback ) callback(null); }
});
}
and here ist my serverside route:
app.get('/matchword/:value', function(req, res) {
console.log(req.params.value);
res.writeHead(200, {'content-type': 'text/json' });
res.write( JSON.stringify({ test : 'test'}) );
res.end('\n');
});
it works but i don´t recieve any data. data in the callback function is always null. so what i am doing wrong? thx for the help
Change
$.ajax('http://127.0.0.1:3000/matchword/' + value + '/', {
to
$.ajax('/matchword' + value + '/', {
What's the URL that you're making the $.ajax() request from? If the page containing that client-side JS wasn't also loaded from 127.0.0.1:3000, the error you're seeing is due to the same-origin requirement on AJAX requests.
hey better late than never...
I was looking at your problem because I am also trying to put a simple live search together with an express.js back end.
first of all I put your url into a local variable. As I don't think that was your problem.
Particularly if your express / node log was showing a 200 response. then the url was fine...
It seems your function wasn't returning data (correct ?) if so try this.
var search_url = "..."// your url
function getMatchingWords(value, callback) {
$.ajax(search_url, {
type: 'GET',
dataType: 'json',
success: function (data, textStatus, jqXHR) {
var returned_data = data;
console.log("returned_data ="+returned_data);//comment out or remove this debug after test
callback(returned_data);
},
error: function( req, status, err ) {
console.log( 'something went wrong', status, err );
}
});
}
you might also need to add / modify your headers subject to the set up...
headers : { Authorization : auth },
type: 'GET',
dataType: 'json',
crossDomain:true,
the auth variable being an encoded auth pair somewhere else in your code (if your web service is requires some kind of auth...