valerio-impiego24
valerio-impiego24

Reputation: 25

jQuery $.get() and $.ajax() doesn't get data from PHP

I have a script that is supposed to alert a message taken from a PHP file after a click event. I've tried both jQuery $.get() and $.ajax(), but both didn't worked. $.ajax() works but alerts an empty message, $.get() alerts "null".

load.php

<?php
    $string = "prova";
    echo json_encode($string);
?>

jquery_save.js

$(document).ready(function(){
    $("#carica").click(function(){
        loadPHP();
    });
});

function loadPHP() {
    $.get( "load.php", function( data ) {
        alert(data)
    }, "json" );
};

index.html

<!doctype html>
  <html>
    <head>
      <meta charset="utf-8">
      <title>This is just a test for Stackoverflow</title>
      <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
      <script type="text/javascript" src="jquery_save.js"></script>
    </head>

  <body>
    <form>
      <input style="background-image:url(img/lc-load.png);" type="submit" value="Carica" name="carica" id="carica">
    </form>
  </body>
</html>

In this way I get the alert but with a "null" output. I've tried this too:

load.php

<?php
    $string = "prova";
    echo $string;
?>

jquery_save.js

$(document).ready(function(){
    $("#carica").click(function(){
        loadPHP();
    });
});

function loadPHP() {
    $.ajax({
        type: 'GET',
        url: 'load.php',
        success: function(data) {
            alert(data); 
        }
    });
};

This gives me an alert with noting inside. Both ways makes the page refresh after closing the alert message (and I don't want this happens). I used another function with $.ajax() to give variables to another PHP file without problem, but I'm not able to take variables from PHP files.

Upvotes: 1

Views: 514

Answers (2)

atmd
atmd

Reputation: 7490

You are using a submit button which causes a submit event which isnt being handled.

try changing it like this

    <input style="background-image:url(img/lc-load.png);" 
type="button" value="Carica" name="carica" id="carica" />

Are you using a submit button to provide a fallback for browsers with javascript disabled? if that's the case you need to prevent the submit event

Upvotes: 0

Jay Blanchard
Jay Blanchard

Reputation: 34406

You have to prevent the default click action -

$("#carica").click(function(event){
    event.preventDefault();
    loadPHP();
});

Your alert does not occur because of the page redirection.

Upvotes: 2

Related Questions