M
M
Maybe_V2016-08-20 13:05:28
JavaScript
Maybe_V, 2016-08-20 13:05:28

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);
}
?>


You need $blockedStatusto assign what the request will return. I'm trying to do it like this:

success: function(data) {
          spamButton.text(textAction);
          "$blockedStatus" = data;
    },

With this entry, the code does not work!

How to do it right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2016-08-20
@prokopov-vi

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 question

Ask a Question

731 491 924 answers to any question