Matteo Soresini Matteo Soresini - 1 month ago 6
jQuery Question

How to post json from a search button?

I created a personal JSON file and when I consolo.log i can see is working but how can i post on the browser from a search button?
I cannot found a good explanation for this.
i have to display 4 small divs in a row with these 4 places below.
The user can only search the word "places" and i have to print places.name, places.imgage_urls, places.location_name, places.day_price, places.review_count

Here my code:

<form>
<input type="text" name="search" placeholder="Find a place to work..">
<input id="submit" type="submit" name="subtim" value="Search">
</form>

`<div id="results"></div>`


jQuery

$.getJSON("../test.json", function(data) {
console.log(data);
});

$.ajax({
url: "../test.json",
dataType: "json",
type: "get",
cache: false,
success: function(data) {
console.log(data);
$(data.places).each(function(index, value){
console.log(value);
});
}
});


JSON

{
"places": [
{
"id": 1,
"name": "HNK Flexplek",
"imgage_urls": "https://d2h37djvgj7smg.cloudfront.net/0b4a33ef924631441bc371646c6c3830592c746d/18995.600x400x16919.jpg",
"location_name": "HNK Amsterdam Houthavens",
"day_price": 175,
"review_count": 11
},
{
"id": 2,
"name": "Harrods",
"imgage_urls": "https://d2h37djvgj7smg.cloudfront.net/4efa8f4624286e1890bdcfc82e9dfb06ccfb77ad/9492.600x400x16919.jpg",
"location_name": "Het Warenhuis",
"day_price": 200,
"review_count": 4
},
{
"id": 3,
"name": "V2",
"imgage_urls": "https://d2h37djvgj7smg.cloudfront.net/cd6dfff88114b71ada941ff4e004b0cf143fdb3e/18996.600x400x16919.jpg",
"location_name": "HNK Amsterdam Houthavens",
"day_price": 260,
"review_count": 13
},
{
"id": 4,
"name": "LaFayette",
"imgage_urls": "https://d2h37djvgj7smg.cloudfront.net/6f5a44425fd3892f70755fed536885e0476fc6b8/2328.600x400x16919.jpg",
"location_name": "Het Warenhuis",
"day_price": 150,
"review_count": 0
}
]


}

Answer

$("#find_place").submit(function(){
var inp = $("[name=search]").val();

$.ajax({
    url: "../test.json",
    dataType: "json",
    type: "get",
    cache: false,
    success: function(data) {
        console.log(data);
        $.each(data.places, function(i, v){
        $("results").append("<div id='place"+i+"' class='place'>"+
+"<h3>"+v.name+"</h3>"
+"<h5>"+v.location_name+"</h5>"
+"<img alt='"+v.location_name+"' title='"+v.location_name+"' src='"+v.imgage_urls+"'></img>"
+"<span>Day Price: "+v.day_price+"</span>"
+"<span>Review count: "+v.review_count+"</span>"
+"</div>");
        });
    }
})
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='find_place'>
<input type="text" name="search" placeholder="Find a place to work..">
<input id="submit" type="submit" name="subtim" value="Search">
</form>

<div id="results"></div>

Comments