Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

php function call with ajax

I am trying to call a php function when an HTML button is clicked.i have done some searching and found that its impossible to do this directly and i should use ajax. so this is my attempt so far which is not working.this is my test.php and the function is also in this page.

 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
 <script type="text/javascript">
 $(document).ready(function() {
 $('.NextPage').on('click', function() {
 $.ajax({
 url: 'test.php',
 data: {x: 1},
 type: 'POST',
 dataType: 'JSON',
 success: function(response) {
 alert(response);
 }
 });
 });
 });
 </script>
 </head>
 <body>
 <button type="button" class="NextPage">go to nextpage</button> 
 <?php
 if (isset($_POST['x'])) {
 if ($_POST['x'] == 1) {
 $data = function1();
 echo json_encode($data);
 exit;
 }
 }
 function function1() {
 return 'Hi user! im function #1';
 }
 function function2() {
 return 'Hi user! im function #2';
 }
 ?>

Answer*

Draft saved
Draft discarded
Cancel
8
  • thank you for your answer,i edited my code.still not working ! nothing happens when i click the button Commented May 18, 2014 at 8:17
  • @user3622910 on my example earlier, i used index.php on url on ajax, try to edit it and match the filename of the php that will handle that ajax call Commented May 18, 2014 at 8:20
  • 2
    @user3622910: Instead of complaining "not working", please actually try to debug the issue. Use your browser's console to see if the POST request is being fired and whether you're getting any response back. View the page source. Keep trying — that's how you solve problems :) Commented May 18, 2014 at 8:21
  • @kevinabelita i changed the url to test.php which is the same page of the function. Commented May 18, 2014 at 8:22
  • @user3622910 okay you could check the edit now, we are now using the same jquery cdn (and check the js scripts). Commented May 18, 2014 at 8:27

default

AltStyle によって変換されたページ (->オリジナル) /