jquery - Save a form with ajax and php
How can I pass any $_Post[''] with ajax to the php function, when the form is submitted?
The function is working with AJAX but it can't receive the post's values. I tested and the alert return null.
I am using wordpress.
window.onload=function(){
jQuery('#newIdeaForm').submit(function(events){
call_ajax(events);
events.preventDefault();
});
};
function call_ajax(){
var name = $("#name").val();
jQuery.ajax({
type: 'POST',
url: myAjax.ajaxurl,
data: {action : 'savedata'},
success: function(response) {
var json = jQuery.parseJSON(response);
alert(json.nome);
}
});
};
function savedata(){
$name = $_POST['name'];
$my_post = array(
'post_title' => 'teste',
'post_content' => 'teste',
'post_status' => 'publish',
'post_author' => $user_id,
);
wp_insert_post($my_post);
$callback = array('name' =>'teste','title'=>'teste','idea'=>'teste','nome' => $name);
$myJson = json_encode($callback);
echo ($myJson);
die();
}
EDITED
Man, I've tried like this:
function call_ajax(){
var serializedForm = jQuery('#newIdeaForm').serialize();
serializedForm.action = 'savedata';
jQuery.ajax({
type: 'POST',
url: myAjax.ajaxurl,
data: serializedForm,
success: function(data) {
alert(data);
}
});
but it seems that it don't add anything like action when I debug via browser, so it don't go to the php function, anyone can help me?
Answer
Solution:
In the ajax call you are passing data which is converted to action=savedata which, but in the PHP you are trying to get 'name' from the POST data. With your ajax request, the form data is not automatically sent, so you either need to manually send it like this:
or use the .serialize() jQuery function which will automatically serialize the data in a form for you (which you can then supply as the data argument).
Answer
Solution:
If this is what you are executing, I can't find you posting a key named "name".
Also have a look at:
jQuery.ajax and jQuery.post
Hope this works. Let me know how it goes.
Answer
Solution:
try serialising your data and provide content type "application/json; charset=utf-8" like