Calix
Calix

Reputation: 25

Sending two data's (image and number) via ajax

I need to pass two different datas using ajax.

I've got this:

$('#sendcover').on('click',function(){
$.ajax({
     type: "POST",
     url: "{{ url('articles_changecover') }}",
     data: new FormData($('#test')[0]),
     processData: false,
     contentType: false,
     success: function (data) {
     alert(data);
    }
  });
});
<form name="test" id="test" method="post" enctype="multipart/form-data">
  <input type="text" value="{{article.id}}" name="id" />
  <input type="file" name="cover">
  <button id="sendcover" type="submit" class="saveData">Save</button>
</form>

I need to pass two var's with data: id and cover

id - sends {{article.id}} cover - sends image

(and on the backend side it's uploading img and converting it - but it's already done by someone else)

Could somebody help me how to do it properly? I've never did such thing, and I can't find any working answer. :(

Upvotes: 0

Views: 31

Answers (1)

Dwza
Dwza

Reputation: 6565

You could send it as an splitted up object like

data: {
    myId: id,
    myCover: cover
} 

but currently you send the whole form that actually should look like

$('form#test').submit(function(e) {
    e.preventDefault();
    var formData = new FormData(this);

    $.ajax({
        type: "POST",
        url: "{{ url('articles_changecover') }}",
        data: formData
        processData: false,
        contentType: false,
        success: function (data) {
            alert(data);
        }
    });
});

And viewing the source looks fine to send...at least for me ^^

Upvotes: 1

Related Questions