0

I have a page with a button and, when I click on this button, jquery-ajax executes the php code in an other file but the code not working as I would like.

The button code is very simple:

<button type="submit" onclick="runCode()"> Execute </button>

The problem is on jquery-ajax code because if I use this code:

$(document).ready(
   function runCode(){
      $.ajax({
         url: "file.php",
         success: function(msg){
            alert( "Done.");
         }
      });
   }
)

when I load the page, the code of file.php is execute but not clicking the button, in fact the button, after loading of the page, is not working.

Instead, if I use this code:

function runCode(){
   $.ajax({  
      url: "file.php",
      success: function(msg){
         alert( "Done.");
      }
   });
}

the button works and I see the alert "Done" when I click on it but file.php is not executed.

Why in the first case the file is executed but button not working, while in the second case button works but php file is not executed? How to correct the code?

dav04
  • 19
  • 7
  • [onclick is evil](http://stackoverflow.com/questions/5871640/why-is-using-onclick-in-html-a-bad-practice) – yunzen May 16 '14 at 13:36

3 Answers3

1

The first case has the function wrapped in the DOM ready wrapper $(document).ready(). This means it's not accessible from the global scope, so when you're button tries to fire runCode() it is undefined.

In the first case, the function is fired when the DOM is loaded, even though you didn't explicitly call it like runCode(), what you're doing is passing the function to the DOM ready handler, which will invoke it.

The second case doesn't have the DOM ready wrapper, and so is in the global scope, therefore is accessible by the button inline click.

When you say the file is not executed but it fired the alert - that's not possible because the success function only runs if the request was successfully sent and a successful response was received.

Also, your use of a button type submit may be confusing things. By default, this will submit the form after running the click handler. if you don't want that, then either change to a type of button or have the click handler return false (or prevent default).

MrCode
  • 63,975
  • 10
  • 90
  • 112
  • My guess is that OP should change the button type from `submit` to `button`. The page is probably posting back so the alert is never seen. – Cᴏʀʏ May 16 '14 at 13:33
  • Instead not execute because my database is not updated; the first case updates the database and shows the alert – dav04 May 16 '14 at 13:37
  • @dav04 see my edit about the first case. If your database isn't updated but the alert shows, check your error log because the PHP script was called, the reason for no database update is not clear. – MrCode May 16 '14 at 13:43
  • what I don't understand is because in the first case the php file is executed but in the second case not.... is not logic.... – dav04 May 16 '14 at 13:48
0

Two things:

  1. You probably need to change the button from type submit to type button:

    <button type="button" id="run-button">Execute</button>
    

    With type="submit", you are submitting whatever form you have on your page and it is refreshing, so you never see the alert.

  2. Hook up the event in the DOM-ready handler; you don't really need the runCode function unless you have other reasons for that.

    $(function() {
        $('#run-button').click(function(e) {
            e.preventDefault();
            $.ajax({
                url: "file.php",
                success: function(msg) {
                    alert( "Done.");
                }
            });
        });
    });
    
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
  • in this way I don't see the alert and the php file is not executed – dav04 May 16 '14 at 13:42
  • This is pretty trivial stuff. If it's not working, you might have other script or PHP errors. Are you testing this in a debugger? Put more alerts or `console.log()` statements in the `click` handler before the AJAX method to see if you're making it in there. – Cᴏʀʏ May 16 '14 at 13:46
0

Try this

<button type="button" id="submitButton"> Execute </button> 
<!-- no onclick. This is handled by jQuery -->
<!-- type: button instead of submit -->

// the same as .ready()
jQuery(function($)( 
   // var: cannot be accessed from outside, makes JS unobtrusive
   var runCode = function(e) { 
      $.ajax({
         url: "file.php"
      })
      // uses 'new' Deferred jQuery
      .done(function(msg){ 
         alert( "Done.");
      });
      // Stops Standard submit behaviour
      e.preventDefault(); 
   }
   $('body').on('click', '#submitButton', runCode);
)
yunzen
  • 32,854
  • 11
  • 73
  • 106
  • I see the alert but the php file is not executed – dav04 May 16 '14 at 14:03
  • What do you mean 'executed'? What do you expect, and what does not happen? – yunzen May 16 '14 at 14:14
  • If you see the alert, then the AJAX request was successfully done. THe problem seems to be in the PHP file then, but that is a different story. Maybe you need to transmit some POST/GET data as well? FOr testing open the site in Google Chrome browser, hit [F12] on keyboard, chose the network tab, klick the filter symbol and chose XHR. So only AJAX requests are shown. Then click the #submitButton – yunzen May 16 '14 at 14:18
  • the php file update a database of mysql... if I use the first case, database is updated, so php file works percectly.... for a reason that i don't know, in the second case database is not updated.... – dav04 May 16 '14 at 14:48
  • the two case are different only for the presence od document ready, so it's not possible that php fila has a problem... – dav04 May 16 '14 at 14:49