I'm currently struggling so as to pass information from my view to a controller (MVC model) in PHP. I am using the ajax method.
I would like to convey pieces of information such as strings or arrays to the controller:
var dataToSend = [{ fieldname: 'ABC' }, { fieldname: 'DEF' }];
dataToSend = JSON.stringify({ 'list': dataToSend });
$(".application-accept").click(function(event){
$.ajax({
url: "/olad2/project/processapplication/1",
type: "POST",
data: dataToSend,
datatype: "JSON",
contentType: "application/json; charset=utf-8"
}).done(function(response){
console.log(response);
console.log("done");
}).fail(function(err){
console.log(err.responseText);
console.log("failed");
});
});
When I echo the result in the controller I have been told in error that there is no array:
echo json_encode(var_dump($_POST));
Which displays (console.log()):
<b>array</b> <i>(size=0)</i>
empty null
I know that there are a lot of topic about this subject but it doesn't work. Could you help me ?
ps: it is my first post
CodePudding user response:
This reviewed version works:
$.ajax({
url:"https://jsonplaceholder.typicode.com/users",
// url: "/olad2/project/processapplication/1",
method: "POST",
data: JSON.stringify({list:[{ fieldname: 'ABC' }, { fieldname: 'DEF' }]}),
datatype: "JSON",
contentType: "application/json; charset=utf-8"
}).done(function (response) {
console.log(response);
console.log("done");
}).fail(function (err) {
console.log(err.responseText);
console.log("failed");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
But even your "almost unchanged" version would work with the typicode target address:
var dataToSend = JSON.stringify({ 'list': [{ fieldname: 'ABC' }, { fieldname: 'DEF' }] });
$.ajax({
// url: "/olad2/project/processapplication/1",
url: "https://jsonplaceholder.typicode.com/users",
type: "POST",
data: dataToSend,
datatype: "JSON",
contentType: "application/json; charset=utf-8"
}).done(function(response) {
console.log(response);
console.log("done");
}).fail(function(err) {
console.log(err.responseText);
console.log("failed");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>