Im trying to send data to PHP with AJAX. I already tryed sending it with JSON, with $.post and $.ajax, but all it does - it returns Notice: Undefined index: id in C:\\xampp\\htdocs\\PHP Test\\db\\editform.php on line 7
What am I doing wrong?
HTML
<form action="" method="post" class="usereditform">
<input type="hidden" name="id" value="'.$db_row['id'].'">
<input type="hidden" name="key" value="'.$_SESSION['security_key'].'">
</form>
jQuery
$(document).on('click', '.edit_user', function (e) {
e.preventDefault();
var form = $(this).parent().find('form.usereditform');
var post_url = 'db/editform.php';
var post_data = form.serialize();
$.ajax({
type: 'post',
url: post_url,
data:post_data,
success: function () {
$('.edit_user_form_placeholder').load('db/editform.php');
$('.edit_user_popup').fadeIn();
}
});
});
PHP - editform.php
$id = $_POST['id'];
echo $id;
HTML
<div class="popup edit_user_popup" style="display:none;">
<div class="popup_container">
<div class="edit_user_form_placeholder"></div>
</div>
</div>
You are actually sending two requests:
//first request with proper settings
$.ajax({
...
success: function () {
//second request without any posted data
$('.edit_user_form_placeholder').load('db/editform.php');
...
}
});
Instead, use the data that you get returned by the request itself. Using the $.post
method this could be done the following way
$.post(post_url, post_data, function(result) {
// ^- this is the data that gets returned by the request
$('.edit_user_form_placeholder').html(result);
$('.edit_user_popup').fadeIn();
});
This is the way I'm currently communicating to PHP via ajax. I find it the easiest way, and can be done without forms.
jQuery
var dataString = 'key1='+ value1 + '&key2='+ value2; //values you want to send
$.ajax({
type: "POST",
url: "db/editform.php",
data: dataString,
cache: false,
success: function(result){
//success text
}
});
PHP - editform.php
And recieve like so.
$rowid = $_POST['key1'];
$securitykey = $_POST['key1'];
Have you tried with parsing the data you are posting into a JSON object?
var post_data = JSON.stringify(form.serializeArray());
The data you are passing to your ajax call are not formatted in a JSON object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.