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)
Related
I'm trying to take the result of my console log and put it in a div. The console log bit works, but not putting it in a div. According to the online tutorials it should be something like this:
<div id="number">Test</div>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function () {
var data;
$.ajax({
type: 'POST',
dataType: 'json',
url: 'report.php',
data: data,
success: function (data) {
console.log(data.report.data[0].breakdown[0].counts);
$('#number').innerHTML = data.report.data[0].breakdown[0].counts;
}
});
});
</script>
However I get no log errors, it just doesn't update the text.
use
$('#number').html(data.report.data[0].breakdown[0].counts)
instead of .innerHTML
Since you using jQuery Selector $, you need to use $('#number').html("text or something").
Or maybe you can do document.querySelectorAll("#number").innerHTML = "text or somthing" if you want to use Vanila Javascript.
$('#number') is a jquery object, .innerHTML works on a DOM object - they are not the same thing.
Either convert $('#number') to DOM, with:
$('#number')[0].innerHTML = data.report.data[0].breakdown[0].counts;
Or use jquery method:
$('#number').html(data.report.data[0].breakdown[0].counts);
I'm trying to fetch a JS array created by a PHP file and re-use the JS array in a JS script in the page. I have tried many different solutions found on this site but none seems to work but I don't know what the issue is with my script.
I have a PHP file that echoes the following:
[["content11", "content12", "content13", "content14","content15"],
["content21", "content22", "content23", "content24","content25"]]
I'm using a simple Ajax get to retrieve the data:
$.ajax({
type: "GET",
url: myUrlToPhpFile,
dataType: "html",
success : function(data)
{
result = data;
alert (result);
}
});
The alert displays the expected output from the PHP file but if I now try to access the array like result[0], it outputs "[" which is the first character. It looks like JS sees the output as a string rather than an array.
Is there something I should do to make JS understand it's a JS array?
I have seen many solution with JSON arrays but before going into this direction, I'd like to check if there are simple solutions with JS arrays (this would prevent me from rewriting too much code)
Thanks
Laurent
In you php file you need check that your arrays echos with json_encode.
echo json_encode($arr);
And in your javascript file:
$.ajax({
type: "GET",
url: myUrlToPhpFile,
dataType: "html", // json
success : function(data)
{
var res = JSON.parse(html);
alert(html); // show raw data
alert(res); // show parsed JSON
}
});
You can use JSON.parse to format the string back into an array.
JSON.parse(result)[0]
or
var result = JSON.parse(result);
result[0];
#Rho's answer should work fine, but it appears that you're using jQuery for your AJAX call, which gives you a shortcut; you can use $.getJSON instead of $.ajax, and it will read the data as JSON and provide you with the array immediately.
$.getJSON(myUrlToPhpFile, function(result) { ... });
This is really just a short way of writing what you already have, but with a dataType of json instead of html, so you could even do it that way if you prefer. This is all assuming that you're using jQuery of course, but your code was following their API so it seems a good bet that you're either using jQuery or something compatible.
I'm stuck on this odd syntax error pointing to the colon in the first key:value pair of the json return. JSONLint.com says the json is valid. Can anyone help? JSFiddle linked below. Thanks
http://jsfiddle.net/gbkester/hgt8bvb8/
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://forecast.weather.gov/MapClick.php?lat=38.14000&lon=-78.45000&FcstType=digitalJSON",
dataType: 'jsonp',
success: function (json) {
console.log(json)
}
})
})
Doesn't seem to me that this response is actually JSONP. It looks like straight JSON.
Typically JSONP endpoints accept a callback= URL parameter. The value of this parameter is used to name a function that wraps the actual object. So, for example:
http://example.com/api/endpoint?callback=foobar
would return something like:
foobar({"key":"value"});
You can see jQuery trying this in the Fiddle:
http://forecast.weather.gov/MapClick.php?...&callback=jQuery11100967190676368773_1409103826888&_=1409103826889
The callback= is naming the function that it would like to see returned, and the _= is an attempt at cache busting. It wants to see a response that looks like:
jQuery11100967190676368773_1409103826888({ ... });
Adding or removing this parameter doesn't seem to change the response content. Not having the API docs handy, it's possible that they use a different parameter for this. If, for example, they used bazquux as the parameter, you could change your request to:
$.ajax({
...
url: "http://forecast.weather.gov/MapClick.php?lat=38.14000&lon=-78.45000&FcstType=digitalJSON&bazquux=?",
...
})
Note the literal &bazquux=?.
You're missing semicolons:
After console.log(json)
After the closing round bracket of the ajax block
After the closing round bracket of 'ready' function
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);
If I have an array like
price=["1#1000", "1000#2000"]
how to convert it into JSON so that it can be send into ajax call of jQuery
$.ajax({
type: 'POST',
url: '',
data: {
'price': price
},
dataType: 'JSON',
success: function(data) {
console.log("success");
console.log(data);
var products = data.products;
console.log(products);
},
});
Since you already posted...parts of jQuery, here is a jQuery plugin that should do it
http://plugins.jquery.com/plugin-tags/stringify
|EDIT| The jQuery-plugins-site is put down for a while.
Anyways, you a looking for a function called Stringify. You can read more about it here:
http://www.json.org/js.html
A simple google-search should give you plenty results.
When writing price=["1#1000", "1000#2000"] you already have your data represented as a javascript array.
It should be possible for you to simply pass this as an argument as you have described within your use of the $.ajax method.
Alternatively (if you really need to parse price as a json object) see the jQuery builtin function for this: http://api.jquery.com/jQuery.parseJSON/
But recheck that this is not just possible, as you have described it, if not, what errors are you getting?