Send a form from Jquery to PHP with ajax (wordpress)

风格不统一 提交于 2019-12-23 06:57:34

问题


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?


回答1:


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

name=foo&email=foo@bar.com&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']




回答2:


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 come 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.



来源:https://stackoverflow.com/questions/20831673/send-a-form-from-jquery-to-php-with-ajax-wordpress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!