harshit
harshit

Reputation: 7951

replace space or encode it

I have following Jquery call.

$("#btnfindAddress").click(function() {
   var dataString = '';
        //built the data string that will be sent with ajax
        dataString += 'business_name='+$('#company').val()+'&';
        dataString += 'business_city='+$('#city').val()+'&';
        dataString += 'business_country='+$('#country').val()+'&';
        dataString += 'business_zipcode='+$('#zipcode').val();
$.ajax({
type: "GET",
url: "/locations/search",
contentType: "application/text; charset=utf-8",
data: dataString, 
success: function(data){ 
    var text_result="";
    text_result="<table  id=\"thetable\"><tbody>";
    $.each(data,function(index,value){
          text_result+="<tr>";
          text_result+="<td>"+value.name+"</td>";
          text_result+="<td>"+value.address+"</td>";
          text_result+="<td>"+value.zipcode+"</td>";
          text_result+="<td><a name="+ value.name+" address="+value.address+" city="+value.city+"href=>Select</a></td>";
          text_result+="</tr>";
    });
          $('#locations').html(text_result);
}
});
 return false; 
});

it generates the following html

<a href="" angeles="" city="Los" website="null" zipcode="90007"  st="" hoover="" s="" address="3303" coffee="" name="Starbucks">Select</a>

The values are splited by space.

It should have been

    <a href="" city="Los angeles"   address="3303 S Hoover st" coffee="" name="Starbucks">Select</a>

How can i fix this ?

Thanks

Upvotes: 0

Views: 83

Answers (2)

King Friday
King Friday

Reputation: 26076

You should not be doing this with string manipulation. jQuery handles the encoding properly if you do the following...

var $table = $('<table>').attr('id','theTable');
$.each(data,function(index,value) {
    $table.append(
       $('<tr>')
         .append($('<td>').text(value.name))
         .append($('<td>').text(value.address))
         .append($('<td>').text(value.zipcode))
         .append($('<td>').append(
           $('<a>').attr('name',value.name).attr('address',value.address)
         )
    );
});
$('#locations').html($('<div>').append($table).html());

Even better would be to use a templating approach like EJS or Moustache.

Upvotes: 1

Māris Kiseļovs
Māris Kiseļovs

Reputation: 17275

You need to add quotes to generated html:

text_result+="<td><a name=\""+ value.name+"\" address=\""+value.address+"\" city=\""+value.city+"\" href>Select</a></td>";

Upvotes: 3

Related Questions