Ajax call to another website - ajax

For some reason when I run this simple javascript snippet I get the message "Error! Status = 404 Message = error"
callPHP(1)
function callPHP(args)
{
$.ajax({
url: "http://lectiogroupgenerator.esy.es/index.php",
type: 'post',
data: { "json" : JSON.stringify(args) },
dataType: "json",
success: function (data)
{
if (data)
{
alert(data);
return data;
}
else
{
alert("Data is empty");
}
},
error: function (xhr)
{
alert('Error! Status = ' + xhr.status + " Message = " + xhr.statusText);
}
});
return false;
}
My PHP file is just:
<?php
?>
I'm guessing 404 implicates that the php could not be found, but it does exist and I have no clue why it can't find it maybe it has something to do with me making a google chrome extension?

It might be because of the CORS issue. http://lectiogroupgenerator.esy.es/index.php doesn't allow cross origin HTTP requests.
If that's not the case try explicitly defining the website in the permissions in the manifest file to allow requests in and out to that website.

The problem was caused by the Same-origin policy, it was solved when I got an SSL certificate for my website.

Related

Catching an AJAX error from a post request (422)

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

Cannot connect to local Rest Service with AJAX (Status: 0)

I currently try to connect to a local Rest service with AJAX. However it seems as if I can't get any connection. The Rest Service runs under http://localhost:8080/LernApp/
For Testing I tried to connect to http://localhost:8080/LernApp/user/ which returns a JSON (GET).
I tested this link inside my Browser (works fine and displays the JSON) and with Postman (also works fine and gets the Answer with a status code of 200 (OK)).
However if I try to connect to it with AJAX, it fails (status code 0).
My first try was this:
var xhttp = typeof XMLHttpRequest != 'undefined' ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhttp.open('GET','http://localhost:8080/LernApp/user/',true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.onreadystatechange = function() {
var data;
if(xhttp.readyState==4) {
if(xhttp.status==200) {
alert("OK");
} else if(xhttp.status==404) {
alert("404");
} else {
alert("ERROR CODE: " + xhttp.status);
}
}
}
xhttp.send();
The next thing I tried was this:
$.ajax({
type: 'GET',
url: 'http://localhost:8080/LernApp/user/',
dataType: 'json',
async: true,
success: function(result) {
alert(result.message);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.status + ' ' + jqXHR.responseText);
}
});
And the last thing I tried was this:
$.ajax({
type: "GET",
url: 'http://localhost:8080/LernApp/user/',
headers: {
Accept : "application/json"
}
})
.done(function (data, textStatus, jqXHR) {
alert(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert("STATUS: " + jqXHR.status);
});
None of these seem to work. Every function returns the status code 0.
Does anyone have any idea what is happening here? Like I've said: Browser and Postman can connect to the url without and problems and retrieve the correct data.
Thanks for your help.
I finally found the solution. I should have mentioned more about my server (but since the server did well in the Browser and in Postman, I assumed that the problem would be on the client side).
Well... it was of course a server problem. The server is running on Apache Tomcat 9 with an embedded H2 database and JAX-RS (for REST Service).
If anyone else faces my problem: the solution is called CORS. If you are having the same problem, first google CORS, so that you know what it is and then you can make all of the needed settings inside the web.xml and/or context.xml of your Tomcat Project.

Handling AJAX Origin errors, caused by the Chrome Extension

Is there way to handle AJAX Origin errors from Chrome's extensions ?
Denying load of
chrome-extension://kldbdjcbjohfhddpicldkbifbkcdanid/data.json.
Resources must be listed in the web_accessible_resources manifest key
in order to be loaded by pages outside the extension.
I tried this:
$.ajax({
url: 'chrome-extension://kldbdjcbjohfhddpicldkbifbkcdanid/data.json',
datatype: 'json',
success: function(xhr) {
alert('ok');
},
erro r: function(xhr, status, err) {
alert('status: ' + xhr.status + ' - ' + err);
}
});
but got nothing in variables. error status is "0", error message is empty.
You can try using the jsonp format. This often gets around cross-origin errors.
$.ajax({
url: 'chrome-extension://kldbdjcbjohfhddpicldkbifbkcdanid/data.json',
datatype: 'jsonp',
success: function(xhr) {
alert('ok');
},
erro r: function(xhr, status, err) {
alert('status: ' + xhr.status + ' - ' + err);
}
});
Sounds like you are attempting to load this resource from a content script, based on the error.
You have to explicitly add either the individual extension resources, or patterns that match your extension resources, in the manifest via web_accessible_resources. Your error message states this is the solution.
Once you've done this, you can construct the URL using chrome.extension.getURL(resourcePath).
Here's an excerpt from my manifest:
"web_accessible_resources" : [
"*.html"
]
And here's the code I'm using to request my HTML template file:
var url = chrome.extension.getURL("template.html");
$.get(url,function(data, textStatus, jqXHR){
console.log("Got the template!");
console.log(data);
},"html");

How to post like with ajax to instagram? Help me please

i have this code but its not working. it says to me ajax post is success but when i look make refresh i saw its not liked.
<?
if ($data->user_has_liked == false)
{
?>
<span class="<?=$data->id;?>">Like</span>
<? } else { echo 'Liked'; } ?>
<script type="text/javascript">
$('a.like').click(function() {
var mediaId = $(this).attr('id');
$.ajax({
url: "https://api.instagram.com/v1/media/" + mediaId + "/likes?callback=?",
dataType: "jsonp",
data: {
access_token: '<?=$access_token;?>',
_method: 'POST'
},
type: "POST",
success: function(data, textStatus, jqXHR) {
$("."+mediaId+"").text('Liked');
},
error: function(jqXHR, textStatus, errorThrown) {
$("."+mediaId+"").text('Error!<br/>' + textStatus + ' - ' + errorThrown);
}
});
});
</script>
I am building something similar and have ran into this problem recently.
Even though your request is sent as a type: POST the request itself is actually sent as GET. This causes your request to return successful without liking anything. Instead it will return all the data for that Media ID.
If you change your datatype to JSON instead of JSONP you request should work as you wish; however, it may require an HTTPS connection requiring an SSL.

ajax GET call with node.js / express server

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...

Resources