I have a problem with ajax, I'm trying to learn it but he doesn't want me :)
So this is my code:
<script>
$('._givePP').on('click', () => {
swal.mixin({
input: 'text',
confirmButtonText: 'Next →',
showCancelButton: true,
progressSteps: ['1', '2']
}).queue([
{
title: 'Question 1',
text: 'Chaining swal2 modals is easy'
},
{
title: 'Question 2',
text: 'bla bla 2'
}
]).then((result) => {
if (result.value) {
$.ajax({
_dapepe: true,
url: '<?php echo Config::$data->url;?>action/profile',
type: 'POST',
success: (e) => {
e = JSON.parse(e);
swal({
title: e.title,
text: e.message,
type: e.type
});
}
});
}
})
});
</script>
And this is the php code:
<?php
if(isset($_POST['_dapepe'])) {
return print_r(json_encode(array('title' => 'Success','text' => 'gg','type' =>'success')));
}
?>
All I'm trying to get is a simple gg text so I know it's reading the php file but I don't get the gg message.. Does anyone know what's wrong or why it doesn't read the text?
BTW, I verified the url it's working.
Your ajax call doesn't send any data to the server, so it the line if(isset($_POST['_dapepe']))
will never be true
. This in turn will mean that your PHP code never returns any data, and therefore your JS "success" code will crash because it tries to access data which doesn't exist. You probably have errors or warnings in your browser's console relating to this, although you didn't mention them.
In the $.ajax options, instead of
_dapepe: true,
you need to write
data: { _dapepe: true },
The way you've written it, jQuery doesn't know that you intended _dapepe
to be a data field, it just sees it as an option it doesn't recognise, and therefore ignores it. You need to put it inside the data
option, so jQuery knows what to do with it.
http://api.jquery.com/jquery.ajax/ documents all the valid options you can supply to the $.ajax() method.
I also recommend these things in your PHP:
1) return print_r
is a mistake and won't work. print_r dumps its data direct to the output, unless you set a separate flag as the second argument to it (see http://php.net/manual/en/function.print-r.php)
2) Use echo
instead of print_r
- print_r is meant to be a debugging tool. Depending on the kind of data you're returning it might sometimes print characters which aren't actually part of your variable data (e.g. https://eval.in/1040578). It's probably safe in the case of json_encode() but don't get into the habit of using it.
2) It would be better if your code always returned something, even if it's an empty object. The JavaScript can crash sometimes if there's simply no response data at all.
With that in mind, I would suggest changing the PHP to:
<?php
$array = array();
if(isset($_POST['_dapepe'])) {
$array = array('title' => 'Success','text' => 'gg','type' =>'success');
}
echo json_encode($array, JSON_FORCE_OBJECT);
?>