I am trying to store JSON data I am retrieving via AJAX in a jQuery cookie. I am using the following plugin: https://github.com/carhartl/jquery-cookie to achieve this. The plugin works great when I am storing non JSON objects.
I can see it is working perfectly when storing simple strings. However, when I try to store my JSON data that I get from my AJAX call, the cookie is not saving. Here is my relevant code:
$.ajax({
dataType: "json",
url: "http://www.example.com/sandbox/BF/context/messagesNew.php",
success: function(data) {
//This works
$.cookie('Name', 'John');
console.log($.cookie('Name'));
//This does not work
$.cookie("test-data", JSON.stringify(data));
var myJSONCookie = JSON.parse($.cookie("test-data"));
console.log(myJSONCookie); // Returns error in console: SyntaxError: JSON Parse error: Unexpected identifier "undefined"
}
});
I have tried several other snippets of code but none have worked properly. I do not even think that test-data is being created as a cookie because when I logged the entire $.cookie(); to the console, my cookie called Name appears but test-data does not.
The value you are trying to put in your cookie is way too large for a cookie. Cookies are limited to around 4k. Part of this is for storage management and part of this is because every request to a server sends all the cookies with it. If you stored a 9MB cookie, you'd be sending an extra 9MB with every single page or ajax request to that server which would obviously be a disaster.
LocalStorage is another option that has larger storage limits, is still partitioned per domain and does not have the issue with sending large things to the server on every request.
If LocalStorage is not large enough also, then you can start considering only modern browsers that contain something like IndexedDB which you can read about here.
You probably need a different design approach. We could probably help with ideas for a different approach, but would have to understand the overall problem you're trying to solve and why you need to store 9MB locally and cannot just retrieve it from the server when needed in the future?
Related
so I made a Chrome extension whose whole purpose is fetching certain data from the backend and process it to do stuff on a certain domain that the user visits.
I'm trying to have it published but it's getting rejected, and this is what they told me:
Your item was found to have requested/fetched one or more external scripts. An example of one such instance in your item was backend URL in background.js. Please remove all external fetches including Json type.
(This is actually the last of 3 emails they sent me, they just added a few more words in this part I quoted with every email... Since they send only one per day, it's very frustrating...)
I use jQuery.ajax in my background script, and after searching with google I found out that by default it tries to process json requests as jsonp requests (I'm not 100% sure though...), so I've set the jsonp property to false in every ajax call in my code. My extension still got rejected today, and they didn't send another email, so I'm just gonna guess they really did mean that I need to remove that call that fetches json from my backend.
Here's an example of an ajax call in my code:
$.ajax({
url: backendUrl + '/theendpoint',
data: {
paramName: 'paramValue'
},
dataType: 'json',
cache: false,
jsonp: false
})
I'm pretty sure that I'm supposed to be allowed to do it. I've also searched to make sure, and other people do it too. So, what could actually be wrong?
I know it's hard by seeing hardly any code, but there's too much of it and the problem is just here in the ajax calls. And I can't post here the content of my manifest file.
I did add my backend to the permissions in the manifest. Do I have to add it to the content_security_policy too, even though I'm just fetching json from it, and not scripts?
Thanks for any help.
Edit: side question: is it mandatory to provide a physical adress and a link to a privacy policy in my developer account? If yes, could that be the reason why the extension keeps getting rejected? (Last time it got rejected, they didn't even send me an email)
(I'm not sure if I should post this as an answer, but)
Today I tried insisting again saying that json isn't a script and that I was supposed to be able to fetch it from my backend. I don't know if it was a coincidence but right after sending the email, I received another one saying this:
Thank you for reaching out to us.
Upon a subsequent review, we’ve reinstated your item and it will be available in the Chrome Web Store within 30 minutes.
Thank you for your cooperation,
Chrome Web Store team
I also must add that I did use this support form to ask for help. Maybe that's what actually did something.
Moral of the story: if your extension is getting mistakenly rejected, keep insisting and explain what you did and why it's valid...
Now, I've only gotta understand why it got immediately taken down from the store...
Edit: My extension was also taken down by mistake, they reinstated it after I used the support form to ask for the reason. So yeah, use that support form, it actually gets things done.
I want to push an data to array in external local JSON file using jQuery.
So any ideas?
I have tried this:
$.getJSON('test.json', function(data) {
data.push('Something');
});
And it wont be pushed into local JSON file
You can do this in JavaScript with node.js (or a multitude of other languages/platforms) but not with a browser & jQuery.
Here's how to read and write a json file in node.js
On the other hand, users could upload a JSON file to your server, where you modify the structure and send them a modified JSON file back as a download.
Is not possible to write files using Javascript (can cause security problems through xss, csrf ..)
No, JavaScript doesn't have access to writing files as this would be a huge
security risk to say the least. If you wanted to get/store information server-
side, though, you can certainly make an Ajax call to a PHP/ASP/Python/etc.
script that can then get/store the data in the server. If you meant store data
on the client machine, this is impossible with JavaScript alone. I suspect
Flash/Java may be able to, but I am not sure.
If you are only trying to store a small amount of information for an
unreliable
period of time regarding a specific user, I think you want cookies. I am not
sure from your question what you are trying to accomplish, though.
Read/write to file using jQuery
You cannot access the files in a local client's machine. May be for development setup you can do it. But before you need to restart the browser with file-access flag set.
You can see my answer here that describes the opening browser setup with the flag set.
Then, you can use the following code to read the data.
var data = [];
var url = "/Users/Vignesh/Desktop/test.json";
var req = new XMLHttpRequest();
req.open("GET",url,true);
req.onreadystatechange=function(){
if(req.readyState === 4)
{
data = JSON.parse(req.responseText);
}
};
req.send();
To write into the file you may look into this. (Not sure it is working or not)
I am building a module for SugarCRM that will be used by many people. Early on I ran into a probelm when saving data with PHP losing part of the POST, I learned that the problem was caused by the PHP INI Setting for max_input_vars
Once I increased the value set for max_input_vars, everything worked perfect again.
I was able to set the max_input_vars value with an .htaccess file. I have ready that you cannot set this value with the PHP function ini_set()
My major concern is this module will be used on many different servers as it will be used by many people.
I need to code a solution that will require the user to do nothing and still have my module continue to function correctly.
On another post a user had recommended that I change my HTML Form which already saved this data using a jQuery AJAX POST to my backend PHP script.
He says that I should change it to save the data by s ending a JSON object to my PHP backend script instead of the large number of POST Vars.
Does anyone else see this as a good solution?
Here is my current frontend code that handles the SAVE now....
function ajaxSaveTasks(){
window.unsavedChanges = false;
// Display a message to the user that we are Saving
ajaxStatus.showStatus('Saving Task Changes');
var url = "index.php?module=apoll_Web_Projects"; // the script where you handle the form post.
//SUGAR.ajaxUI.showLoadingPanel();
jQuery('#project_tasks').showLoading(showLoadingSettings);
$.ajax({
type: "POST",
url: url,
data: $("#editTasksForm").serialize(), // serializes the form's elements.
success: function(data)
{
//alert(data); // show server response
//SUGAR.ajaxUI.hideLoadingPanel();
hideTaskUnSavedChangesHeaderBar()
jQuery('#project_tasks').hideLoading();
}
});
ajaxStatus.hideStatus();
};
The other user mentions that if this code is modified to POST my FORM using JSON instead that I can get around the max_input_vars issue altogether. If I understand correctly, he is saying that instead of my 1,000+ Form POST variables being sent, it will send it as 1 variable which holds a huge giant JSON string instead...does that sound right?
If this sounds like it could be a good solution, then could someone show me how I might achieve this?
My FORM is a page for Mass Adding and Editing Project Task Database records, so it can be very large and have hundreds of Task records to update in the database.
In the code above you can see that it simply runs $("#editTasksForm").serialize() to get all the Form fields.
I have a page where people can login and their login request is sent with jQuery's $.ajax to a processing page. On that page all of the errors collected during the login attempt are stored in $_SESSION['error'].
How can I access this variable to alert users of the errors after the attempt is made. I know how to access a session variale, I mean how do I access a php variable without reloading the page. The only way I currently am aware of is to inject them on page load, but there must be some way to access them with JavaScript after they have changed due to an Ajax request.
Unfortunately you cannot directly access the PHP $_SESSION[] array from JavaScript. This is by design, because one of the major points of using a Session, is that the data is saved on the server side, unmodifiable by the end user, and therefore your Javascript.
What you could do however, is include the error list in your ajax response. Chances are you are doing an ajax request that returns a 'json' type format. Just include your error list in your json returned, and use the JavaScript to display them. I recommend not sharing the entire $_SESSION array, since it could give away some key information about the interworkings of your PHP.
Also, if you are not currently doing an ajax request that expects json, back, then consider switching it up so that you are expecting and returning json. You can provide much more hidden data this way, instead of just some HTML or text.
Hope this helps
I want to send some data from one HTML page to another. I am sending the data through the query parameters like http://localhost/project/index.html?status=exist. The problem with this method is that data remains in the URL. Is there any other method to send the data across HTML pages using JavaScript or jquery.
why don't you store your values in HTML5 storage objects such as sessionStorage or localStorage, visit HTML5 Storage Doc to get more details. Using this you can store intermediate values temporarily/permanently locally and then access your values later.
To store values for a session:
sessionStorage.setItem('label', 'value')
sessionStorage.getItem('label')
or more permanently:
localStorage.setItem('label', 'value')
localStorage.getItem('label')
So you can store (temporarily) form data between multiple pages using HTML5 storage objects which you can even retain after reload..
I know this is an old post, but figured I'd share my two cents. #Neji is correct in that you can use sessionStorage.getItem('label'), and sessionStorage.setItem('label', 'value') (although he had the setItem parameters backwards, not a big deal). I much more prefer the following, I think it's more succinct:
var val = sessionStorage.myValue
in place of getItem and
sessionStorage.myValue = 'value'
in place of setItem.
Also, it should be noted that in order to store JavaScript objects, they must be stringified to set them, and parsed to get them, like so:
sessionStorage.myObject = JSON.stringify(myObject); //will set object to the stringified myObject
var myObject = JSON.parse(sessionStorage.myObject); //will parse JSON string back to object
The reason is that sessionStorage stores everything as a string, so if you just say sessionStorage.object = myObject all you get is [object Object], which doesn't help you too much.
possibly if you want to just transfer data to be used by JavaScript then you can use Hash Tags
like this
http://localhost/project/index.html#exist
so once when you are done retriving the data show the message and change the
window.location.hash to a suitable value.. now whenever you ll refresh the page the hashtag wont be present
NOTE: when you will use this instead ot query strings the data being sent cannot be retrived/read by the server
Well, you can actually send data via JavaScript - but you should know that this is the #1 exploit source in web pages as it's XSS :)
I personally would suggest to use an HTML formular instead and modify the javascript data on the server side.
But if you want to share between two pages (I assume they are not both on localhost, because that won't make sense to share between two both-backend-driven pages) you will need to specify the CORS headers to allow the browser to send data to the whitelisted domains.
These two links might help you, it shows the example via Node backend, but you get the point how it works:
Link 1
And, of course, the CORS spec:
Link 2
~Cheers