Before, I had this:
<head>
<script src="/Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
var optPrompt = "- Select One -";
var subCats;
var parentCats;
var nextBtn;
var ParentChanged = function() {
ClearDescription();
if (this.selectedIndex == 0) {
$(subCats).html($("<option>").text(optPrompt));
}
$.getJSON('<%=Url.Action("GetChildCategories") %>', { parentId: $(this).val() },
function(data) {
subCats.options.length = 0;
$("<option>").text(optPrompt).appendTo(subCats);
$(data).each(function() {
$("<option>").attr("value", this.ID).text(this.Name).appendTo(subCats);
});
});
}
var DisplayDescription = function(catId) {
$.ajax({
url: '<%=Url.Action("GetDescription") %>',
data: { categoryId: catId },
dataType: 'html',
success: function(data) {
$("p#categoryDescription").html(data);
}
});
}
var ChildChanged = function() {
var catSelected = this.selectedIndex != 0;
if (!catSelected) ClearDescription();
else DisplayDescription($(this).val());
}
var ClearDescription = function() {
$("p#categoryDescription").html('');
}
$(function() {
parentCats = $("select#Category").get(0);
subCats = $("select#Subcategory").get(0);
nextBtn = $("input#nextButton").get(0);
$(parentCats).change(ParentChanged);
$(subCats).change(ChildChanged);
});
</script>
</head>
Then I put all of my inline script into a file (myScript.js) and changed my HTML to this:
<head>
<script src="/Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="/Scripts/myScript.js" type="text/javascript"></script>
</head>
And now nothing is working. I opened up my page in IE7 and it had a page error that read:
Line: 54
Error: Unknown name.
Line 54 happens to be the last line of my external javascript file.
What am I doing wrong?
Am I right in saying that this is ASP.Net? If it is, inline scripts like:
<%=Url.Action("GetDescription") %>
cannot go in the external JavaScript file.
Did you put the < script > tag inside your myScript.js? If yes, remove them.
Your myScript.js should start with
var optPrompt = "- Select One -";
Since you are now serving the js as a static file, rather than via your ASP, lines like
<%=Url.Action("GetChildCategories") %>
will no longer work as the server doesn't interpret them and replace them with the correct values. You'll need to hard-code them in the script, or leave those lines as inline scripts in the main page and set them as global variables which you can then reference from the external file.
Related
Briefly, i work on to create a Wordpress plugin. In this plugin, i need a progress bar that moving on according to background process. So, I determined a specific php file which contains my custom functions. Let's call this 'func.php' . Also, there is a file that acts as plugins main page file. We can call it 'main.php' .
So; I designed a concept in my head. On the main page, when I click begin button (named 'buttonbegin'), a jquery post being sent to func.php . I can control this POST value with these codes in func.php:
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'buttonbegin':
func1();
break;
case 'otherbutton':
func2();
break;
}
}
After it, func1 executes. In this function, i had these codes for testing:
function func1() { ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
var itemnumber=0;
for (var i = 1; i <= 3000; i++) { //it should be execute 3000 times because of nature of process
itemnumber++;
if (itemnumber == 30) {
var value = "mystring";
var ajaxurl = 'fullurl+pluginsdirectory/main.php', //func.php and main.php are in same folder
data = {'action': value};
$.post(ajaxurl, data, function (response) {
});
itemnumber=0;
}
}
});
</script>
<?php
}
At this point in this func1, I wanna do another jquery post to make a trigger mechanism for progress bar on main.php . And finally, there is some javascript code to control this last jquery post and expand 1% progress bar. Here is the script codes in main.php :
<script type="text/javascript"> //below are for the first process i told
var width = 0;
var addition = 1;
jQuery(document).ready(function($) {
$('#buttonbegin').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'fullurl/func.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
});
});
//actual part starts here
var continuous = setInterval(function() {
var code = <?php echo !isset($_POST['action']) ?>; // the source of the problem
if(!code) {
var percent = $("#myBar").width() / $("#myBar").parent().width() * 100;
if (percent == 100) {
clearInterval(continuous);
}
var element = document.getElementById("myBar");
element.style.width = (width+addition) + "%";
element.innerHTML = (width+addition) * 1 + "%";
width = width + addition;
}
}, 1000);
});
</script>
But it doesn't work. When i print the 'code' variable with console.log, I see NaN value. The php code inside script tags doesn't work properly. Is there any mistake? Or is there another simpler way to do whole process?
Note: Necessary jquery cdn links are included in main.php and func.php both. This is how its look like:
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</head>
I am facing this problem, and i cannot figure it out. Its simple thing, i need to include my js file into a head. But in my page I've got error Uncaught SyntaxError: Unexpected token '<' in ShopData.js:1 . So I've checked that file in chrome inspector, and i see that there is no JS content inside of it. It basically clone the html file and include it as js. How this can even happen and what is the solution? In ShopData.js is pure JS content, no includes or something. I've already checked permissions for that files and set it to read/write but no result, whole page is in domain hosting. Thanks for any advice.
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="ShopData.js"></script>
</head>
JS File:
var ShopID = 0;
var Name = "";
var City = "";
var Street = "";
var PostCode = "";
var State = "CZ";
var Longitude = "";
var Lattitude = "";
var Email = "";
var Telephone = "";
var Tittle = "";
var Description = "";
var Keywords = "";
var Barbers;
var OpeningHours;
var ItemTypes;
var Items;
let ShopData = {};
jQuery.ajax({
type: "GET",
url: "https://example.com/",
dataType: "json",
success: function(response) {
console.log(response);
}
});
Screenshot of response
This file isn't valid JavaScript so it will give that error:
https://barber.minuto.cz/web/ShopData.js
Also it seems to give that response no matter which URL you type in:
https://barber.minuto.cz/web/asdfasdf
Also you may want to make it so everyone can't login here since it is out in public now:
https://barber.minuto.cz
As I asked here I would like to know how I could pass the data from a simple JS function to php, and log it there.
I found this answer and tried to follow it. This is my code right now (both in the same file)
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"> </script>
</head>
<body>
<script>
function getClientScreenResolution() {
var screenResolutionW = screen.width;
var screenResolutionH = screen.height;
console.log(screenResolutionW + ' ' + screenResolutionH)
$.post("index.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
}
</script>
<script type="text/javascript">
getScreenResolution();
</script>
</body>
</html>
<?php
$screenResolutionW = $_POST['screenResolutionW'];
$screenResolutionH = $_POST['screenResolutionH'];
if(isset($_POST['screenResolutionW'])) {
$fh = fopen('log.txt', 'a');
fwrite($fh, 'Screen res: '."".$screenResolutionW .'x'."".$screenResolutionH
."\r\n");
fclose($fh);
}
?>
However, this does not work.
I wouldn't know how to fix this, whenever I try to google this problem people use more advanced methods, that I wouldn't even know how to start with.
Edit: My PHP and HMTL are in the same file (index.php).
Edit 2: Removed old code for clarity.
This results in these error messages:
Notice: Undefined index: screenResolutionW in index.php on line 153
Notice: Undefined index: screenResolutionH in index.php on line 154
What you want to do with $.post is include your data like this:
$.post("index.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
where the first of the pair is the POST identifier (the ['screenResolutionW']) and the second of the pair is the variable value.
You will also want to change your POST identifiers to be quoted:
$screenResolutionW = $_POST['screenResolutionW'];
$screenResolutionH = $_POST['screenResolutionH'];
Otherwise, you will get a warning about constants. I have also corrected the spelling in these variables, to reflect what you're trying to write into your file.
fwrite($fh, 'Screen res: '."".$screenResolutionW .'x'."".$screenResolutionH ."\r\n");
EDIT
Part of the problem is that you never call the function to execute it. Here is your HTML with the additions I have suggested, plus calling the function:
EDIT TWO
Added an onload handler for the document:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"> </script>
</head>
<body>
<script>
function getScreenResolution() {
var screenResolutionW = screen.width;
var screenResolutionH = screen.height;
console.log(screenResolutionW + ' ' + screenResolutionH);
$.post("index.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
}
</script>
</body>
<script type="text/javascript">
$(function() {
getScreenResolution();
});
</script>
</html>
OTHER NOTES
You really should separate the PHP code and place it in a different file because when you run the page as it is now you should get one line logged that has no variables when the page initially runs, then one logged line when the JavaScript fires after the page loads.
Then once separated you should not run your PHP until you test for the existence of a variable, for example:
if(isset($_POST['screenResolutionW'])) {
// your code to write to the file here
}
EDIT THREE
I placed all of the JavaScript in the same script block in the head of the file and have tested again:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"> </script>
<script type="text/javascript">
$(function() {
function getScreenResolution() {
var screenResolutionW = screen.width;
var screenResolutionH = screen.height;
console.log(screenResolutionW + ' ' + screenResolutionH);
$.post("post_test.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
}
getScreenResolution();
});
</script>
</head>
<body>
</body>
</html>
Here you can see the variables are being posted:
Adapting the others answers.
try it:
function getScreenResolution() {
"http://example.com/index.php", screenResolutionW + screenResolutionH
$.ajax({
url: '/index.php',
method: 'POST',
data: {
screenResolutionW : screen.width,
screenResolutionH : screen.height
},
success: function(data) { console.log(data); }
});
}
And in your PHP
$screenResolutionW = $_POST['screenResolutionW'];
$screenResolutionH = $_POST['screenResolutionH'];
echo $screenResolutionW . " - " . $screenResolutionH;
you have to use serialize the array before doing post request.
var screenResolutionW = screen.width;
var screenResolutionH = screen.height;
var serializedArr = {
width: screenResolutionW,
height: screenResolutionH
};
$.post('/index.php', serializedArr, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
In the server end, you will get values in $_POST variable.
Apart of all those mistakes you have discovered thanks to other replies, you have these:
$screenResoltuionW = ...
Notice you wrote "ltuion" and in the fopen command you have it correct. screenResolutionW
Same thing with $screenResoltuionH...
That's why you don't get any value in the file, because those variables doesn't exists.
I have a header.html and header.js files because I want to use the same header through my webpages.
In header.js file, on window load I want it to console.log("header file loaded").
I also have index.html and index.js file for my homepage. In index.js, on window load I want it to console.log("index file loaded")
I called header.html in index.html file, in order to import the header for the homepage. This works fine.
based on js files the console output should
header file loaded
index file loaded
The problem I am having is that
it seems like header.js and index.js cannot work simultaneously
only the last referenced file gets outputed in the console
for example this format
<script src="js/header.js"></script>
<script src="js/index.js"></script>
will output
index file loaded
and this
<script src="js/index.js"></script>
<script src="js/header.js"></script>
will output
header file loaded
I use the code to import header.html in index.html
<head>
<div data-include="header"></div>
</head>
<body>
<script>
$(function(){
var includes = $('[data-include]');
jQuery.each(includes, function(){
var file = $(this).data('include') + '.html';
$(this).load(file);
});
});
</script>
</body>
this is the content of both js file
function retrieveInfo(data) {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
var userId = firebase.auth().currentUser.uid;
return firebase.database().ref('/Sellers/' + userId).once('value').then(function(snapshot) {
console.log(userId)
console.log("index file loaded")
});
}
})
}
what am I doing wrong and how can I fix it to have both js file called?
You are doing it in a wrong way, .load() is used for loading HTML contents. You should be using .getScript(), to load the js and execute it.
According to docs:
.load()
Load data from the server and place the returned HTML into the matched element.
.getScript()
Load a JavaScript file from the server using a GET HTTP request, then execute it.
Here is an example for using getScript:
$.ajax({
url: url,
dataType: "script",
success: function() {
alert("script loaded");
}
});
In your case it would be:
$(function(){
var includes = $('[data-include]');
jQuery.each(includes, function(){
var JS = $(this).data('include') + '.js';
var file = $(this).data('include') + '.html';
$(this).load(file);
$.ajax({
url: JS,
dataType: "script",
success: function() {
alert(file + " loaded");
}
});
});
});
Why am I getting this error, when I'm trying to get a response from a file on my own server?
$.get("http://www.example.com/user.php?q=" + client + "", function(response) {
if(response == "invalid"){
console.log("invalid login");
return;
}
And btw, the string client is mentioned already in the code.
And jquery is included.
http://i.gyazo.com/693e6633d211ab6da79598e75c6dde58.png
I have solve the problem like this ( i have jquery loaded async so i check if is defined and then get a css...etc..)
<script id="jquery" type='text/javascript' async defer src='//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js?ver=1.8.3'></script>
<script type='text/javascript'>
(function checkJQuery(){
if ('undefined' == typeof window.jQuery) {
setTimeout(function(){checkJQuery();},250);
}else{
var css = "url-of-my-css";
console.log("my css is loading");
window.jQuery.get( css, function( data ) {
$('<style>'+ data +'</style>').appendTo(document.getElementsByTagName('head')[0]);
console.log("css loaded");
});
var js = document.createElement('script');
js.type = 'text/javascript';
js.async = 'async';
js.defer = 'defer';
js.src = 'url-of-my-js';
var node = document.getElementsByTagName('script')[1];
node.parentNode.insertBefore(js, node);
}
})();
</script>
Changing $.get to window.JQuery.get
Hope this help.
I had a problem like this in asp.net mvc 5.
<script>
function OpenBulkUpload() {
$.get("/AdminPanel/BulkUpload/Index").then(
function (r) {
$("<div id='DivBulkUpload'></div>").html(r).dialog(
{
width: 'auto', height: 'auto', modal: true, title: "Upload Pictures",
close: function () { $('#DivBulkUpload').remove(); }});
});
}
</script>
show Uncaught TypeError: Cannot read property 'get' of undefined in debuger browser.
solution:
1.By adding jquery UI in package manager console
PM> install-package Jquery.UI.combined
2.And add scripts and links in top of cshtml page
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery-ui-1.11.4.js"></script>
<link href="~/Content/themes/base/all.css" rel="stylesheet" />
My problem was solved.
I think this will work:
$.get("http://www.example.com/user.php?q=" + client, function(response) {
if(response == "invalid"){
console.log("invalid login");
return;
}
});