Chidananda Nayak
Chidananda Nayak

Reputation: 1201

"Uncaught SyntaxError: Unexpected identifier" in Javascript in Django Template

I'm building a Django Weather App, where there is a search input field and and by writing city name in input we can get weather details in console for now. But when typing any city name in input form, its showing "Uncaught SyntaxError: Unexpected identifier" error in console. I am unable to debug this error.

models.py

class City(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

forms.py

class CityForm(forms.ModelForm):
    class Meta:
        model = City
        fields = ('__all__')

urls.py

urlpatterns = [
path('ajax5',views.ajax5view)
]

views.py

def ajax5view(request):
    return render (request,'ajax5.html')

ajax5.html

<!DOCTYPE html>
{% load staticfiles %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
   </script>
    <script src="{% static 'js/ajax5.js' %}" type="text/javascript">

    </script>
</head>
<body>
<form method="GET" action="">
    <span><input type="text"  name='city_name' id="city" placeholder="Search: city_name" value="{{ request.GET.get }}"/></span>

    <span><input class="btn btn-primary btn-sm" type="submit" value="Search" ></span>
    </form>
</form>
</body>
</html>

javascript (ajax5.js)

$(document).ready(function(){
    $('.btn').click(function(){
        var city = $('#city').val();
            $.ajax({
                url: 'https://api.openweathermap.org/data/2.5/forecast?q='+ city +'&appid=026b9c980571390d69406536cdaaccea',
                method : 'GET',
                dataType: 'json'
                success: function(data){
                    console.log(data);
                }

            })

    });
});

Upvotes: 0

Views: 1614

Answers (1)

Chidananda Nayak
Chidananda Nayak

Reputation: 1201

As corrected by @WillemVanOnsem I added comma in dataType Line and then problem was my form was getting refreshed so data from console was getting erased. Therefore i added preventDefault() and my code is working fine. This is my final Ajax Code.

$(document).ready(function(){
    $('.btn').click(function(event){
    event.preventDefault()
        var $city = $('#city').val();
            $.ajax({
                url: "https://api.openweathermap.org/data/2.5/forecast?q="+$city+"&appid=026b9c980571390d69406536cdaaccea",
                type : 'GET',
                dataType: 'json',

                success: function(data){
                    console.log(data);
                }

            })

    });
});

Upvotes: 1

Related Questions