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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Man I just paste the most important part of the code, but I have the other functions needed.
3

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']

8 Comments

Please see my post above as this is somewhat misleading and promotes bad practices that leave your Wordpress installation vulnerable.
@Ohgodwhy nothing in my answer has any bearing on wordpress, is simply cleaning up client side code. Client has no knowledge of wordpress
I disagree, this directly promotes that, as you're not passing in an action parameter which would suggest that you're not using add_action() in your functions.php file which then implies that you're sending this directly to your own file and bypassing the Wordpress core. That is, as I stated previously, both misleading and promoting a bad practice.
@Ohgodwhy what do you mean...of course there's an action parameter in data in my code
Oops, you're right, I'm wrong. I'll leave my comments here anyway.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.