将变量从PHP传递到AJAX成功函数

时间:2022-12-08 19:43:14

My aim is to update a WordPress post using AJAX. My code so far:

我的目标是使用AJAX更新WordPress帖子。我的代码到目前为止:

Script:

脚本:

$.ajax({
    type: 'POST',
    url: ajax_url,
    data: {
        'action': 'wp_post',
        'ID': post_id,
        'post_title': post_title
},
success: function( data ) {
        $( '.message' )
        .addClass( 'success' )
        .html( data );
},
error: function() {
        $( '.message' )
        .addClass( 'error' )
        .html( data );
    }       
});

PHP:

PHP:

function wp_post() {

    $post['ID'] = $_POST['ID'];
    $post['post_title'] = $_POST['post_title'];
    $post['post_status'] = 'publish';

    $id = wp_update_post( $post, true );

    if ( $id == 0 ) {
        $error = 'true';
        $response = 'This failed';
        echo $response;
    } else {
        $error = 'false';
        $response = 'This was successful';
        echo $response;
    }

}

As you can see the $response variable in my PHP function is being passed to the success function in my script and the value of $response is displayed on the page.

正如您所看到的,我的PHP函数中的$ response变量正在传递给我的脚本中的success函数,并且$ response的值显示在页面上。

I want to modify my success function to do something like this:

我想修改我的成功函数来做这样的事情:

success: function( data ) {
    if( $error == 'true' ) {
        // do something
    } else {
        // do something else
    }
},

The problem is, I am having trouble passing both the $response and $error variables in my PHP function to the success function in my scipt.

问题是,我无法将PHP函数中的$ response和$ error变量传递给我的scipt中的success函数。

  1. Can anyone let me know how to pass $response and $error to my script's success function?
  2. 任何人都可以让我知道如何将$ response和$ error传递给我的脚本的成功函数?
  3. Is there a better approach I should be taking?
  4. 我应该采取更好的方法吗?

I'm newish to AJAX so forgive me if the question is very basic.

我对AJAX很新,所以请原谅我,如果这个问题非常基础的话。

6 个解决方案

#1


10  

You shoud encode the response of the php script as json, as follows:

你应该将php脚本的响应编码为json,如下所示:

function wp_post() {

    $post['ID'] = $_POST['ID'];
    $post['post_title'] = $_POST['post_title'];
    $post['post_status'] = 'publish';

    $id = wp_update_post( $post, true );

    $response = array();

    if ( $id == 0 ) {
        $response['status'] = 'error';
        $response['message'] = 'This failed';
    } else {
        $response['status'] = 'success';
        $response['message'] = 'This was successful';
    }

    echo json_encode($response);

}

And then, in your javascript code:

然后,在您的JavaScript代码中:

success: function( data ) {
    if( data.status == 'error' ) {
        // error handling, show data.message or what you want.
    } else {
        // same as above but with success
    }
},

#2


2  

You can create a JSON array like this one, in the backend:

你可以在后端创建一个像这样的JSON数组:

$arr = array('error' => true, 'something' => 'foo');
echo json_encode($arr);

And then parse the json array to fetch the returned values, like this:

然后解析json数组以获取返回的值,如下所示:

success: function( data ) {
    var error = '';
    var something = '';
    for(var i = 0; i < data.length ; i++)
    {
        error = data[i].error;
        something = data[i].something;
    }
    if( error ) {
        // do something
    } else {
        // do something else
    }
},

Wherea you echoed the array from the backend to the frontend, you can't simply access PHP variables within the JavaScript.

如果您从后端到前端回显数组,则不能简单地在JavaScript中访问PHP变量。

Note that there might be a syntax error, since I'm not testing it.

请注意,可能存在语法错误,因为我没有测试它。

#3


1  

What you are looking for is json_encode()

你在找什么是json_encode()

This converts a PHP array to JSON.

这会将PHP数组转换为JSON。

For example:

例如:

$dataArray = array( 'message' => 'Error', 'data' => data);
echo json_encode($dataArray);   

#4


0  

You cannot directly use PHP variables within JavaScript. The best you can do is manipulate PHP output in your JavaScript code.

您不能在JavaScript中直接使用PHP变量。您可以做的最好的事情是在JavaScript代码中操作PHP输出。

For example, you could print $response as either 'error' or 'no_error' - and in your AJAX callback, check that var data does not equal 'error' (For example).

例如,您可以将$ response打印为'error'或'no_error' - 并且在您的AJAX回调中,检查var数据是否不等于'error'(例如)。

#5


0  

if you use:

如果您使用:

echo json_encode($response);

on your .php function, remember to use:

在.php函数上,记得使用:

var data = $.parseJSON(data);

on your ajax success.

关于你的ajax成功。

Example:

例:

function php_ajax_function() {

    // whatever you want to do...

    $response = array();

    if ( $id == 0 ) {
        $response['status'] = 'error';
        $response['message'] = 'This failed';
    } else {
        $response['status'] = 'success';
        $response['message'] = 'This was successful';
    }

    echo json_encode($response);
}

And then, in your javascript code:

然后,在您的JavaScript代码中:

success: function( data ) {

    console.log(data);

    var data = $.parseJSON(data);

    if( data.status == 'error' ) {
        // do something
    } else {
        // do other thing
    }
}

#6


-2  

the javascript variable data contains your echoed $response variable. So using your example, it would be something like this. Be sure you are also asking for html as your return data in the ajax function. here is the docs on that: http://api.jquery.com/jquery.ajax/

javascript变量数据包含echoed $ response变量。所以使用你的例子,它会是这样的。请确保您还要求将html作为ajax函数中的返回数据。这是关于它的文档:http://api.jquery.com/jquery.ajax/

success: function( data ) {
    if( data == 'This failed' ) {
        // do something
    } else {
        // do something else
    }
},

#1


10  

You shoud encode the response of the php script as json, as follows:

你应该将php脚本的响应编码为json,如下所示:

function wp_post() {

    $post['ID'] = $_POST['ID'];
    $post['post_title'] = $_POST['post_title'];
    $post['post_status'] = 'publish';

    $id = wp_update_post( $post, true );

    $response = array();

    if ( $id == 0 ) {
        $response['status'] = 'error';
        $response['message'] = 'This failed';
    } else {
        $response['status'] = 'success';
        $response['message'] = 'This was successful';
    }

    echo json_encode($response);

}

And then, in your javascript code:

然后,在您的JavaScript代码中:

success: function( data ) {
    if( data.status == 'error' ) {
        // error handling, show data.message or what you want.
    } else {
        // same as above but with success
    }
},

#2


2  

You can create a JSON array like this one, in the backend:

你可以在后端创建一个像这样的JSON数组:

$arr = array('error' => true, 'something' => 'foo');
echo json_encode($arr);

And then parse the json array to fetch the returned values, like this:

然后解析json数组以获取返回的值,如下所示:

success: function( data ) {
    var error = '';
    var something = '';
    for(var i = 0; i < data.length ; i++)
    {
        error = data[i].error;
        something = data[i].something;
    }
    if( error ) {
        // do something
    } else {
        // do something else
    }
},

Wherea you echoed the array from the backend to the frontend, you can't simply access PHP variables within the JavaScript.

如果您从后端到前端回显数组,则不能简单地在JavaScript中访问PHP变量。

Note that there might be a syntax error, since I'm not testing it.

请注意,可能存在语法错误,因为我没有测试它。

#3


1  

What you are looking for is json_encode()

你在找什么是json_encode()

This converts a PHP array to JSON.

这会将PHP数组转换为JSON。

For example:

例如:

$dataArray = array( 'message' => 'Error', 'data' => data);
echo json_encode($dataArray);   

#4


0  

You cannot directly use PHP variables within JavaScript. The best you can do is manipulate PHP output in your JavaScript code.

您不能在JavaScript中直接使用PHP变量。您可以做的最好的事情是在JavaScript代码中操作PHP输出。

For example, you could print $response as either 'error' or 'no_error' - and in your AJAX callback, check that var data does not equal 'error' (For example).

例如,您可以将$ response打印为'error'或'no_error' - 并且在您的AJAX回调中,检查var数据是否不等于'error'(例如)。

#5


0  

if you use:

如果您使用:

echo json_encode($response);

on your .php function, remember to use:

在.php函数上,记得使用:

var data = $.parseJSON(data);

on your ajax success.

关于你的ajax成功。

Example:

例:

function php_ajax_function() {

    // whatever you want to do...

    $response = array();

    if ( $id == 0 ) {
        $response['status'] = 'error';
        $response['message'] = 'This failed';
    } else {
        $response['status'] = 'success';
        $response['message'] = 'This was successful';
    }

    echo json_encode($response);
}

And then, in your javascript code:

然后,在您的JavaScript代码中:

success: function( data ) {

    console.log(data);

    var data = $.parseJSON(data);

    if( data.status == 'error' ) {
        // do something
    } else {
        // do other thing
    }
}

#6


-2  

the javascript variable data contains your echoed $response variable. So using your example, it would be something like this. Be sure you are also asking for html as your return data in the ajax function. here is the docs on that: http://api.jquery.com/jquery.ajax/

javascript变量数据包含echoed $ response变量。所以使用你的例子,它会是这样的。请确保您还要求将html作为ajax函数中的返回数据。这是关于它的文档:http://api.jquery.com/jquery.ajax/

success: function( data ) {
    if( data == 'This failed' ) {
        // do something
    } else {
        // do something else
    }
},