Javascript obfuscate AJAX code - javascript

First of all sorry if the name of the topic isn't the most correct.
Imagine the following code which connects to a PHP file by AJAX.
function get_locales(){
var the_locale = $('#page-add-text').val();
var url = "classes/load_info.php?type=locale&value=" + the_locale;
var all = "";
$.getJSON(url, function(data){
$.each(data, function(index, item){
all += "<li data-name='" + item.value + "'></li>";
});
$("#page-add-listview").html(all);
$("#page-add-listview").trigger("change");
$("#page-add-listview").listview("refresh");
});
}
If people download the page, they will see classes/load_info.php?type=locale&value= + the_locale;
With this they automatically assume that the url is: www.stackoverflow.com/classes/load_info.php?type=locale&value=TESTING;
So, they can view/retrieve what the function prints, plus, they might try to get some bugs.
I'm asking for help in know-how of best ways (if there is any..) to avoid this.
Thank you.

No matter how much you obfuscate your code, the Network panel of Developer Tools will always show the exact request clear as day.
Why not try just fixing bugs and not leaving security holes in your code?

The person will only be able to see client side code and not the code that is executed on your sever (PHP, etc). There is no way to hide what the server sends to the browser.

Security of your application should never rest on the client-side, for reasons just like this one. If you are passing anything to the client that they shouldn't see, then the way you fix that is to just not pass sensitive data to the client. The data that you pass to the client is data that you want them to see. Errors and bugs happen, but the fact that they are taking the time to inspect your AJAX returns probably means that they won't mind much.

Related

Retrieving cross-domain JSON data, Javascript/JSON

I did some research on retrieving cross domain JSON data, but when I implemented it, the code didn't work. Doing some more research, I found that browsers don't let websites retrieve data from a different host due to security reasons. I found an answer that said I should use JSONP, but it still wasn't working? This was my code.
function getWeather(location){
$.getJSON("http://api.openweathermap.org/data/2.5/weather?q=" + location + "&appid=/*my usual app id is here*/&callback=?", function(result){
//response data are now in the result variable
alert(result.weather[0].description);
var changeW = document.getElementById("theweathertext");
changeW.innerHTML = "The current weather at your destination: " + result.weather[0].description +".";
});
}
When I test the code, the browser isn't letting me retrieve the data? How would I fix this? Thanks in advance.
UPDATE: This code was working when I was testing it locally, but when I did a live launch preview, it didn't work. Could this be some other problem?
I think this code will work if you provide a valid apikey:
$.getJSON(
'http://api.openweathermap.org/data/2.5/weather?q=lisbon&callback=?',
function(data){
console.log(data);
}
);
EDIT: It currently gives me 401 code which means i have no rights to access this endpoint. That is why i'm suggesting to use a valid api key.

Why am I getting this Internal Server Error in the Laravel Framework?

I have come across a situation that doesn't make much sense to me. Just as some background information, I'm using the Laravel framework. The page in question calls a query when the page is requested using Laravel's '->with('var', $array)' syntax. This query (which I will post later) works perfectly fine on page load, and successfully inserts dummy data I fed it.
I call this same query via an Ajax $.post using jQuery, on click of a button. However, when I do this $.post and call this query, I get an Internal Server Error every time. Everything is exactly the same, information passed included; the only difference seems to be whether or not it is called on page load or via the $.post.
Here is the error:
Below is the code that performs the query on page load:
routes.php sends the HTTP get request to a file called AppController.php
routes.php
AppController.php
The page is then made with the following array acquired from DeviceCheckoutController.php
Which then goes to DeviceCheckout.php
I am able to echo $test on the page, and it returns the ID of a new row every time the page is reloaded (which obviously mean the 'insertGetId' query worked). However, I hooked this query up to the page load just to test. What I really want to happen is on click of a button. Here is the code for that:
$("#checkoutFormbox").on('click', '#checkoutButton', function() {
var checkoutInformation = Object();
var accessories = [];
var counter = 0;
var deviceName = checkoutDeviceTable.cell(0, 0).data();
$(".accessoryCheckbox").each(function() {
//add accessory ID's to this list of only accessories selected to be checked out
if($(this).val() == "1")
{
accessories[counter] = $(this).data('id') + " ";
}
counter++;
});
checkoutInformation['deviceID'] = $(".removeButton").val(); //deviceID was previously stored in the remove button's value when the add button was clicked
checkoutInformation['outBy'] = '';
checkoutInformation['outNotes'] = $("#checkOutDeviceNotes").val();
checkoutInformation['idOfAccessories'] = 2;
checkoutInformation['dueDate'] = $("#dueDate").val();
if($("#studentIdButton").hasClass('active'))
{
checkoutInformation['renterID'] = 0;
checkoutInformation['emplid'] = 1778884;
console.log(checkoutInformation);
$.post("http://xxx.xxx.xxx.xxx/testing/public/apps/devicecheckout-checkoutdevices", {type: "checkoutDeviceForStudent", checkoutInformation: checkoutInformation}, function(returnedData) {
alert(returnedData);
});
}
});
Which is also then routed to AppController.php, specifically to the 'checkoutDeviceForStudent' part of the switch statement:
And then back to that query that is shown previously in DeviceCheckout.php
Finally, here is my DB structure for reference:
Any explanation as for why this would be happening? Also, any Laravel or other general best practice tips would be greatly appreciated as I'm inexperienced in usage of this framework and programming overall.
Sorry for such a long post, I hope there is enough information to diagnose this problem. Let me know if I need to include anything else.
Edit: Included picture of error at the top of the page.
Everything is exactly the same, information passed included
No, it isn't. If it was exactly the same you wouldn't be getting the error you're getting.
These sorts of issues are too difficult to solve by taking guesses at what the problem might be. You need to
Setup your system so Laravel's logging errors to the laravel.log file
Setup you PHP system so errors Laravel can't handled are logged to your webserver's error log (and/or PHP's error log)
Put Laravel in debug mode so errors are output the the screen, and the view the output of your ajax request via Firebug or Chrome
Once you have the actual PHP error it's usually pretty easy to see what's different about the request you think is the same, and address the issue.
I found a resolution to my problem after some advice from a friend; much easier than I anticipated and much easier than any solution that has been offered to me here or other places.
Essentially, what I needed to do was place a try, catch clause in my model function, and then if an exception is encountered I store that in a variable, return it, and use console.log() to view the exception. Here is an example to emulate my point:
public function getUserFullname($userID)
{
try
{
$myResult = DB::connection('myDatabase')->table('TheCoolestTable')->select('fullName')->where('userID', '=', $userID)->get();
return $myResult;
}
catch(Exception $e)
{
$errorMessage = 'Caught exception: ' . $e->getMessage();
return $errorMessage;
}
}
And then on the View (or wherever your model function returns to), simply console.log() the output of your POST. This will display the results of the successful query, or the results of the Exception if it encountered one as opposed to an unhelpful Internal Server Error 500 message.

Execute javascript inside the target of an Ajax Call Drag and Drop Shopping Cart without Server language

Well i wanna create an Ajax Drag and Drop Shopping cart using only javascript and ajax. Currently i'm using the example in this page as a stepping stone. Right now it's only with local jquery and it works fine but i want to make the cart work with ajax calls. Note that i do not want to use a server side language( like php, rubby, asp etc), only html and javascript.
My initial thought was that at the $(".basket").droppable i should add an ajax call to another html page containing the "server logic" in javascript, execute in that file all the necessary steps( like reading the get variables (product name, product id and quantity), set a cookie and then return an ok response back. When the server got the "ok" response it should "reload" the cart div with the updated info stored inside the cookie.
If this was with php i would know how to do it. The problem is that as far as i know, you can execute javascript once it reaches the DOM, but how can you execute that js from inside the page that isbeing called upon ? ( thanks to Amadan for the correction)
I've thought about loading the script using $.getScript( "ajax/test.js", function( data, textStatus, jqxhr ).. but the problem with that is that the url GET variables i want to pass to the "server script" do not exist in that page.
I havent implemented all the functionality yet as i am stuck in how to first achieve javascript execution inside an ajax target page.
Below is a very basic form of my logic so far
// read GET variables
var product = getQueryVariable("product");
var id = getQueryVariable("id");
var quantity= getQueryVariable("quantity");
//To DO
//--- here eill go all the logic regarding cookie handling
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
alert('Query Variable ' + variable + ' not found');
}
Any help regarding this matter will be appreciated.
Note: Logic in simple words:
1)have an html page with products+cart
2)Have an "addtocart.html" with the "Cart Server Logic"( being the target of the ajax call when an item is dropped into the product.)
If you have some other idea on this, please enlighten me :)
thanks in advance
Foot Note-1:
if i try loading the scipt using
$("#response").load("ajax/addtocart.html?"+ $.param({
product: product,
id: id,
quantity:quantity
})
);
i get the alert about not being able to find the url parameters( something that i thing is normal as because the content is being loaded into the initial page, from which the request is started, there are no get parameters in the url in the first place)
The problem is that as far as i know, you cannot execute javascript contained in the target of an ajax call, as that page never reaches the browser interpreter.
This is either incorrect or misleading. The browser will execute any JavaScript that enters DOM. Thus, you can use $.load to load content and execute code at the same time. Alternately, you can use hacked JSONP to both execute code and also provide content as a JSON document.
EDIT: Yes, you can't get to the AJAX parameters from JavaScript. Why do you want to? Do you have a good reason for it, or is it an XY problem?
The way I'd do it is this:
$('#response').load(url, data, function() {
onAddedToCart(product, id, quantity);
});
and wrap your JS code in your HTML into the onAddedToCart function.
Depending on what exactly you're doing, it could be simplified even further, but this should be enough to cover your use case.

hide variables passed in URL

We've been working on a web application and we've just about got it finished up, but there's one thing that bothering us (although by no means is it going to stop production.)
When we call one of the pages (index.html), we sometimes have to pass it a variable in the URL (searchid). So we get a page like http://domain.com/index.html?searchid=string.
We'd ideally like to not show the ?searchid=string, but I'm not sure how we'd do that.
My group doesn't own the index.html page (but we are working with the group that does), so I don't know how much we'd be able to do with anything like .htaccess or similar.
I was thinking about POSTing the variable, but I don't know how to receive it with just HTML and jQuery. Another person in my group thought that after the page loaded we could remove it from the URL, but I assume we would need a page refresh which would then lose the data anyway.
I'm trying to avoid XY problem where the problem is X and I ask about Y, so what's the right way to remove the variable from the URL?
You can use the History API, but it does require a modern browser
history.replaceState({}, null, "/index.html");
That will cause your URL to appear as /index.html without reloading the page
More information here:
Manipulated the browser history
Your question seems to indicate that the target page is not and will not be powered by some server-side script. If that's the case, I'd suggest changing the querystring to a hash, which has the advantage of being directly editable without triggering a page-load:
http://yourdomain.com/page.html#search=value
<script type='text/javascript'>
// grab the raw "querystring"
var query = document.location.hash.substring(1);
// immediately change the hash
document.location.hash = '';
// parse it in some reasonable manner ...
var params = {};
var parts = query.split(/&/);
for (var i in parts) {
var t = part[i].split(/=/);
params[decodeURIComponent(t[0])] = decodeURIComponent(t[1]);
}
// and do whatever you need to with the parsed params
doSearch(params.search);
</script>
Though, it would be better to get some server-side scripting involved here.
It's possible to rewrite the URL using JavaScript's history API. History.js is a library that does this very well.
That being said, I don't think there's any need for removing the query-string from the URL, unless you're dynamically changing the contents of the page to make the current query-string irrelevant.
You could post the data, then let the server include the posted data in the page, e.g.:
echo "<script> post_data = ".json_encode($_POST)." </script>";
This works cross-browser.

Can't get json result on my phonegap page

I'm trying to get some json data in my application, but it won't come in the result function.
function myLoad(){
output.innerHTML = 'in the load';// + items;
var myJsonUrl = 'http://....be/.../lineup.php';
$.getJSON(myJsonUrl, function(data) {
output.innerHTML = "IN THE FUNCTION";
});
output.innerHTML = 'END load';
}
In mu output div I can see 'in the load' so it stops at the .getJSON part.
I've included the right jquery libraries (jquery mobile and jquery1.4) and the json from the specified url validates.
What am i doing wrong?
EDIT:
In chrome it works sigh.
I was testing it in Eclipse web browser since I'm working for an Android application.
Apperantly that browser s**ks.
Thx for the idea Sir Troll
=> still can't answer my own question
I might be a bit late in answering this but was working on phonegap and had similar issue. You would need to add the URL in your phonegap.plist file under ExternalHost Array.
I added that and I am now getting JSON data from an external URL.
Hope this helps.
Are you sure you're not getting the data? Your example would most likely overwrite END load with IN THE FUNCTION, since the callback will be executed after the function finishes.
So output.innerHTML would get the values like this:
1. "in the load".
--> Ajax request start
2. "end load"
--> Ajax request finishes
3. "in the function"
I would suggest trying to output data in the callback, and remove the innerHTML changes from outside the callback function.
Is the jsonUrl in the same domain as your script? I'm not really sure, but I think you cannot do cross-domain requests with AJAX scripts.
Update:
Is the php script sending json headers?
header('Content-type: application/json')

Categories

Resources