Avriel Moscovitz
Avriel Moscovitz

Reputation: 21

having problems using ajax to call a php function

on clientside(js) im using this script

    jQuery.ajax({
    type: "GET",
    url: "editold.php",
    data: "call=generateCode",
    success: function (response) {
        alert("Succesful getting php file");
    },
    error: function (response) {
         alert("Error getting php file");
    }
});

on serverside(php) im using this code:

<?php 



if($_SERVER['REQUEST_METHOD']=="GET") {
echo '<script type="text/javascript">' . 'alert(" ' . 'hey' . '");' . '</script>'; 
$function = $_GET['call'];

    if(function_exists($function)) {        
        call_user_func($function);
    } 
    else {
        echo 'Function Not Exists!!';
    }
}

function generateCode() {
echo '<script type="text/javascript">' . 'alert(" ' . 'hey' . '");' . '</script>'; 
}
?>    

Although I do get an alert saying my success function alert meaning the file was loaded succesfully I dont seem to be getting the final generatecode function to work.(I dont get a second alert.)

i've tried lots of things but nothing seems to work.

What do i do?..

Upvotes: 0

Views: 1591

Answers (2)

M.Nagy
M.Nagy

Reputation: 21

1-At server side send the response without script tag.

2-At client side use eval() function to execute your code.

if($_SERVER['REQUEST_METHOD']=="GET") {
echo 'alert(" ' . 'hey' . '");';
$function = $_GET['call'];

if(function_exists($function)) {        
    call_user_func($function);
} 
else {
    echo 'Function Not Exists!!';
}
}

function generateCode() {
//your code 
}


jQuery.ajax({
    type: "GET",
    url: "editold.php",
    data: "call=generateCode",
    success: function (response) {
        alert("Succesful getting php file");

        eval(response);
    },
    error: function (response) {
        alert("Error getting php file");
    }
});

Upvotes: 0

Shomz
Shomz

Reputation: 37701

This should do it:

jQuery.ajax({
    type: "GET",
    url: "editold.php",
    data: {call: "generateCode"}, // <-- This one is changed into an object
    success: function (response) {
        alert("Succesful getting php file");
        $('body').append(response); // <-- Append the ajax response to the page body
    },
    error: function (response) {
        alert("Error getting php file");
    }
});

If not, try doing var_dump($_GET); in your PHP file.

Upvotes: 2

Related Questions