How to get the CSS-Code and save in a String? - javascript

I am trying to get the code of a CSS-File and save it into a String for later use. I already found something which could do the trick in another post, but nothing I tried was working.
$.ajax({
url: "css/style.css",
dataType: "text",
success: function(cssText) {
}
});
Can anyone help and tell me how to get and save the CSS-Code?
Thanks

Read thejQuery.get() API. Tells you right there.
var myData;
$.get( "your_css.css", function( data ) {
console.log(data);
myData = data;
});
console.log(myData);
Just a warning, due to JavaScript's nature, line 6 may fire off before line 3. Just food for thought.
EDIT
I know the console.log(myData); responds null. I meant it to. I was teaching him that if he does this, make sure that if the data is being manipulated anymore, either force it sync or put it in the callback. A better choice would be to put it in the callback.

If you are getting proper css as response then try using below function :
$.ajax({
url: "css/style.css",
dataType: "text",
success: function(cssText) {
// paste styles to head
$('<style type="text/css"></style>').html(cssText).appendTo("head");
}
});

You can add stylesheet, and disable it with attribute.
var href = "style.css";
$("head").append("<link id='Iwait' type='text/css' href='"+href+"' attribute>");
When you want to use your stylesheet, remove disabled attribute :
$("#Iwait").prop('disabled', false);

Related

Update Span Element with Ajax and php

Hello again stack overflow
I have a simple PHP file (countsomething.php) that looks up a number and echo's it.
How do I get ajax to update a simple span element on my HTML page.
I've tried triggering the ajax on page load with : <body class="skin-blue" onload="updateCDNonts();">
The JS
function updateCDNonts() {
$.get("x.x.x.x:8080/getliveontscdn.php=", function(result){
$("#countonts").html(result)};
}
The HTML
<span id="countonts" class="info-box-number">0</span>
Can someone point me in the right direction ?
You have a few issues with your code i have tried to point them all out below for you:
function updateCDNonts() {
$.get("x.x.x.x:8080/getliveontscdn.php", function(result){ //removed equals from url
$("#countonts").html(result); //removed curly brace that shouldn't be there
}); //added missing bracket and semicolon
Also as someone else noted watchout for cors if your url is different.
I managed to get it working. I changed my php script to return a json, here is the json: {"cdnonts":"144","eagonts":"0","stamonts":null,"foxonts":null,"pentonts":null,"topponts":null,"wickhamonts":null}
And in the html I did the following
<script language="javascript">
window.onload = function() {
$.ajax({
type: 'GET',
url: 'countallonts.php',
dataType: "json",
data: { get_param: 'cdnonts' },
success: function(data){
$('span#cdnonts').html( data.cdnonts);
$('span#eagonts').html( data.eagonts);
}});}
</script>
Although I am not sure why it works, because I expected data variable to return just the "cdnonts" object, but I suspect it parses all of the objects instead?
Thank you for you help.

JSON call giving value that is not actually in the .json file

I am a little new when it comes to JSON and Javascript , so please excuse me if if this is a stupid question, but I have run into a problem that is starting to drive me insane.
On a webpage I am including two scripts; jQuery and a file called "scripts2.js". In the same directory as scripts2.js, I have a JSON file; "settings.json". From within my "scripts2.js" file I am running he following code inside of a function.
var settingsPath = settings.json;
jQuery.getJSON(settingsPath, function (data){
jQuery.each(data, function(index){
console.log("!"+data[index].name);
/*unrelated other stuff */
});
});
Previously the settings.json file looked like this
[
{"name":"Standard Black"},
{"name":"Gold"},
{"name":"Silver"}
]
So naturally when I looked in the Chrome Dev Console the log would print out
!Standard Black
!Gold
!Silver
However, when testing what would happen upon editing my settings.json file I changed "name":"Gold" to "name":"Test".
[
{"name":"Standard Black"},
{"name":"Test"},
{"name":"Silver"}
]
After the json updates I tried refreshing the page but my console log is still printing out
!Standard Black
!Gold
!Silver
...
I am at a loss. I have no idea why the data being retrieved with jQuery.getJSON() is sending the data of my old settings.json even after the changes has been saved. I have perused my .php file (which is generating the HTML) , as well as my included javascript and there is no other mention of another json file or any sort of clone of my json file in any related directory.
I really have no idea what is going on and I am starting to go insane. Does anyone have an idea of what the issue might be?
I dont know if it matters but I am running a XAMPP stack on my localhost. All files (index.php, scripts2.js, and settings.json) are in a directory located inside XAMPP's htdocs folder.
EDIT: Thank you all for the speedy and thorough answers, many of you answered the question I was a bout to ask next. I really appreciate it!
This is because the browser is caching the file from your first request. Simply clear the cache and run it again and the new data will be retrieved.
UPDATE:
To prevent the browser from caching this file, change your AJAX settings like so:
jQuery.ajaxSetup({ cache: false });
Before you make the getJSON call
Try clearing web cache and restart local servers if you have not already
When using jQuery.ajax() instead of the shorthand method, you can disable caching like this:
jQuery.ajax(settingsPath, {cache: false})
jQuery will append a timestamp parameter to your request URL which changes with every request and therefore keeps the browser from caching the response.
To force the browser to get a new version each time you can use cache: false in jQuery.ajax()
$.ajax({
dataType: "json",
url: settingsPath,
cache: false,
success: function (data){
$.each(data, function(index){
console.log("!"+data[index].name);
});
}
});
Pass additional parameter to your requested url which value will change with every request.So,your browser will consider it as new request every time and will not cache the data.
var random = Math.round(new Date().getTime())
var settingsPath = 'settings.json&time=' + random;
jQuery.getJSON(settingsPath, function(data) {
});
});
You can use any algoritham that generate random new value everytime for random for every request.
OR
you can have same things with jQuery#Ajax method
jQuery.getJSON is a shorthand Ajax function, which is equivalent to:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
So, set the optional parameter cache to false (this value by default is always true):
$.ajax({
dataType: "json",
url: url,
data: data,
cache: false, // If set to false, it will force requested pages not to be cached by the browser
success: success
});
Therefore, your getJson becomes:
var settingsPath = settings.json;
jQuery.ajax({
dataType: "json",
url: settingsPath,
data: data,
cache: false,
success: function(data) {
jQuery.each(data, function (index) {
console.log("!" + data[index].name);
/*unrelated other stuff */
});
}
});

JQuery Form No reload : how to pass the $_POST info after success?

First the code below works, but truth be told i don't know why :) it just worked after many trial and errors
I need the $_POST data submitted through the #filter-form, for loading the page as action1 function will require $_POST data.
If i remove +data or .html(data) it doesn't work anymore.
Also if i change url:"..." it does not work anymore either and i don't understand why as i don't need to to anything here, all i need is to load this page.php page and pass the $_POST so that it can output properly.
My QUESTION is, WHY does it work ? (i want to understand why putting +data or html(data) is so important to make sure $_POST is passed) and how can i make it more proper ?
Thanks for your help
<script type="text/javascript">
$("#filter-form").submit(function(event) {
$.ajax({
type: "POST",
url: "includes/page.php?action=action1",
//Specify the datatype of response if necessary
data: $("#filter-form").serialize(),
success: function(data){
alert("succeess");
$("#tableresult").load("includes/page.php?action=action1"+data).html(data);
}
});
event.preventDefault();
return false;
});
</script>';
You don't need to use .load() at all. It should be:
success: function(data) {
alert("success");
$("#tableresult").html(data);
}
This takes the response that the AJAX server returned, which should be HTML code, and puts it into the tableresult element.
The way you had it written, you're calling the server twice, which doesn't seem right.

How do I read a GET variable from JavaScript/jQuery?

How do I get a particular GET variable in JavaScript or jQuery?
I want to pass it on in ajax script in this sort of way:
$.ajax({
url: 'foo/bar.php',
data: {
search: $(this).val(),
page: something //$_GET['page'] only in js
},
...
Check out http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html
what you try is almost correct, but you dont hav to label the data and you have a wron placed } in your code.
$.ajax({
url: 'foo/bar.php',
{
search: $(this).val(),
page: 'something'
},
...
});
for more information, take a look at the documentation.
EDIT: to read your get-variable, just do it like you always do: $s = $_GET['search'];. maybe you have to use $.get instead of $.ajax or set the request type for your $.ajax-call (don't know if it's POST by default, but you should be able to see this using firebug or something similar)

jQuery Ajax HTTP Request INTO a click function - not working

My question is:
Is it possible to do an Ajax request WITHIN a click function, with jQuery? (see example below), If so, what am I doing wrong? Because I'm not being able to do any request (I'm alerting the data through my success function and nothing is being retrieved).
Thank you very much in advance for any help! :)
function tracker(){
this.saveEntry = function(elementTracked, elementTrackedType){
var mode = "save";
var dataPost = "mode="+mode+"&elementTracked="+elementTracked+"&elementTrackedType="+elementTrackedType;
$.ajax({
type: "POST",
url: 'myURL',
data:dataPost,
success:function(msg){
alert(msg);
},
beforeSend:function(msg){
$("#trackingStatistics").html("Loading...");
}
});
return;
},
this.stopLinksSaveAndContinue = function(){
var fileName;
$("a[rel^='presentation']").click(function(e){
fileName = $(this).attr("rel").substring(13);
this.saveEntry(fileName,"Presentation");
})
}
}
If your anchor is linked with the href attribute, then this may be interrupting your AJAX request. A similar problem was recently discussed in the following Stack Overflow post:
window.location change fails AJAX call
If you really want to stick to using AJAX for link tracking, you may want to do the following:
Link
With the following JavaScript logic:
function tracker(url) {
$.ajax({
type: 'POST',
url: 'tracker_service.php',
data: 'some_argument=value',
success: function(msg) {
window.location = url;
}
});
}
Have you considered the possiblity that the request might be failing. If so, you're never going to hit the alert.
Can you confirm that the beforeSend callback is being fired?
Also, I'm assuming 'myURL' isn't that in your real-world source code?
There may also be something awry in the }, that closes your function.
Im guessing some sort of error is being generated. Try adding
error:function(a,b){
alert(a);
},
After 'success'

Categories

Resources