Casa > H > How To Update A Php Variable Without Reloading Page

How to update a PHP variable without reloading page

Using only PHP you can’t update a variable without reloading the page. PHP is a server side language so it cannot update the DOM without making a request to the server(reloading the page).

To do this kind of functionality I would suggest using ajax calls with javascript or jQuery

Ex: You have a controller in your PHP class that handles if a post is liked or not. (I’am using symfony here but i think you get the point).

  1. /**  
  2. * @Route("/like", name="like_post")  
  3. */ 
  4. public function likeAction(){  
  5. // Your logic you want to achieve here 
  6.  
  7. return new Response(json_encode(array("liked" => true))); 
  8. }  

And on your client side you will make something like this

  1. $.ajax({ 
  2. url: "/like", 
  3. type: "POST", 
  4. data: JSON.stringify({"post_id": data.id}), // This will send post id to controller  
  5. success: function(){ 
  6. // If the use liked the post before on element html() you can write "dislike" and viceversa 
  7. $("your_html_element_id_that_you_want_to_update").html("liked"); 
  8. });  

This is my first answer and I hope I answered it correctly. I also want to apologize if my english is bad.

Cheers,

De Loredo

Which Xiaomi phone is the best on the T-Mobile network, the Xiaomi Mi A1 or the Xiaomi Mi A2? :: Porque é que são sempre 5 horas em algum lugar?