I have a script where I am doing an Ajax request to the server:
var answers = JSON.stringify(Controller);
$.ajax({
type: "POST",
url: "/utdanningstesten/ws/answers/",
dataType: "json",
contentType : "application/json",
data: answers,
success: function(res){
console.log(res);
if (lang === 'nb') {
window.location.replace("/utdanningstesten/resultPage.php?id="+res);
}
else {
window.location.replace("/utdanningstesten/resultPage.php?id="+res+'&lang='+lang);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.readyState == 4) {
console.log('HTTP error');
}
else if (XMLHttpRequest.readyState == 0) {
console.log('Network error (i.e. connection refused, access denied due to CORS, etc.)');
}
else {
console.log('something weird');
}
}
});
}else{
//$('.btnG').append('<div class="alert">');
blink('.btnG', 6, 150)
}
And this works fine on the live server, when I am trying to test this on the local server, with the local address http://velgriktig.dev:8888 it doesn't work. In the console I get that the request to that endpoint is pending, no errors, just pending forever.I have tried with adding also http://velgriktig.dev:8888 to the endpoint, so that I have the full URL, but that didn't help either, why can't I get this work locally?
Related
I want to send a secure request to the targeted API endpoint and don't want to let the browser to track the requested API URL in browser debugging tool.
Is there any way to decode the API requested URL so that the URL will not be shown in the browser debugger network tab?
I am using pyton django framework.
Ajax
function Approve(camp_id, updated)
{
if (updated === 1){
var payload = {'campaign_status': 5}
}
else{
var payload = {'campaign_status': 1}
const token = '{{csrf_token}}';
}
$.ajax(
{
url: `https://api.example.com`,
data:{
camp_id:camp_id
}
type:"PUT",
headers:{"Authorization": `Bearer ${token}`,, "csrfmiddlewaretoken": token },
contentType: "application/json",
data: JSON.stringify(payload),
success: function(response, xhr)
{
window.location.reload();
},
error: function(response, xhr)
{
console.log(response)
}
}
);
}
i have solved this problem by handling my api call via django view, rather than with ajax, final code will look like
Ajax:
function Approve(camp_id, updated)
{
if (updated === 1){
var payload = {'campaign_status': 5}
}
else{
var payload = {'campaign_status': 1}
const token = '{{csrf_token}}';
}
$.ajax(
{
url: `approve/edit`,// django view url
data:{
camp_id:camp_id
}
type:"PUT",
headers:{"Authorization": `Bearer ${token}`,, "csrfmiddlewaretoken": token },
contentType: "application/json",
data: JSON.stringify(payload),
success: function(response, xhr)
{
window.location.reload();
},
error: function(response, xhr)
{
console.log(response)
}
}
);
}
I have an ajax that call to a server and run a long process (this process is writing the status on a database).
I have other ajax (recursively) to get the status of the long process and set the params on a Progress Bar.
My problem is that the second ajax not start until the first one finishes. Is there a way to send the first ajax and no wait for a response?
Any ideas?
I appreciate any suggestion, I am a little bit tired about this issue.
If there is another method to send a long process and get the status of the long process, tell me, please.
Thank you!
This is my code, in case it's helps
executeProgressBar(1, token);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
url: "/long_process",
data: form_data,
success: function (response) {
//NOTHING
}
});
function executeProgressBar(start, token) {
if (start == 1) {
//reset progress bar
$('.progress-bar').css('width', '0%');
$('.progress-bar').text('0%');
$('.progress-bar').attr('data-progress', '0');
}
$.ajax({
type: "POST",
url: "/progress_bar_status",
data: { token: token, sleep: 0 },
success: function (response) {
$('.progress-bar').css('width', response['percentage'] + '%');
$('.progress-bar').text(response['percentage'] + '%');
$('.progress-bar').attr('data-progress', response['percentage']);
$('#done').text(response['executed']);
$('.execute-time').text('tiempo');
if (response.percentage == 100) {
$('.end-process').show();
} else {
executeProgressBar(0, token);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (textStatus == 'parsererror') {
textStatus = 'Technical error: Unexpected response returned by server. Sending stopped.';
}
alert(textStatus);
}
});
}
EDIT
I solved whit this code on the server side - php
/************** Close connection and return echo message **************/
ob_end_clean();
header("Connection: close");
ignore_user_abort(true);
ob_start();
echo('text response to ajax');
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush();
flush();
// if you're using sessions, this prevents subsequent requests
// from hanging while the background process executes
if (session_id()) {
session_write_close();
}
/************** background process starts here **************/
View in this post: How do I close a connection early?
You are calling the executeProgressBar instantly instead of waiting for the first AJAX call to complete. Call the executeProgressBar function in the success method callback and pass it to the executeProgressBar function and modify the parameters like the example below.
Be sure to build a check in that lets the recursive function know when to stop.
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
url: "/long_process",
data: form_data,
success: function (response) {
executeProgressBar(1, token, response);
}
});
function executeProgressBar(start, token, response) {
if (start == 1) {
//reset progress bar
$('.progress-bar').css('width', '0%');
$('.progress-bar').text('0%');
$('.progress-bar').attr('data-progress', '0');
}
$.ajax({
type: "POST",
url: "/progress_bar_status",
data: {token: token, sleep: 0},
success: function (response) {
$('.progress-bar').css('width', response['percentage'] + '%');
$('.progress-bar').text(response['percentage'] + '%');
$('.progress-bar').attr('data-progress', response['percentage']);
$('#done').text(response['executed']);
$('.execute-time').text('tiempo');
if (response.percentage == 100) {
$('.end-process').show();
} else {
executeProgressBar(0, token, response);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (textStatus == 'parsererror') {
textStatus = 'Technical error: Unexpected response returned by server. Sending stopped.';
}
alert(textStatus);
}
});
}
I am using ajax call, and it is throwing "not responding due to a long-script is running" in browser and gives a button to stop script.
the url is coming perfectly and the console.log(4) inside the success function is not even loading, it just hangs.
The issue is happening for certain scenarios only for others it is working. I have even compared the data, there is no change in data structure also.
Please helpme out
$.ajax({
timeout: 3000,
type: "POST",
url: serviceURL,
data: JSON.stringify(apiInput),
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
console.log(4);
if (onsuccess !== null) {
onsuccess(data);
}
},
error: function (x, y, z) {
if (onerror !== null) {
onerror(x, y, z);
}
}
});
I am not sure what the onsucces part of your Ajax success method is trying to do here.
Try this and look a the console for the errors
$.ajax({
type: "POST",
url: serviceURL,
data: JSON.stringify(apiInput),
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
},
error: function (x, e) {
if (x.status == 0) {
console.log('You are offline!!\n Please Check Your Network.');
} else if (x.status == 404) {
console.log('Requested URL not found.');
} else if (x.status == 500) {
console.log('Internel Server Error.');
} else if (e == 'parsererror') {
console.log('Error.\nParsing JSON Request failed.');
} else if (e == 'timeout') {
console.log('Request Time out.');
} else {
console.log('Unknow Error.\n' + x.responseText);
}
}
});
I think you were trying to check if the API call was successful or not, the way Ajax works is on the status of the request essentially if the request returns a status of 200 (which means it's ok) then it will hit the success part of the method, if it's an error foe example 404 (cannot find the URL) or 500 (internal server error) then the error part of the function will be hit, then just console.log that data and view it as you need to.
I have the following json sent (POST) from my javascript to the php
function boardToJSON() {
return JSON.stringify({
"pieces" : gPieces, // gpieces and gdestinations is an array
"destinations" : gDestinations,
"boardSize" : kBoardHeight // boardSize is an integer value 9
});
// Below function is called on Button Click and url contains PATH to the php file.
function makeMove() {
var move;
$.ajax({
type: 'POST',
url: url,
contentType: "application/json",
dataType: "json",
async: false,
data: boardToJSON(),
success: function(msg) {
move = msg;
},
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Unable to connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested URL of HalmaAI not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Data from HalmaAI was not JSON :( Parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
On the server side (in PHP) I am trying to get it like this
$jsonString = file_get_contents("php://input");
$myJson = json_decode($jsonString);
echo $myJson["boardSize"]; // also tried $myJson.boardSize etc
Issue is that I am unable to decode JSON in PHP. Can someone guide me here please ? Thanks
You should set the contentType property on AJAX request to application/json. This will set proper header on request such that server will not attempt to populate $_POST in favor of you working with the raw input.
function makeMove() {
var move;
$.ajax({
type: 'POST',
url: url,
contentType: "application/json"
dataType: "json",
async: false,
data: boardToJSON(),
success: function(msg) {
move = msg;
}
});
}
Assuming this works, you can access the boardSize property at:
$myJson->boardSize;
The other problem you have is that since you specify dataType: "json" you need to make sure you send back valid JSON, which you currently are not.
This is not valid JSON:
echo $myJson["boardSize"];
This would be (of course this is a trivial example):
$returnObj = new stdClass();
$returnObj->boardSize = $myJson->boardSize;
echo json_encode($returnObj);
If you want decode json to array in PHP, you should set the 2nd argument of json_decode to true.
Example:
$jsonString = file_get_contents("php://input");
$myJson = json_decode($jsonString, true);
echo $myJson["boardSize"];
I want to make an Ajax request with response in JSON. So I made this Ajax request:
$.ajax({
url: 'http://my_url',
dataType: "json",
success: function(data){
alert('success');
},
error: function(data){
alert('error');
},
complete: function(data) {
alert('complete')
}})
This code works good but when my url send me a HTTP code 404, no callbacks are used, even the complete callback.
After research, it's because my dataType is 'json' so 404 return is HTML and the JSON parsing failed. So no callback.
Have you a solution to call a callback function when a 404 is raised ?
EDIT: complete callback don't call is return is 404. If you want an URL wit 404 you can call : http://twitter.com/status/user_timeline/jksqdlmjmsd.json?count=3&callback=jsonp1269278524295&_=1269278536697 it's with this URL I have my problem.
$.ajax({
url: 'http://twitter.com/status/user_timeline/jksqdlmjmsd.json?count=3&callback=jsonp1269278524295&_=1269278536697',
dataType: "json",
success: function(data) {
alert('success');
},
error: function(data) {
alert('error');
},
complete: function(xhr, data) {
if (xhr.status != 0)
alert('success');
else
alert('fail');
}
})
With your configuration jQuery uses jsonp to transport the data. This works by dynamically inserting a script element and setting the URL to the specified value. The data returned by the server is then evaluated as JavaScript - usually calling the provided callback. If the server returns a 404, the contents is obviously no JavaScript and the callback is never called. Some browsers support error handlers on the script tag, which are called in these situations. Unfortunately IE doens't support this. The best way to detect an error is to rely on a timeout.
In your case you should specify an additional timeout option, which causes the error handler to be called if the callback wasn't called in time (which would be the case for a 404 response).
$.ajax({
url: 'http://my_url',
timeout: 2000, // 2 seconds timeout
dataType: "json",
success: function(data){
alert('success');
},
error: function(data){
alert('error');
},
complete: function(data) {
alert('complete')
}
});
Use the statusCode-Option
$.ajax({
url: 'http://my_url',
dataType: "json",
statusCode: {
404: function() {
alert("I could not find the information you requested.");
}
},
success: function(data) {
alert('success');
},
error: function(data) {
alert('error');
},
complete: function(data) {
alert('complete');
}
})
If you want to handle errors when accessing the Twitter API with Javascript and jsonp you need to include the parameter suppress_response_codes in your request. This makes all responses from the Twitter API respond with a 200 OK response and include a error. Then you need to check if the response includes the error parameter or not.
$.ajax({
url: "https://api.twitter.com/1/users/show.json",
dataType: 'jsonp',
jsonp: "callback",
data: {
screen_name: "simongate1337",
suppress_response_codes: true // <- Important part
},
success: function(data) {
if(data.error) {
console.log("ERROR: "+data.error);
} else {
console.log("Success, got user " + data.screen_name);
}
}
});
Do not you think that the problem is not with the dataType but with cross-domain requests that you are not allowed to make?
The code below works as expected when you request data from the same domain and does not when you are making cross-domain requests:
function handle404(xhr){
alert('404 not found');
}
function handleError(xhr, status, exc) {
// 0 for cross-domain requests in FF and security exception in IE
alert(xhr.status);
switch (xhr.status) {
case 404:
handle404(xhr);
break;
}
}
function dumbRequest() {
var url = 'http://twitter.com/status/user_timeline/jksqdlmjmsd.json?count=3&callback=jsonp1269278524295&_=1269278536697';
url = 'http://twitter.com/';
url = '/mydata.json';
// url = 'mydata.json';
$.ajax(
{url: url,
dataType: 'json',
error: handleError}
);
}
Is it simply because the dataType is set to "json"? If so, try changing it to text and evaluate the JSON yourself:
$.ajax({
url: 'http://twitter.com/status/user_timeline/jksqdlmjmsd.json?count=3&callback=jsonp1269278524295&_=1269278536697',
dataType: 'text',
success: function(data, status, xmlHttp) {
try {
data = eval('(' + data + ')');
alert('success');
} catch (e) {
alert('json parse error');
}
},
error: function(xmlHttp, status, error) {
alert('error');
},
complete: function(xmlHttp, status) {
alert('complete');
}
});
Are you aware that even though the HTTP status is 404, the actual body is valid JSON? For instance, this link has the following JSON:
jsonp1269278524295({"request":"/status/user_timeline/jksqdlmjmsd.json?count=3&callback=jsonp1269278524295&_=1269278536697","error":"Not found"})
As such, you should check if your data has the error property within your normal callback function.
UPDATE: apparently, even though the actual content of the page is valid JSON, the browser (I checked in Firefox) is not executing it, most likely because it is a 404. Because jQuery has to add a script element (because of the cross-domain issue), its JSONP wrapper is never called, and as a consequence, neither are your callbacks.
So, in short, I don't think there is a way to deal with this without manually adding that script element and checking if your pre-defined callback function has been called afterwards.
Just faced the same issue, and saw another question mentioned that jQuery-JSONP (jQuery Plugin) supports catching 404 errors or as they describe: "error recovery in case of network failure or ill-formed JSON responses"
And it works perfect :)
Here is my (simplified) code for fetching details about a YouTube video via JSONP:
$.jsonp(
{
url: "https://gdata.youtube.com/feeds/api/videos/ee925OTFBCA",
callbackParameter: "callback",
data:
{
alt: "jsonc-in-script",
v: "2"
},
success: function(json, textStatus)
{
console.log("WEEEEEEEE!");
},
error: function(xOptions, textStatus)
{
console.error(arguments);
}
});
Here's how I deal with this. I check the returned data for errors before trying to use it. What is shown below is just a sample that you could extend to more closely match your requirements. This also considers session time outs and other scenarios...
My initial call:
$.ajax({ type: 'POST',
url: '../doSomething',
data: 'my data',
success: function(data) {
if (HasErrors(data)) return;
var info = eval('(' + data + ')');
// do what you want with the info object
},
error: function(xmlHttpRequest) {
ReportFailure(xmlHttpRequest);
}
});
And the two helper functions:
function HasErrors(data) {
if (data.search(/login\.aspx/i) != -1) {
// timed out and being redirected to login page!
top.location.href = '../login.aspx';
return true;
}
if (data.search(/Internal Server Error/) != -1) {
ShowStatusFailed('Server Error.');
return true;
}
if (data.search(/Error.aspx/) != -1) {
// being redirected to site error reporting page...
ShowStatusFailed('Server Error. Please try again.');
return true;
}
return false;
}
and
function ReportFailure(msg) {
var text;
if (typeof msg == 'string') {
text = msg;
}
else if (typeof msg.statusText == 'string') {
if (msg.status == 200) {
text = msg.responseText;
}
else {
text = '(' + msg.status + ') ' + msg.statusText + ': ';
// use the Title from the error response if possible
var matches = msg.responseText.match(/\<title\>(.*?)\<\/title\>/i);
if (matches != null)
{ text = text + matches[1]; }
else
{ text = text + msg.responseText; }
}
}
// do something in your page to show the "text" error message
$('#statusDisplay')
.html('<span class="ui-icon ui-icon-alert"></span>' + text)
.addClass('StatusError');
}
Following solution is working fine for me :)
$.ajax({
url: 'http://my_url',
dataType: "json",
success: function(data){
alert('success');
},
error: function(data){
alert('error');
},complete: function(xhr, data) {
if(data==="parsererror"){
alert('404');
}
}
});