如何使用ajax和PHP将数据传递到服务器? $ _POST ['data']不起作用
I have an HTML form that I want to send to the server (using a PHP script) some information before it gets submitted. I'm using .ajax() jQuery function as well.
Here's my demo.html file:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label>Provincia</label>
<select id ="demo" class="form-control">
<option> </option>
<option value="op1">Opcion 1</option>
<option value="op2">Opcion 2</option>
<option value="op3">Opcion 3</option>
</select>
</div>
<div id="demo2"></div>
<script>
$(document).ready(function() {
$('#demo').on('change', do_something);
console.log('ready');
});
function do_something() {
var selected = $('#demo').val();
$.ajax({
url: 'delete.php',
type: 'POST',
dataType: 'json',
data: { selected }
});
console.log(selected);
$('#demo2').append(selected);
}
</script>
I don't know what to do to get the selected item. I get to print the selected item on the screen and in the console. How do I get that with PHP?
The delete.php file has only this:
<?php
var_dump($_POST['data']);
var_dump($_POST['selected']);
Because I want to know what's on the server, but nothing gets printed. How may I get what's been selected?
Use data
attribute to set values you want to send to PHP
and you can also set success
to execute code when the request is successful.
function do_something() {
var selected = $('#demo').val();
$.ajax({
url: 'delete.php',
type: 'POST',
dataType: 'json',
data: { selected: selected },
success: function (response) {
// response comes from PHP
if (response.result == true) {
// request was success
}else if (response.result == false) {
// request was not successful
}
}
});
}
Then in your PHP, you can access the values through $_POST
<?php
$selected = $_POST['selected'];
// rest of the code here
// you can also send response to Javascript here
// for failure echo json_encode(['result' => false]);
// for success echo json_encode(['result' => true])
The data
attribute in the AJAX options specifies the name of the value you are looking for. Your data
object is:
{
value: selected
}
so simply use $_POST['value']
to get the selected item name. If you ever want to know what's in the POST object, just run a vardump like so:
vardump($_POST);
that may help you answer questions like these in the future.