最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Send a form from Jquery to PHP with ajax (wordpress) - Stack Overflow

programmeradmin5浏览0评论

I have a javascript file serializing and sending a form to the php function:

function call_ajax(){


var data2 = jQuery('#newIdeaForm').serialize(); // <--- Important

jQuery.ajax({
    type: 'POST',
    url: myAjax.ajaxurl,
    data: ({action : 'savedata',data : data2}),
    success: function() {


        alert(data2);


    }
});

};

The thing is that I don't know how to receive this form in this php function:

function savedata(){



$my_post = array(
            'post_title'    => 'data.name',
            'post_content'  => 'data.idea',
            'post_status'   => 'publish',
            'post_author'   => $user_id,
            );
        wp_insert_post($my_post);

        die();
    }

Some fields of the form are 'name' and 'idea', I know the var data2 receive the form serialized but don't know how to get this form into the php funcition.

Other question: In the alert event of the javascript file it alerts the serialized form, how could I unserialize this form to alert just the name field?

I have a javascript file serializing and sending a form to the php function:

function call_ajax(){


var data2 = jQuery('#newIdeaForm').serialize(); // <--- Important

jQuery.ajax({
    type: 'POST',
    url: myAjax.ajaxurl,
    data: ({action : 'savedata',data : data2}),
    success: function() {


        alert(data2);


    }
});

};

The thing is that I don't know how to receive this form in this php function:

function savedata(){



$my_post = array(
            'post_title'    => 'data.name',
            'post_content'  => 'data.idea',
            'post_status'   => 'publish',
            'post_author'   => $user_id,
            );
        wp_insert_post($my_post);

        die();
    }

Some fields of the form are 'name' and 'idea', I know the var data2 receive the form serialized but don't know how to get this form into the php funcition.

Other question: In the alert event of the javascript file it alerts the serialized form, how could I unserialize this form to alert just the name field?

Share Improve this question asked Dec 30, 2013 at 0:22 Andrey Lima RamosAndrey Lima Ramos 792 silver badges12 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

This is a prime example of how not use AJAX in Wordpress.

First, you need to hook into the action that wordpress provides. For this, we'll use both the nopriv and generic.

add_action('wp_ajax_nopriv_savedata', 'my_ajax_handler');
add_action('wp_ajax_savedata', 'my_ajax_handler');

Now, we need to define the my_ajax_handler() function and configure it to only parse the ajax requests that we send (more on this later)

function my_ajax_handler(){
    switch($_REQUEST['fn']):
        case 'savedata' : 
            echo my_ajax_save_form($_REQUEST['data']);
            break;
    endswitch;
}

Then, we need to define the my_ajax_save_form() function so we can trigger the actual WP Post submission.

function my_ajax_save_form($arr){
    $post_vars = array();
    $data = parse_str($arr, $params);
    $my_post = array(
        'post_title'    => $data['name'],
        'post_content'  => $data['idea'],
        'post_status'   => 'publish',
        'post_author'   => $user_id, //where did this e from?
        );
    if(wp_insert_post($my_post)) return true;
    return false;
}

The most noteable above is the $data = parse_str($_REQUEST, $params);. This s being used to take the serialized jQuery form var1=a&var2=b....etc, and turn it into an array, where we can then extract the variables. The function then will return true if it posts successfully, otherwise fallsback on false. Finally, you need to update your ajax function to supply the new fn argument to be switched() on.

jQuery.ajax({
    type: 'POST',
    url: ajaxurl, //wordpres supplies this global variable. use it.
    data: ({fn: 'savedata', action : 'savedata',data : data2}),
    success: function(resp) {
        if(!resp){ alert ('Failed!')}else{ alert(data2) }
    }
});

To note is that when making ajax requests, WP reserves the action parameter as a value in your add_action(), which is why it's named as such. If you want to change the action value in your javascript then make sure you update the add_action code as necessary.

serialize() will generate a form encoded string that looks like:

name=foo&[email protected]&age=86

If you pass an object to data jQuery will convert it to this format by default.

Mixing serialize and object thus gets tricky so is best to to stick to one method or the other.

Try this:

var data2 = jQuery('#newIdeaForm').serialize()
jQuery.ajax({
    type: 'POST',
    url: myAjax.ajaxurl,
    data: data2 + '&action=savedata',
    success: function() {
        .....

    }
});

Now you can access all the form name's using $_POST['fieldName']

发布评论

评论列表(0)

  1. 暂无评论