Answer the question
In order to leave comments, you need to log in
How to assign result returned by ajax to php variable?
I want to send an ajax request and assign the result to a php variable!
my code looks like this:
<?php
if ($friend) {
$friendId = $friend->getAttribute('id');
$blockedStatus = $friend->getAttribute('blocked');
$isBlocked = Friend::STATUS_BLOCKED;
$setButtonValue = <<< JS
var textRemove = 'Удалить с черного списка';
var textAdd = 'Добавить в черный список';
var spamButton = $('.to-spam-button');
if ("$blockedStatus" == "$isBlocked") {
spamButton.text(textRemove);
} else {
spamButton.text(textAdd);
}
function sendRequest (textAction) {
$.ajax('/user/spam-friend', {
type: 'POST',
data: "blocked-status=" + "$blockedStatus" + "&friend-id=" + "$friendId",
success: function(data) {
spamButton.text(textAction);
},
error: function(data) {
alert('error');
}
});
}
spamButton.click(function() {
if (spamButton.text() == textAdd) {
sendRequest(textRemove);
} else {
sendRequest(textAdd);
}
});
JS;
$this->registerJs($setButtonValue, View::POS_LOAD);
}
?>
$blockedStatus
to assign what the request will return. I'm trying to do it like this:success: function(data) {
spamButton.text(textAction);
"$blockedStatus" = data;
},
Answer the question
In order to leave comments, you need to log in
1. what do you expect from this line "$blockedStatus" = data; ? Are you trying to assign a variable to a string?
2. php is executed on the server, ajax in the browser. When ajax returns something it returns it to the browser, there are html and js there are no php variables there.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question