Send value from a Javascript variable to PHP

Asked

Viewed 3,595 times

0

I have searched a lot and done many tests but I’m not able to send the value of a Javascript variable to a PHP variable.

My case is as follows: I have a real estate portal and I would like to take the information (more precisely the real estate data or just its name) searched by a Javascript function and pass to a variable in PHP, in this case the variable $title, which is the variable that regulates the title that will appear on each page in the browser.

The JS function that picks up this information is this:

function getDadosImobiliaria(id) {
$.getJSON('../site/Control/controlUsuario.php', {type: 'selectDadosImob', imobiliariaId: id}, function(data) {
    if (data.tipo == "f") {
        var imobiliaria = data.nome+" "+data.sobrenome;
        $('.nomeAnunciante').html(imobiliaria);
    } else {
        var imobiliaria = data.sobrenome;

        $('.nomeAnunciante').html(imobiliaria);
    }

    $('#logoAnunciante').attr('src', 'imagensUpload/'+data.logo);
    $('.ruaNumero').html(data.rua+', '+data.numero);
    $('.bairro').html(data.bairro);
    $('.cidadeUf').html(data.cidade+' - '+data.uf);
    $('#fone').html(data.fone);
    $('.showCidade').html(data.cidade);
    $('.showCidade').attr('href', '/imobiliarias/'+data.cidade);
    $('.countTotalImoveis').html(data.count);

    if (data.creci != undefined) {
        $('.creci').html("CRECI: "+data.creci);
    }

}); 
}

How can I pass the real estate variable or any other variable to the PHP variable $title contained in another archive and thus form the titles of the pages of the real estate portal? By POST? Ajax?

Thanks in advance!

  • The only objective is to change the title?

  • Post php page code as well. You can help find the solution.

  • But if you just change the title use the famous... Document.title = "title"

  • Possible duplicate of Pass Javascript variable to PHP body

  • Andrei, the only goal is to change the title. It needs to be dynamic to improve the SEO of pages. And the PHP code practically does not have, I tested only with the variable $title receiving the value. Since I’m not really in the programming area, I couldn’t go on. I used Document.title after seeing what you suggested, but it didn’t work either. I just want to be able to pass this JS variable to PHP. Thanks in advance!

  • The variable imobiliaria is the value you want it to contain in <title>?

  • But do you want to send it to PHP or take it via ajax and inject it into <title> with JS? Your question is very confusing, edit it and explain what you really want.

  • Yes Andrei, the real estate variable is the value I want to pass to the title.

  • Guilherme, I wanted to or send by PHP, either way (ajax, post and everything possible) or, by JS even, set the title with the variable real estate. I managed to do this after a lot of testing, but unfortunately, setting by JS the title of the page, does not appear the title I did by JS when searching on google, IE, It is not relevant to set by JS the SEO of the page. Then I will have to do by PHP to have relevance.

Show 4 more comments

2 answers

1

I managed to get the value in another way, straight with php, and set it in the title, after many try also haha. But I think the question I was looking for, which was to pass the value of a js variable to php, was resolved in the answer above, where it actually worked, but, as I remarked, on the way back to the JS file, the page is updated and all the loaded information is gone, with only the right title. But finally, the main issue has been resolved and so I end the matter here. Thank you all very much and I hope that the above answer given by Andrei will help many with the same doubt. Big hug!

  • Yes... It was like I told you.. Unfortunately php is read before you change the variable. So, for SEO, it wouldn’t do much good. = ) Hug

0


After I took a closer look at your code I noticed that you were using the jquery. There is a way you can send the js variable to php the same way you are using ajax. However, I find it easier, in this case, you change the title of the document through the jquery. From what I understood from the code the variable imobiliaria is the one you want to be on <title>. Then it would look like this:

 ...

    // Dentro da função mesmo...

    if (data.tipo == "f") {
        var imobiliaria = data.nome+" "+data.sobrenome;
        $('.nomeAnunciante').html(imobiliaria);
    } else {
        var imobiliaria = data.sobrenome;

        $('.nomeAnunciante').html(imobiliaria);
    }

    $(this).attr("title", imobiliaria); // aqui ele altera o título

...

This will probably work. If it doesn’t, comment here that I’ll manage

EDIT

"Houston we have a problem!"

Based on what you have put so far there is a variable called $titlewhich is in a php file. What you want is to launch rescued content through the js file and pass that content to that variable because supposedly, you would solve the problem of SEO and change the <title> right?. There is a way to do this, however, this will not solve your problem, because the php is interpreted before the javascript And the only thing you’ll do is update some of the code, but the page loaded on the server remains the same. This is the same thing as the previous example, only taking a bigger turn. See:

This is the php code (rescuerVariable.php)

<?php 
    @$title = $_POST['title'];
    echo json_encode($title);
?>

That’s the index php.:

<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
    var imobiliaria = "Imobiliária Stack Overflow";
    $.ajax({

        type: 'POST',
        url: 'resgataVariavel.php',
        cache: false,
        data: { 'title': imobiliaria },
        success : function(retorno){
                 var resultado = JSON.parse(retorno);
                 document.title = resultado;
           }
    })

});
</script>
<title></title>
</head>
...

Through ajax, I passed the contents of the variable imobiliaria for the variable $title. However, at the end, the title will be changed by javascript with document.title = resultado;.

What you need to do is take this content through php and launch it into the variable $title before the javascipt is executed.

Understand, even if this php variable $titleis inside the tag <title></title>, and I use javascript to change it, but it still wouldn’t work, because the server already "read" the content before it was changed by javascript.

A SOLUTION THAT CAN WORK...

Try to do it this way:

 ... (código anterior)...

if (data.tipo == "f") {
        var imobiliaria = data.nome+" "+data.sobrenome;
        $('.nomeAnunciante').html(imobiliaria);
    } else {
        var imobiliaria = data.sobrenome;

        $('.nomeAnunciante').html(imobiliaria);
    }


    $.ajax({

        type: 'POST',
        url: 'resgataVariavel.php',
        cache: false,
        data: { 'titulo': imobiliaria },
        success : function(retorno){
            document.write(retorno);
        },
    })

   ...(resto do código)...

Filing cabinet resgataVariavel.php

<?php 
    @$title = $_POST['titulo'];
    echo "<title>".$title."</title>";
?>

Note that I put php to include <title></title>, I don’t know if it will work for SEO, because the person who writes this file is javascript. But it’s an option. I hope I’ve helped.

  • Thank you, Andrei, it worked the way you showed me. But unfortunately, for google SEO, set the title or any other javascript metatag does not work, when searching google, the title that appears on the page is not the one edited by JS. Only the pages that the title is made by PHP appear right. And I really need to get this variable to move to a PHP variable. Thank you if you can help me do that.

  • Okay... I’ll do it the way you need it then.. Calm down and

  • @Alessandrobeiersdorf posts the php or html page that has this code. It will help a lot

  • That last edition you made worked too! But.. (always has a but haha) when returning to the js file after going to the php file, the real estate information that has already been uploaded is gone, leaving only the right title, with no other information on the page. I believe it is the order of the function call, or the answer of the call in ajax sucess. I’ve tried everything so that it doesn’t happen, but I couldn’t. I’m sorry it took me so long to answer.

  • @Alessandrobeiersdorf , rsrs... it’s like that... But before you fix it. See if when you changed the title, it worked for SEO. Got it?

  • @Alessandrobeiersdorf because if it doesn’t work for SEO, it won’t do any good to fix the code.

  • And do not forget that you can evaluate the answers ok? This gives an incentive.. =)

  • Unfortunately I will not be able to update on the air like this, because, as I mentioned, the information on the page is not loaded, being only right the title. But I did it another way :D

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.