I am using XAMP localhost. I have a folder named wesite in my htdocs for my website template I am creating. My ajax call works fine when both js and php is in the root of this folder. However, when I create a folder name functions and put the js and php script there at the root, the js ajax call don't call the php. Below is the code. It works fine when both are in the directory as the index.php or any other html files, but not in a sub directory. I know it has to do with the path because the scripts work otherwise.
The folder structure is like this there is a folder called Website which has all the html files saved with php ext. Inside this Website folder I have the functions folder which has all the js and php functions no sub directory in the functions folder so all js and php files are at the root of the functions folder. When I look at the inspect element in Chrome, it says the update.php file has a 404 file not found error. This is weird giving the fact that both the js and php are in the same folder. The php script is a simple test script which just echo "Hello From php" to see if I am getting a response
function navUpdate(){
alert('Hello from functins');
var navItemOne = document.getElementById('menu-item-one').innerHTML;
var navItemTwo = document.getElementById('menu-item-two').innerHTML;
var navItemThree = document.getElementById('menu-item-three').innerHTML;
var navItemFour = document.getElementById('menu-item-four').innerHTML;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
alert(this.responseText);
}
}
xhttp.open("POST", "update.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(`nav-item-one=${navItemOne}&nav-item-two=${navItemTwo}&nav-item-
three=${navItemThree}&nav-item-four=${navItemFour}`);
}
Related
Since I upgraded my application to .Net Core 3.0, I can't return a html view from a controller.
If I call View("Views/test.html"), it says it doesn't find the file. In 2.2, it worked well...
Any idea on the breaking change that made my code broken ?
If you want to be able to request static HTML files, add them under wwwroot or create a directory inside it , for example , html folder , and serve that as well via the static files middleware . Then you can return the html to view with text/html content-type :
public IActionResult Index()
{
return File("/html/test.html", "text/html");
}
Thanks.
Finally, I modifier StaticFiles Middleware configuration to serve also html files that are not in the wwwroot folder using this code :
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "MyFiles/MyAngularJSApplication")),
RequestPath = "/app",
});
see : https://learn.microsoft.com/fr-fr/aspnet/core/fundamentals/static-files?view=aspnetcore-3.0
Setup:
html file on local machine in parent dir
js file in sub dir
image files in sub dir "Fotos"
Following code in js file:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (true/*this.readyState == 4 && this.status == 200*/) {
alert(this.responseText);
}
};
xhttp.open("GET", "/Fotos", true);
xhttp.send();
This causes TWO alerts to pop up with completely empty message box. I tried playing around with the directory path, but nothing changed, even with just "/". If I delete the true and replace it with the line in /* it doesn't yield a message box at all.
I was hoping to get some form of parsable list of image files from this.
I realize this has been solved with jQuery before, but I want to do this without, as it should be simple enough. Well, why isn't it?
It fails if the /Fotos folder does not exist (or does not have the correct permissions).
Additionally, for XMLHttpRequest to work, it needs the web page to be served by a web server. It must be accessed with http or https protocol (even if in localhost). E.g. http ://localhost/myfolder/pagewithcode.html Then, the Fotos folder must be a subfolder of "myfolder". The code would also work if the route is http: //localhost/pagewithcode.html (and Fotos is a subfolder of the one where pagewithcode.html is).
The code below (slightly modified from yours) gets the contents of the current folder (in which the html page with the JavaScript code is stored).
Notice that the responseText is HTML, with all the tags, not just the list of files, so that it could be shown in the browser.
<html>
<body>
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// enter here only when success
console.log(this.readyState);
console.log(this.responseText);
}
else {
// enter here for all state changes except success
console.log(this.readyState);
console.log(this.responseText);
}
};
xhttp.open("GET", ".", true);
xhttp.send();
</script>
</body>
</html>
If Fotos is a subfolder of the one the html page is in, then you'd better remove the initial '/' of the path (otherwise, you are getting a Fotos folder in the root folder of the server):
xhttp.open("GET", "Fotos", true);
I setup the following Routes for now (Moving a barebone php project to laravel):
Route::get('/', function () {
return view('index');
});
Route::get('cat/a', function (){
return view('cat.cat_a');
});
Both Files include 4 other Files located in /resources/views/includes. I load those files using:
#include('includes.header')
#include('includes.sidebar_a')
[...] Content [...]
#include('includes.sidebar_b')
#include('includes.footer')
All includes are correctly included in both, domain.com/ aswell as domain.com/cat/a but whitin the view domain.com/cat/a all included css & js files (included in footer.blade.php & header.blade.php) return 404.
Here is my file structure:
You should use asset helper to generate links to JS&CSS:
{{ asset('js/main.js') }}
In this case you'll get HTML with correct paths.
I have very simple jQueryMobile application. I want to submit a form and to call ajax. On my desktop PC this works fine and looks like this:
application on my PC
When i press the button "Save" the text below appers. The HTML code for the interface is in the script accountAdd.html. At my PC It works as expected, but i need this app for my mobile device. Here is the screenshot from my device when i try to do the same thing that is showed at the first figure.
application on my mobile device
So here is the part of the script that calls ajax.
accountAdd.html
<script>
$( document ).ready(function() {
$(document).on('submit', '#formDetails', function() {
var theName = $("#accountName").val();
if($('#accountName').val().length > 0) {
$.ajax({
url: 'accountAdd.php',
data: $('#formDetails').serialize(),
type: 'post',
dataType: 'json',
timeout: 5000,
success: function (result, status) {
$("#resultLog").html("accountName: " + result.accountName);
},
error: function (request,error) {
alert('Network error has occurred please try again! Error: ' + error);
}
});
} else {
alert('Please fill all necessary fields');
}
return false;
});
});
</script>
.
.
.
HTML code
Here is my other script that contains code that is executed in back-end.
accountAdd.php
<?php
header('Access-Control-Allow-Origin: *');
$return['accountName'] = $_POST['accountName'];
$return['accountType'] = $_POST['accountType'];
$return['accountBalance'] = $_POST['accountBalance'];
$return['accountDate'] = $_POST['accountDate'];
echo json_encode($return);
?>
So the ajax call on my mobile device is not working as expected and as you can see at the second figure is giving parseerror. The code is completely the same at both devices. I'am converting the scripts with phonegap. I think that the problem is related with JSON objects (I think that ajax call in phonegap need to pass JSON obejects but I'm not sure). I need help, how to modify the code, so that can work at the PC and at my mobile device at the same time.
Ok, you have <access origin="*"/> so it is not a CORS issue.
I think maybe your problem is that you do not set the datatype to json in your php but expect it in the javascript side. Try adding the following line in your php file :
header('Content-Type: application/json');
Edit
I see the url to your php uses local path (should have noticed earlier but didn't know if you removed the server address on purpose), so it seems you put the .php files in the phonegap app.
That is not how it works. Either you need to do things locally and you do it in javascript, or you want to communicate with a server and you
do not put any php page in the www folder of your local page
provide the url of your server to each ajax calls.
Make sure your config.xml file is in the same folder as your index.html file and then use the (Or whatever domain you are on)
I have an Ajax post call written in a separate ".js" file which I call in multiple pages.
My code looks like this:
$.ajax({
url: '/MyVirtualDirectory/Controller/Action',
type: 'POST',
dataType: 'json',
....
....
})
Each time I change my virtual directory in my server, I'm required to change the code in "URL" to make my Ajax call working.
Is there any method that can make my code independent of my "Virtual Directory" name in IIS ..?
My application is MVC3.
Description
You should use the Url.Action method. But in your case, a seperate js file, you cant access this method. So i would create a javascript variable for each url in your view. Then you can use this variable in your js file.
UrlHelper.Action Method - Generates a fully qualified URL to an action method.
Sample
Your View
<script type="text/javascript">
var myUrl = '#Url.Action("actionName", "controllerName")';
</script>
<script type="text/javascript" src="yourJsFile.js"/>
Your js file
$.ajax({
url: myUrl,
....
})
Update
Another way is to store your url in a hidden field inside your view and get the hidden fields value inside your js file.
More Information
MSDN - UrlHelper.Action Method
I finally found a partial work around.
In my .js file i did some dirty coding like this:
var Path = location.host;
var VirtualDirectory;
if (Path.indexOf("localhost") >= 0 && Path.indexOf(":") >= 0) {
VirtualDirectory = "";
}
else {
var pathname = window.location.pathname;
var VirtualDir = pathname.split('/');
VirtualDirectory = VirtualDir[1];
VirtualDirectory = '/' + VirtualDirectory;
}
$.ajax({
url: VirtualDirectory/Controller/Action,
....})
The basic idea is I check the URL for localhost and port number. If both are there, it means that then I'm debugging in my local machine and so I don't need virtualdirectory in URL. If I'm running a hosted version then there won't be localhost and port number in my URL(provided I'm hosting on port 80).
And by this way when I run on my local machine while debugging the url will be only Controller/Action and while I host the URL will be VirtualDirectory/Action/Controller. It works fine for me now.
But please post if there is any other simple method.
I think it would be safer to declare a global Javascript variable and then set the variable for the first time, maybe when Home/Index fires. and then reuse it in every ajax calls like so:
$.ajax({... url: GlobalVariablePath + "Controller/Action/RouteValues" ...})
if you already designed your WebApp and every thing works fine and stuck when site is deployed, then you can manipulate the all ajax URLs like so:
$.ajaxSetup({
beforeSend: function (jqXHR, settings) {
settings.url = GlobalVariablePath + settings.url;
}
});
Using this way, you can safely use the existing js codes and leave the rest without change.