简体   繁体   中英

Call page PHP with Ajax

I have some difficulties to call PHP script with:

$("#tata").click(function(){


    $.ajax({

        url : 'http://localhost/joomla/modules/mod_visitor/helper.php' ,
        type : 'GET' ,

        success: function(data) {
            alert(data);
        },

        error : function(resultat, statut, erreur){
        console.log("no")
    }

});

});

But my alert is empty... I am sure that the URL is correct, because if I add in my PHP file HTML code it appear on my alert!

I am sure that my PHP code works

PHP file:

 echo "lalalala";
$getData = new mod_visitor();
$writeData = new  writeData();
$urlPart1 = $_SERVER['HTTP_HOST'];
$urlPart2 = $_SERVER['REQUEST_URI'];
$pageEnCours = $urlPart1 .= $urlPart2;
$getData->get_ip();
$getData->LookupIP($GLOBALS['domain']);


$getData->ValidateIP($GLOBALS['domain']);




if ($GLOBALS['domain'] && $pageEnCours != preg_match("#localhost/joomla/$#", $pageEnCours)) {
    $GLOBALS['domain'] = trim($GLOBALS['domain']);

    if ($getData->ValidateIP($GLOBALS['domain'])) {
        echo "cc";
        $result = $getData->LookupIP($GLOBALS['domain']);
        $writeData->write_domain($result);
    } else {
        echo "erreur";
        $writeData->write_error();
    };

} else {
    echo "je ne rentre pas dans la boucle";
};

echo $pageEnCours;
echo $GLOBALS['domain'];

Parse the dataType to 'json'
Add dataType: 'json' to the javascript

$.ajax({
    url : 'http://localhost/joomla/modules/mod_visitor/helper.php' ,
    type : 'GET' ,
    dataType: 'json',
    success: function(data) {
        alert(data);
    },
    error : function(resultat, statut, erreur){
    console.log("no")
}

And echo back as JSON in your php

<?php
    echo json_encode('lalala');
?>

If you want to return multiple items, you can return them as an array

<?php
    $return = array(
        'pageEnCours' => $urlPart1 . $urlPart2,
        'domain' => $GLOBALS['domain']
    );

    echo json_encode($return);
?>

And get the items client-side

success: function(data) {
    console.log(data.pageEnCours, data.domain);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM