I have simple code in GoogleOauth2.js file
function storedAccsessToken(token) {
$.ajax({
type: "GET",
url: '<%=HttpContext.Current.Request.ApplicationPath %>/SaveToken.ashx?accToken=' + token,
dataType: "text",
complete: function (resp, status) {
if (status == "success" || status == "notmodified") {
if (resp.responseText != '');
alert(resp.responseText);
window.location = window.location;
}
}
});
}
and
function refresh() {
var akkToken = '<%=Session["googleAccToken"]%>';
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + akkToken,
data: null,
success: function (resp) {
user = resp;
alert(user.name);
},
dataType: "jsonp"
});
}
when i put js file in teg head
<head runat="server">
<title></title>
<script type="text/javascript" src="Scripts/jquery-1.8.2.min.js"></script>
<script src="Scripts/GoogleOauth2.js" type="text/javascript"></script>
</head>
and when i start my project and debug js i see that <%=Session["googleAccToken"]%>
compilator understand this as text
but when i put js code in head tag between simple <script type="text/javascript"></script> it work fine and i get my value in session i want to know can i keep this code
in separate file and that it worked fine
Your error is that you have include the <%= %> inside the javascript .js files, and they are not compile to give the results you expect - they stay as they are.
There are two possible solutions to that.
Ether include the variables before the javascript file, ether full move it to the page so the <%= %> can be compile. For example, you can do that :
<head runat="server">
<script type="text/javascript" src="Scripts/jquery-1.8.2.min.js"></script>
<script>
var akkToken = '<%=Session["googleAccToken"]%>';
var UrlTo = '<%=HttpContext.Current.Request.ApplicationPath %>SaveToken.ashx?accToken=';
</script>
<script src="Scripts/GoogleOauth2.js" type="text/javascript"></script>
</head>
and remove the akkToken from the GoogleOauth2.js file, and place url:UrlTo + token on the other line that also have the <%= %>
It's because in the latter case the javascript was processed by .NET. When the script is part of the .NET page the <%= %> tags are processed and replaced by whatever value is calculated.
When the script is an external file, it's requested by the browser separately (and even cached by the browser on subsequent page visits) and so .NET will not be processing it, resulting in the string '<%=Session["googleAccToken"]%>'.
Related
I have a validation in my site that uses a large table (in csv format).
I've tried the following code:
let styleurl = document.getElementById("isthisthestore");
styleurl = styleurl.getAttribute("data-stylesheeturl")
console.log(styleurl);
let data;
$.ajax({
type: "GET",
url: styleurl + "/tambour.csv",
dataType: "text",
success: function(response)
{
data = $.csv.toArrays(response);
console.log(data);
}
});
I'm getting the url from an element i have on the page (I'm sure therre is a better way but that's not the problem...)
I'm getting an error that says:"GET https://correct-file-url/tambour.csv 404"
Any idea why that is?
I have created a file for you see an easy code that work, but an observation is to check the complete "url", for example, when the var will printed on console, copy this url and check it, very important are that dont have any spaces white, or doubles slashs (//), see the example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>An Example for correct csv.toArrays</title>
</head>
<body>
<div id="isthisthestore" style="display: none;" data-id="https://yousiteweb.test/"> </div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/1.0.11/jquery.csv.min.js" integrity="sha512-Y8iWYJDo6HiTo5xtml1g4QqHtl/PO1w+dmUpQfQSOTqKNsMhExfyPN2ncNAe9JuJUSKzwK/b6oaNPop4MXzkwg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script type="text/javascript">
var styleurl = $('#isthisthestore').attr('data-id'); //use jquery to get an url
var styleurl = styleurl+"tambour.csv"; //dont put slashes in the file name if your var url have a slash in the end of string, like data-id="https://yoursiteweb.test/"
console.log('the complete url is: '+styleurl); // check if your url+file is available
let data;
$.ajax({
type: "GET",
url: styleurl, //the var with the csv file
dataType: "html", //type html for use jquery.csv
success: function(response)
{
data = $.csv.toArrays(response);
console.log(data);
}
});</script>
</body>
</html>
King Regards
i simply want the button click to redirect to a different page..
at the beginning my code looked like this :
<asp:Button runat="server" ID="Register_BTN" Text="Register here !"
OnClientClick="Register_BTN_Click();"/>
<script type-"text/javascript">
function Register_BTN_Click() {
window.location.href("Registration.aspx");
}
the error that was thrown : Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.
i have searched about it online and found this question :
JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..."
later i changed the code :
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
$.ajaxSetup({async:true});
function Register_BTN_Click() {
window.location.href("Registration.aspx");
}
and still same exception..
also tried this change and it didn't help..
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
$.ajax({
async: true, // this will solve the problem
type: "POST",
url: "/Page/Method",
contentType: "application/json",
data: JSON.stringify({ ParameterName: paramValue }),
});
function Register_BTN_Click() {
window.location.hash("Registration.aspx");
}
how can i fix this ?
Thanks
window.location.href is a property, not a function, and you should use it like this:
window.location.href = "Registration.aspx";
it works when i change the asp control to an html control
for example :
this solution doesnt work :
<asp:Button runat="server" ID="Register_BTN" Text="Register here !"
OnClientClick="Register_BTN_Click();"/>
<script type-"text/javascript">
function Register_BTN_Click() {
window.location.href="Registration.aspx";
}
but this one does :
<input type="button" value="Register here !" onclick="Register_BTN_Click();" id="Register_BTN" />
<script type="text/javascript" >
function Register_BTN_Click() {
window.location.href = "Registration.aspx";
}
</script>
can someone tell me why when i use the asp control i get this error thrown :
- Synchronous XMLHttpRequest on the main thread is deprecated
I am using an AJAX request to get some data fetched from the database. There are four .js files that I have included in the HTML page. They are
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript" src="scripts/jqueryui.js"></script>
<script type="text/javascript" src="scripts/framework.plugins.js"></script>
<script type="text/javascript" src="scripts/custom.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".buttonid").click(
function(){
$.ajax({ //create an ajax request to load_page.php
type: "POST",
url: "php/fetch_candidates.php",
async: true,
dataType: "html", //expect html to be returned
error: function(){
return true;
},
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
</script>
This doesn't work. But if I remove
<script type="text/javascript" src="scripts/framework.plugins.js"></script>
<script type="text/javascript" src="scripts/custom.js"></script>
then the AJAX starts working. How can I solve this as I need to keep all the .js files in the html page.
There is a responsecontainer div which handles the html afte rthe ajax request. The problem is only with including those two js scripts. TIA
When the other frameworks also use $ function, it might override jQuery's $ functional behaviour. But this leaves the jQuery variable untouched. So try using a closure and execute it inside an IIFE:
(function ($) {
$(document).ready(function() {
$(".buttonid").click(function () {
$.ajax({ //create an ajax request to load_page.php
type: "POST",
url: "php/fetch_candidates.php",
async: true,
dataType: "html", //expect html to be returned
error: function(){
return true;
},
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
})(jQuery);
This will translate all the $ into jQuery's original function and make sure you use $ with only jQuery and not any other framework like PrototypeJS or Scriptaculous.
Try using var jq = $.noConflict(); , just before the $(".buttonid").click(
and use jq instead of $, it looks like a conflict issue, can you please share what is inside the framework.plugins.js and custom.js
Please could someone help me work out how to get started with JSONP?
Code:
$('document').ready(function() {
var pm_url = 'http://twitter.com/status';
pm_url += '/user_timeline/stephenfry.json';
pm_url += '?count=10&callback=photos';
var photos = function (data) {
alert(data);
};
$.ajax({
url: pm_url,
dataType: 'jsonp',
jsonpCallback: 'photos',
jsonp: false,
});
});
Fiddle: http://jsfiddle.net/R7EPt/6/
Should produce an alert, as far as I can work out from the documentation: isn't (but isn't producing any errors either).
thanks.
JSONP is really a simply trick to overcome XMLHttpRequest same domain policy. (As you know one cannot send AJAX (XMLHttpRequest) request to a different domain.)
So - instead of using XMLHttpRequest we have to use script HTMLl tags, the ones you usually use to load JS files, in order for JS to get data from another domain. Sounds weird?
Thing is - turns out script tags can be used in a fashion similar to XMLHttpRequest! Check this out:
script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.someWebApiServer.com/some-data";
You will end up with a script segment that looks like this after it loads the data:
<script>
{['some string 1', 'some data', 'whatever data']}
</script>
However this is a bit inconvenient, because we have to fetch this array from script tag. So JSONP creators decided that this will work better (and it is):
script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.someWebApiServer.com/some-data?callback=my_callback";
Notice my_callback function over there? So - when JSONP server receives your request and finds callback parameter - instead of returning plain JS array it'll return this:
my_callback({['some string 1', 'some data', 'whatever data']});
See where the profit is: now we get automatic callback (my_callback) that'll be triggered once we get the data.
That's all there is to know about JSONP: it's a callback and script tags.
NOTE:
These are simple examples of JSONP usage, these are not production ready scripts.
RAW JavaScript demonstration (simple Twitter feed using JSONP):
<html>
<head>
</head>
<body>
<div id = 'twitterFeed'></div>
<script>
function myCallback(dataWeGotViaJsonp){
var text = '';
var len = dataWeGotViaJsonp.length;
for(var i=0;i<len;i++){
twitterEntry = dataWeGotViaJsonp[i];
text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
}
document.getElementById('twitterFeed').innerHTML = text;
}
</script>
<script type="text/javascript" src="http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=myCallback"></script>
</body>
</html>
Basic jQuery example (simple Twitter feed using JSONP):
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: 'http://twitter.com/status/user_timeline/padraicb.json?count=10',
dataType: 'jsonp',
success: function(dataWeGotViaJsonp){
var text = '';
var len = dataWeGotViaJsonp.length;
for(var i=0;i<len;i++){
twitterEntry = dataWeGotViaJsonp[i];
text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
}
$('#twitterFeed').html(text);
}
});
})
</script>
</head>
<body>
<div id = 'twitterFeed'></div>
</body>
</html>
JSONP stands for JSON with Padding. (very poorly named technique as it really has nothing to do with what most people would think of as “padding”.)
There is even easier way how to work with JSONP using jQuery
$.getJSON("http://example.com/something.json?callback=?", function(result){
//response data are now in the result variable
alert(result);
});
The ? on the end of the URL tells jQuery that it is a JSONP request instead of JSON. jQuery registers and calls the callback function automatically.
For more detail refer to the jQuery.getJSON documentation.
In response to the OP, there are two problems with your code: you need to set jsonp='callback', and adding in a callback function in a variable like you did does not seem to work.
Update: when I wrote this the Twitter API was just open, but they changed it and it now requires authentication. I changed the second example to a working (2014Q1) example, but now using github.
This does not work any more - as an exercise, see if you can replace it with the Github API:
$('document').ready(function() {
var pm_url = 'http://twitter.com/status';
pm_url += '/user_timeline/stephenfry.json';
pm_url += '?count=10&callback=photos';
$.ajax({
url: pm_url,
dataType: 'jsonp',
jsonpCallback: 'photos',
jsonp: 'callback',
});
});
function photos (data) {
alert(data);
console.log(data);
};
although alert()ing an array like that does not really work well... The "Net" tab in Firebug will show you the JSON properly. Another handy trick is doing
alert(JSON.stringify(data));
You can also use the jQuery.getJSON method. Here's a complete html example that gets a list of "gists" from github. This way it creates a randomly named callback function for you, that's the final "callback=?" in the url.
<!DOCTYPE html>
<html lang="en">
<head>
<title>JQuery (cross-domain) JSONP Twitter example</title>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.getJSON('https://api.github.com/gists?callback=?', function(response){
$.each(response.data, function(i, gist){
$('#gists').append('<li>' + gist.user.login + " (<a href='" + gist.html_url + "'>" +
(gist.description == "" ? "undescribed" : gist.description) + '</a>)</li>');
});
});
});
</script>
</head>
<body>
<ul id="gists"></ul>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>An JSONP example </title>
</head>
<body>
<!-- DIV FOR SHOWING IMAGES -->
<div id="images">
</div>
<!-- SCRIPT FOR GETTING IMAGES FROM FLICKER.COM USING JSONP -->
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
format: "json"
},
//RETURNED RESPONSE DATA IS LOOPED AND ONLY IMAGE IS APPENDED TO IMAGE DIV
function(data) {
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
});
});</script>
</body>
</html>
The above code helps in getting images from the Flicker API. This uses the GET method for getting images using JSONP. It can be found in detail in here
I'm trying to pass a variable from my jQuery code to my HTML/PHP code using AJAX and POST, but I get the error message "Notice: Undefined index: testData in C:\xampp\htdocs\teszt\test1.php on line 9".
I'm using XAMPP, I'm running the code in localhost, I'm using Mozilla Firefox and here's my HTML/PHP code (test1.php):
<!DOCTYPE html>
<html lang="hu">
<head>
<title>Test</title>
<meta http-equiv="Content-type" content="text/html;charset=utf-8">
</head>
<body>
<?php echo "<p class='testParagraph'>" . $_POST['testData'] . "</p>";?>
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
And here's my jQuery code (script1.js):
$(document).ready(function() {
var temporaryVariable = "temporary variable";
$.ajax({
type: "POST",
url: "test1.php",
data: { testData:"2" },
success: function (result) {
alert('success');
}
}).done(function() {
$('.testParagraph').addClass( temporaryVariable );
});
});
What I tried changing so far (but didn't work of course):
test1.php:
charset was previously iso-8859-2
GET instead of POST in both codes
commenting out the script tag includes
script1.js:
commenting out the $(document).ready(function() {... lines
in data: I tried changing the quote symbols from ' to " or no quote symbols at all
commenting out the success: function... line and the two lines below it
Also, when I run the PHP code, the p tag gets the temporaryVariable class from the jQuery code.
Still, I get the error message written above. I would appreciate any help I get.
Change your test1.php to:
<!DOCTYPE html>
<html lang="hu">
<head>
<title>Test</title>
<meta http-equiv="Content-type" content="text/html;charset=utf-8">
</head>
<body>
<p id='testParagraph'> </p> <!-- You receive the value by jquery not from PHP. -->
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
And your script1.js to:
$(document).ready(function() {
var temporaryVariable = "temporary variable";
$.ajax({
type: "POST",
url: "test1.php",
data: { testData:"2" },
success: function (result) {
alert('success');
}
}).done(function() {
$('#testParagraph').html(temporaryVariable); //The value is inserted into the paragraph.
});
});
Hope works for you.
Unless you are getting the php page from a post request, using $_POST['testData'] will be of no use and will always give an index not found error. If you want to set the value in the p tag from jquery, you could use $('.testParagraph').html( temporaryVariable ) instead of .addClass
Use data : 'testData=2',
Instead of data : {testData:"2"},
Notice: Undefined index: testData in C:\xampp\htdocs\teszt\test1.php
on line 9
means your
data: { testData:"2" },
is wrong.
Didn't test it, but this should work:
data: [ testData:"2" ],
because $_POST is an Array
It sounds like you're posting test1.php to itself, and it's not clear why you would do that.
As #Rasclatt has pointed out in the comments check to see if the data exists before you try to access it.
Change:
<?php echo "<p class='testParagraph'>" . $_POST['testData'] . "</p>";?>
To:
<?php
if( isset( $_POST['testData'] ) ) {
echo "<p class='testParagraph'>" . $_POST['testData'] . "</p>";
}
?>
If, however, test1.php is a different script altogether then make the following changes:
Include a placeholder for the ajax content in your HTML:
<p class="tetParagraph"></p>
Trim and edit your JavaScript to the following:
$(document).ready(function() {
var tempVal = "temporary variable";
$.ajax({
type: "POST",
url: "test1.php",
data: { testData:"2" },
success: function (result) {
tempVal = result;
$('.testParagraph').html( tempVal );
alert('success');
}
});
});