1

I am using django rest framework.My views response is ok but when i submit my view using ajax it gives me an error json parse error.

Here is my views.py file:

@api_view(['GET', 'POST'])
@parser_classes([JSONParser])
def signup(request, format=None):
    if request.method == 'POST':
        data = JSONParser().parse(request)
        username = data.get('username')
        first_name = data.get('first_name')
        last_name = data.get('last_name')
        email = data.get('email')
        password = data.get('password')
        gender = data.get('gender')
        birth_date = data.get('birth_date')
        serializer = UserSerializer(data=data)
        if serializer.is_valid():
            user = User.objects.create_user(username=username,first_name=first_name,last_name=last_name,email=email,gender=gender,birth_date=birth_date)
            user.set_password(password)
            user.save()
            data = {'result': 'success', 'message':'You have registered successfully now you can login'}
            return Response(data=data, status=201)
        elif not serializer.is_valid():
            data = { 'result': 'error', 'message':serializer.errors}
            return Response(data=data)
    if not request.user.id and request.method == 'GET':
        return render(request, 'sessionauthapp/signup.html')

My ajax js script:

var frm = $('#signupform');
var token = '{{csrf_token}}';

$('#signupform').on('submit', function(e) {
    e.preventDefault();
    $.ajax({
        headers: { "X-CSRFToken": token },
        url: '/signup/',
        type: 'post',
        data: $(this).serialize(),
        dataType: "json",
        contentType: "application/json",

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

          

        },
        error: function(data) {

        }
    });
    return false;
});

My ajax script gives me an error like json parse error but my views response is ok.

2
  • request body / data? JSONParser().parse(request.body) JSONParser().parse(request.data) I'm just trying to guess, not sure which is which Commented Aug 20, 2021 at 13:53
  • same error from ajax script but my response is ok. Commented Aug 20, 2021 at 14:00

1 Answer 1

1
This is my question and i solved it here is my valid script Firstly, convert my form data into json serialize objects with the help of each() and Json.stringify with respective names and values of form:



var frm = $('#signupform');
var token = '{{csrf_token}}';
$('#signupform').on('submit', function(e) {
    e.preventDefault();

    var formDataObj = {};
    (function() {
        frm.find(":input").not("[type='submit']").not("[type='reset']").each(function() {
            var thisInput = $(this);
            formDataObj[thisInput.attr("name")] = thisInput.val();
        });
    })();

    $.ajax({
        headers: { "X-CSRFToken": token },
        url: '/signup/',
        method: 'post',
        // data: $(this).serialize(),
        data: JSON.stringify(formDataObj),
        dataType: "json",
        contentType: "application/json",

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

          

        },
        error: function(data) {

        }
    });
    return false; });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.