1

There are few questions with this name but I want a simple example without lots of details.

There is a button on page, when I click, it must go to server and run a php file on the server. Below code is not working...

my html code (with js) is:

<button onclick="myFunction()">Do it</button>
<script type="text/javascript">

function myFunction(){
    var x = new XMLHttpRequest();
    x.open("GET","C:\testSample\sample.php",true);
    x.send();
    return false;
</script>

my php file is:

<?php
 echo "Hello world";
 ?>

Is it about the path of php file that I defined in js ?

5
  • 1
    I think you want to use a URL to sample.php, and not a filepath. Commented Dec 15, 2016 at 12:09
  • 1
    yes, you suppose to set server address, not physical Commented Dec 15, 2016 at 12:09
  • 1
    You can't send an AJAX request to the file system, it has to be to a web server. You need to actually install PHP and some kind of web server. Commented Dec 15, 2016 at 12:09
  • hey thanks. there is already a server in production installed on IIS. when we write "prodserver/mod/page/view.php?id=130" on explorer it goes to the page including the button. Should I find the path of the php file from IIS manager on server ? Commented Dec 15, 2016 at 12:21
  • @abidinberkay: If sample.php is on that server then you'd use its HTTP address to access it. Commented Dec 15, 2016 at 13:28

2 Answers 2

2

You have to install XAMPP server because PHP file needs to be executed on web server rather than some local file location. Once you install you can specify the path like

x.open("GET","http://localhost/testSample/sample.php",true);
Sign up to request clarification or add additional context in comments.

3 Comments

I modified the path as you suggested, but still the button does nothing, not writing "hello world". Do you think my js and php sysntax is correct ?
You have missed closing bracket of myFunction()
@abidinberkay: You're also not actually using the "hello world" response anywhere, so where do you even expect it to be printed?
0

Your path be something like this:

xmlhttp.open("GET","./Path/Here/books.xml", false);  //for relative urls

xmlhttp.open("GET","http://localhost/Path/Here/books.xml", false); //for absolute urls

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.