简体   繁体   中英

JQuery/AJAX Unable to Get Response from PHP file

I am trying to run a server side python script for my wordpress site. I can call the python file inside a php function and run it on the site as shortcode. So, the php file is working. The issue I am having is building my JQuery and getting the response from the php file. I am trying to do a hello_world set-up to debug the issue

AJAX Query:

<script >

function myFunction() {
  alert("Testing button");
}

function HelloWorldShortcode() {
    jQuery(document).ready( function($) {

        $.ajax({
            dataType: 'json', 
            method: 'POST',
            url: "http://localhost/wp-content/helloworld.php",
            data: {
                action: 'helloworld'
            },
        error: function (data) {
            alert("bad");
        },
        success: function (response) {
            alert(response);
        }
        });

    })
}

and the php file:

<?php # -*- coding: utf-8 -*-

ini_set('display_errors', 1);

function hello_world() {

    $test = 'hello';
    return $test;

}

if (isset($_POST['helloworld'])) {
    return hello_world();
}

I have also tried using GET instead of POST. When I access the php file in the browser I do not get any errors and the success part of the ajax query is being reached, as i do not get any error messages. What can I do to access the hello_world function inside of the php file and display the output?

Thanks

You are using the value of the parameter, not the parameter itself...

if (isset($_POST['action'])) {
    echo hello_world();
    // Or json_encode(hello_world()); for returning an Array 
}

or

if ($_POST['action'] == 'helloworld') {
    return hello_world();
    // Or json_encode(hello_world()); for returning an Array 
}

You would do something like:

if (isset($_POST['helloworld'])) {
    echo hello_world();
    // Or json_encode(hello_world()); for returning an Array 
}

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