如何使用ajax从div id中提取数据? [关闭]

I'm trying to figure out how to do that, but I don't have a clue. I need to get the text from a div using ajax and then use php to send it with SMTP, but I believe I just need to know how to make the ajax part.

Let's say I have this:

<div id="trajeto-texto1">
     <span id="resultado">
         <div class="calculo"><label>Distância: 0.00 Km</label></div>
         <div class="calculo"><label>Duração: 0 min.</label></div>
         <div class="calculo"><label>Custo: R$ 0,00</label></div>
     </span>                    
</div>

And I need to parse every single text inside the div id "trajeto-texto", or inside the span id "resultado".

It's like a php echo, but in javascript.

Console debugging, apparently there is nothing related to the form:

Failed to load resource: the server responded with a status of 404 (Not Found)
main.js:61 Uncaught TypeError: undefined is not a function
main.js:60 You have included the Google Maps API multiple times on this page. This may cause unexpected errors.
33209.html:9 Uncaught ReferenceError: J is not defined
VM7253:10 Uncaught TypeError: Cannot set property 'geometry' of undefined
dados-do-formulario.js:100 Uncaught SyntaxError: Unexpected token :
http://sitesdemo.mghospedagem.com/ivam-entregas/3/images/bg.png Failed to load resource: the server responded with a status of 404 (Not Found)
33209.html:1 Uncaught ReferenceError: J is not defined
33209.html:9 Uncaught ReferenceError: J is not defined
33209.html:3 Uncaught ReferenceError: J is not defined
33209.html:6 Uncaught ReferenceError: J is not defined
http://sitesdemo.mghospedagem.com/ivam-entregas/3/33209/css Failed to load resource: the server responded with a status of 404 (Not Found)

UPDATE

Ok, so I decided to give it a try, still no success:

 $(document).ready( function(){ //Quando documento estiver pronto
    $('#btnEnviar').click( function(){ /* Quando clicar em #btn */
        /* Coletando dados */
        var nome  = $('#nome').val(); 
        var email = $('#email').val(); 

var distance = $("#distance").text();
var duration = $("#duration").text();
var costs = $("#costs").text();         


        var msg   = $('#txtDetalhes').val();                                            
        var end1 = $('#1').val(); 
        var end2 = $('#txtEnderecoChegada').val(); 



        if(nome.length <= 3){           
            alert('Informe o seu nome');                        
            return false;           
        }    
        if(email.length <= 3){           
            alert('Informe o seu email');                        
            return false;           
        }  


        if(end1.length <= 3){           
            alert('Informe o endereço de partida');                        
            return false;           
        }                         
        if(end2.length <= 5){           
            alert('Informe o endereço de chegada');                        
            return false;           
        }      
        if(msg.length <= 5){           
            alert('Informe os detalhes');                    
            return false;           
        }                     





        /* construindo url */

/*

var urlData = "&nome=" + nome + "&email=" + email +  "&end2=" + end2 + "&distance=" + distance + "&duration=" + duration + "&costs=" + costs + "&msg=" + msg + "&end1=" + end1;

*/








 // extract all the values

    var data = [];
    $('#resultado span').each(function (index, item) {
        var id = $(item).attr('id');
        data[id] = $(item).text();
    });

    // do we have all the values?
    console.log(data);

    // POST the values to backend.php (adjust the URL).
    $.ajax({
        type: "POST",
        url: "sendmailivam.php",
        data: data,
        success: function (response) {
            console.log(response);
        }
    });
});




var urlData = { 
    "nome": nome,
    "email": email,
    "distance": distance,
    "duration": duration,
    "costs": costs,
   "msg": msg,
    "end1": end1,
    "end2": end2
};


        // Ajax 


        $.ajax({
             type: "POST",
             url: "sendmailivam.php", // endereço do phpmailer
             async: true,
             data: urlData, // informa Url
             success: function(data) { // sucesso 
                 $('#retornoHTML').html(data);
             },
             beforeSend: function() { // antes de enviar 
                 $('.loading').fadeIn('fast'); 
             },
             complete: function(){ // completo 
                 $('.loading').fadeOut('fast');
             }
         });




    });    
}); 

TRIED AGAIN, I BELIEVE I DIDN'T MISS ANY POINT NOW, AND I SUSPECT THAT THE PROBLEM IS: THE DATA IS EMPTY. LOOK HOW I'M DOING IT:

$(document).ready(function() { //Quando documento estiver pronto
     $('#btnEnviar').click(function() { /* Quando clicar em #btn */
         /* Coletando dados */
         var nome = $('#nome').val();
         var email = $('#email').val();



         /*
                  var distance = $("#distance").text();
                  var duration = $("#duration").text();
                  var costs = $("#costs").text();
                 */


         // extract all the values

         var data = [];
         $('#resultado span').each(function(index, item) {
             var id = $(item).attr('id');
             data[id] = $(item).text();
         });

         // do we have all the values?
         console.log(data);



         var msg = $('#txtDetalhes').val();
         var end1 = $('#1').val();
         var end2 = $('#txtEnderecoChegada').val();



         if (nome.length <= 3) {
             alert('Informe o seu nome');
             return false;
         }
         if (email.length <= 3) {
             alert('Informe o seu email');
             return false;
         }


         if (end1.length <= 3) {
             alert('Informe o endereço de partida');
             return false;
         }
         if (end2.length <= 5) {
             alert('Informe o endereço de chegada');
             return false;
         }
         if (msg.length <= 5) {
             alert('Informe os detalhes');
             return false;
         }

         //Construindo URL
         var urlData = {
             "nome": nome,
             "email": email,
             "data": data,
             "msg": msg,
             "end1": end1,
             "end2": end2
         };


         /*
            var urlData = {
                      "nome": nome,
                      "email": email,
                      "distance": distance,
                      "duration": duration,
                      "costs": costs,
                      "msg": msg,
                      "end1": end1,
                      "end2": end2
                  };

         */



         // Ajax 

         $.ajax({
             type: "POST",
             url: "sendmailivam.php", // endereço do phpmailer
             async: true,
             data: urlData,


             // informa Url
             success: function(data) { // sucesso 
                 $('#retornoHTML').html(data);
             },
             beforeSend: function() { // antes de enviar 
                 $('.loading').fadeIn('fast');
             },
             complete: function() { // completo 
                 $('.loading').fadeOut('fast');
             }
         });




         // do we have all the values?
         console.log(data);




     });
 });

I interpret your question a bit and maybe it's what you want:

1 How to extract the values from HTML?

The trick is do add one more dom element, to make the selection of the actual values easier.

<div id="trajeto-texto1"> 
    <span id="resultado">
        <div class="calculo">Distância: <span id="distance">1.00</span> Km</div>
        <div class="calculo">Duração: <span id="duration">2</span> min.</div>
        <div class="calculo">Custo: R$ <span id="costs">3,00</span> </div>
    </span>    
    <button id="SubmitButton">Send</button>
</div>

This allows to select the "values" without worries (split or regexp the value from the text of the label).

You simply use $("#distance") to select the dom element by ID with jQuery. To get the value you append .text();.

var distance = $("#distance").text();
var duration = $("#duration").text();
var costs = $("#costs").text();

Or a bit better use .each() for iteration over the dom elements and build your data object, like so:

// extract the values
var data = [];
// iterate over dom element inside span (= item)
$('#resultado span').each(function (index, item) {
    // from this item, get the id
    var id = $(item).attr('id');
    // from this item, get the text, which is the value
    data[id] = $(item).text();
});

console.log(data); // browser console = debug display = open it with key F12

The console output is: [distance: "1.00", duration: "2", costs: "3,00"].

Ok, we made sure data contains the values we want to send... now: let's send.

2 How to send the values over to PHP?

Well, that depends. You could do a POST or GET request. Hmm, lets go with a POST:

// your data looks like this, we got this already
var data = [distance: "1.00", duration: "2", costs: "3,00"];

// post data array to your PHP backend
$.post("backend.php",
    data: data,
    function(data,status){
      // do anything with response
});

Full example:

http://jsfiddle.net/b6w0ckmj/2/

$('#SubmitButton').click(function (evt) {

    // extract all the values

    var data = [];
    $('#resultado span').each(function (index, item) {
        var id = $(item).attr('id');
        data[id] = $(item).text();
    });

    // do we have all the values?
    console.log(data);

    // POST the values to backend.php (adjust the URL).
    $.ajax({
        type: "POST",
        url: "/echo/html/",
        data: data,
        success: function (response) {
            console.log(response);
        }
    });
});

Jens A. Koch, it's not working. I'm using the javascript like this:

var urlData = "&nome=" + nome + "&email=" + email +  "&end2=" + end2 + "&distance=" + distance + "&duration=" + duration + "&costs=" + costs + "&msg=" + msg + "&end1=" + end1;


        /* Ajax */
        $.ajax({
             type: "POST",
             url: "sendmailivam.php", /* endereço do phpmailer */
             async: true,
             data: urlData, /* informa Url */
             success: function(data) { /* sucesso */
                 $('#retornoHTML').html(data);
             },
             beforeSend: function() { /* antes de enviar */
                 $('.loading').fadeIn('fast'); 
             },
             complete: function(){ /* completo */               
                 $('.loading').fadeOut('fast');
             }
         });
    });    
});

@user3692451 this is for your comment below

data needs to be an object:

var urlData = { 
    nome: nome,
    email: email,
    end2: end2,
    distance: distance,
    duration: duration,
    costs: costs,
    msg: msg,
    end1: end1
};

If you need to extract all the texts from a div, no matter how nested they are, you can do something like:

function getTexts(rootNode){
    var stack = Array.prototype.slice.call(rootNode.childNodes,0);
    var texts = [];
    var currentNode;
    while(currentNode = stack.pop()){
        if(currentNode.nodeType === Node.TEXT_NODE && 
           currentNode.textContent.match(/[A-z0-9]/)
          ){
            texts.push(currentNode.textContent);
        }
        if(currentNode.childNodes.length > 0){
            stack.push.apply(stack, 
                Array.prototype.slice.call(currentNode.childNodes,0)
            );
        }
    }
    return texts;
};

Demo on JSFiddle

Solved it, I had to put the element inside a form and use a hidden input after the element. So it got like this:

    <div id="trajeto-texto1"> 
 <form method="post" action="33209/33209.html">

        <span id="resultado" style="font-weight:bold">


        <div class="calculo">Distância: 1.00 Km</div>
        <div class="calculo">Duração: 2 min.</div>
        <div class="calculo">Custo: R$ 3,00 </div>
    </span>  
   <input id="resultado" type="hidden" name="resultado" />

   </div>

Also had to make some adjusts in the javascript, but nothing reaaally different from Jens A. Koch's answer.