Send log errors to a file - javascript

I developed a website for my graduation however it still only one thing I have do. What I want is when the script is installed on a website I want to send the name of the website who has installed my script, also whenever there is an error I want to send it to my website so for example:
This website installed my script
www.security-dz.com/myscript
I want to see the path + website in an other file in other website. For example:
www.getlog.com/mylogs.php
The purpose of this is keep my customers update and give them support and see the errors that happen so I can fix them in next updates.

You might want to take a closer look at the JQuery docs for ajax requests, so you can use a secure http connection for logging. This javascript code basically describes a function that sends the errors in text-format to your server-side script. This script can in turn write the error description to a file on the server. I'd recommend using a DB instead; That way you can easily write a web-client that displays all reported errors (and filters and the other good stuff).
You can extract the origin url from the referer [sic] field in the ajax http get-request on the server.
(function () { // function operator, in case console doesn't exist
!console ?
(console = {}) : console;
!console.log ?
(console.log = function () { }) : console.log;
!console.info ?
(console.info = console.log) : console.info;
!console.error ?
(console.error = console.log) : console.error;
}());
// Uses JQuery
function reportError (errDesc) {
var path = "www.getlog.com/mylogs.php";
$.ajax({
url: path,
type: "GET",
async: true,
cache: false,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
crossDomain: true,
data: errDesc,
dataType: "jsonp",
error: function (req, type, errObj) {
console.error("Reporting error failed: " + type + "\nAt url: " + path + "\n" + errObj);
// In case you need to debug the error reporting function
},
succes: function (res) {
console.info("Reported error to server:\nRequest:" + errDesc + "\nResponse: " + res);
// extra error logging facility on client-side, invisible to most users
},
global: false // prevent triggering global ajax event handlers
});
return errDesc; // in case you want to reuse the errDesc
}
Code has been validated with jshint. Please let me know if there are still issues, because I didn't take the time to completely replicate your setup (setting up 2 different domains etc.)
Addendum: Some useful reading if you're having issues with cross-domain messaging, JSON is not a subset of javascript, Cross-origin resource sharing, JSONP.

What you could do is post both the name of the website that uses your script and the error code variable with AJAX through URL to your logging website, which will then get the variable and name from the URL and use these to add to your log.
You should, however, by using this tactic, also make use of some URL validation, otherwise this will leave you wide open to injection attacks.

it is easy when your script installed , get the site info and send by socket and http request with get method and then recive it on your server.
for errors, php has some method to control error logs so custom it.

Related

Simple POST request using jQuery leads to unexpected redirect

I've got a few similar POST request on a website. In one case, the request is working (data is stored on the server), but then, there's an unexpected redirect. I send/receive data using jQuery. On the backend, I use the PHP framework Laravel.
Let's say I'm on myapp.dev/clients/123. Then I click the store-data-button and data is sent to/received from the server (Let's assume $('#resubmission_note').val() === 'abc'):
// AJAX request
$('#store-data-button').on('click', function() {
let ajaxRequest = $.ajax({
url: '/resubmissions',
type: 'POST',
data: {
// An integer, some text, and a date
'client_id': $('#id').html(),
'resubmission_note': $('#resubmission_note').val(),
'resubmission_due_date': $('#resubmission_due_date').val()
}
});
ajaxRequest.done(function(returned_id) {
// Removed all code here for testing. Browser still redirecting.
});
});
But then the browser is redirected to myapp.dev/clients/123?resubmission_note=abc.
The network tab in Chrome devtools says
Name:123?resubmission_note=abc
Status: 200
Type: document
initiator: Other
There's data appended in the URL, that should only be the case with GET request, AFAIK. I checked whether some other JavaScript code might interfere, but couldn't find store-data-button or resubmission_note in any unexpected files.
Any advice on how to fix the problem or how to debug it?

400 Bad Request error when when moving application from local to web server

I have a pyramid application that runs perfectly on a local server, but when I move it over to a web server (Dreamhost), I get the following error:
400 Bad Request:
Bad request (GET and HEAD requests may not contain a request body)
The code in question is the following ajax in Javascript:
function summary_ajax(sName){
$.ajax({
type: "POST",
url: "summary",
dataType: "json",
data: {
'ccg_name': sName,
},
async: false,
success: function(data) {
//alert("In ajax success function") <----------- This never executes
lValues = data.lValues;
lLabels = data.lLabels;
},
});
};
return (lValues, lLabels);
And is handled in views.py:
#view_config(route_name="ccg_map_summary_ajax",renderer="json")
def ccg_map_summary_ajax(self):
sCCG = self.request.POST.get('ccg_name')
fData = open('pyramidapp/static/view_specific_js/ajax_summary_data.js')
dData = json.load(fData)
lLabels = dData[sCCG].keys()
lValues = dData[sCCG].values()
return {
'lLabels' : lLabels,
'lValues' : lValues,
}
I did some testing by placing alert() functions (its slow, because the server only reloads the script every so many minutes), and everything executes fine except for alerts in the ajax call. So it seems that either the post fails, or something goes wrong in the view. Any ideas?
So is there something in this code that works in my local server (in Pyramid) but breaks down in the web server (Dreamhost)?
The file structure is the same in the local and web server. I don't see why it shouldn't, but will fData still open the file for reading?
For anyone else out there, I found the problem:
The path I specified above was a relative path that worked on my system but not on the server because the working directories are obviously different. So instead of using a relative path, I just changed the script to have the correct absolute path.
To find the current working directory path, just enter pwd into terminal.

jQuery $.ajax works with GET but fails on POST

I've got a really weird problem on a customer's server.
I'm using code like the one posted below in several scripts.
The $.ajax configurations are almost identical (i.e. only file, data and success function change) and always use type:POST.
This works most of the times, but for the case below POST always fails.
Changing the type to GET works without a problem.
I'm a little bit clueless what happens here.
var parameter = {
password : $("#password").val()
};
$.ajax({
type : "POST",
url : "query/submit_password.php",
dataType : "xml",
async : true,
data : parameter,
success : function(aXHR) { /* ... */ },
error : function(aXHR, aStatus, aError) { alert("Error:\n" + aStatus + "\n"+ aError); }
});
This code always results with an alert "NetworkError: A network error occurred.".
Again - other cases with almost identical code work without a problem.
Chrome and Firefox dev tools report a POST error without any further explanation.
Any idea what happens here?
A few more details.
The client's site is hosted on GoDaddy
The same piece code works well on other servers
Yes, the file does exist as a GET request works
All browsers I tried this on have no blocker plugins (like adblock) installed
HTTPScoop shows the following results
(3 attempts, the red status says "Connection closed by communications partner"):
Chrome shows the following:
Almost solved.
The apache log showed a status 403 on the request.
It also showed a returned size of 0 which probably is the reason why chrome, etc. showed a failed request.
Why this happens is still not clear but it is definitely a server side configuration problem (most likely a mod_rewrite problem or sth. like that).
try add contentType: "application/json; charset=utf-8" to your ajax call
$.ajax({
type : "POST",
url : "query/submit_password.php",
contentType: "application/json; charset=utf-8",
dataType : "xml",
async : true,
data : parameter,
success : function(aXHR) { /* ... */ },
error : function(aXHR, aStatus, aError) { alert("Error:\n" + aStatus + "\n"+ aError); }
});
if it doesn't help try what benhowdle89 says, stringify(parameter).

External server query not working

I am building a jQuery Mobile and PhoneGap application.
Here is some of my code to query data from an external server:
function showDetail(stationID){
$('#itemDetail').load('http://www.mywebsite.com/detailPage.php?stationId='+stationID, function(){
});
It works perfectly on my local machine, WAMP server, however when I compile the script and run on an actual device, Android, it does not work. The same thing applies to this form:
$('#addStationForm').on('submit', function(e) {
$.post( 'http://www.mywebsite.com/add_parser.php', $(this).serialize(), function(response) {
alert( response );
});
// disable default action
e.preventDefault();
});
Also I have whitelisted my server, so that is not the problem.
Any help would be greatly appriciated, thanks.
Are you trying to get data from a server and load it into a dom element?
If so use the .ajax function to perform a http request to get the data from the sever.
Check the following doc with good examples
http://api.jquery.com/jQuery.ajax/
Also provide more info about the type of data you are going to request receive to help you further in the configuration of the ajax call parameters.
You can also use getJSON but depending on your data and needs.
EDIT
Post is a shorthand of the ajax function.
Make sure your PHP does have the correct content-type in the headers. That is very important
Like:
header("Content-Type:text/plain");
or
header("Content-Type:text/html");
depending what you need, want.
Also you can debug the HTTP response using firebug or any other tool out there, and let us know what you got.
Also try to use the verbose option of the function, give it a try. Make sure you specify correctly the dataType and the data parameters.
$.ajax({
type: "POST",
url: url,
data: data,
dataType: "html" // DATA TYPE is ALSO VERY IMPORTANT
})
.done(function() {
alert( "success" );
})
.fail(function( XMLHttpRequest, textStatus, errorThrown ) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
});
Also, when you said "when I compile the script and run on an actual device, Android, it does not work.", what errors you got? use the FAIL function of the http request to print the errors (like in the example above).

jQuery and Ajax - cannot POST

I am trying to login to a website using a known username and password and to get some data displayed from the site for a specific user account on that website. I am using jQuery and Ajax for this purpose. This is my code:
$.ajax({
async: false,
cache: false,
type: 'POST',
dataType: 'json', // json...just for example sake
data: ({
'login_username': username,
'secretkey': password
}),
url: 'https://mail.someserver.com/src/redirect.php',
success: function (data) {
alert("SUCCESS!")
if (data === '1') { // server returns a "1" for success
// success!
// do whatever you need to do
} else {
// fail!
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// something went wrong with the request
alert("Failed!");
}
});
I've already made my search around the web and I know that browsers do not permit cross server ajax calls to prevent security issues, but I've already tried to use "jsonp" as dataType to no avail :(
So, what am I doing wrong?
Be sure that your url is not breaking the same origin policy -- that is, the request coming from the client cannot request data from a server from a different domain (there are exceptions to this rule, namingly CORS, but that requires that you make changes to the server/application you're talking to).
The solution to your problem would be to make the request from some server-side script, then in turn having your client application query that script, based on the same machine that's serving the application to the web.
My fault isn't at the code above, my fault was that in my manifest file (I am building a Google Chrome extension) I didn't have set proper permissions (https://*).
Sorry for the frustration!

Categories