basic structure for converting ajax to axios? - ajax

Can some one give me example of how to convert ajax to axios ?
I am trying to convert this code into axios
$.ajax({
type: 'POST',
url: 'http://example.com/storeauthcode',
// Always include an `X-Requested-With` header in every AJAX request,
// to protect against CSRF attacks.
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
// Handle or verify the server response.
},
processData: false,
data: authResult['code']
});

axios.post('http://example.com/storeauthcode', authResult['code'], {
headers: {
'X-Requested-With': 'XMLHttpRequest'
'Content-Type: 'application/octet-stream; charset=utf-8',
},
transformResponse: (data) => { // do something with your data },
});
However a better place for the content-type would be the axios instance config itself.

Configure once globally:
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
Then per request:
const result = await axios.post(
'http://example.com/storeauthcode',
authResult['code'],
{
headers: {
'Content-type': 'application/octet-stream; charset=utf-8'
}
}
);

Related

Laravel Authentication with Passport,how send token Bearer in ajax header inside laravel project

I can get response from RESTful api when using Postman with Authorization Bearer + token.
But How can I send request with token in ajax (i made it inside my laravel project).
$.ajax({
url: "url",
headers: {
'Authorization': authorizationToken,
},
type: "post",
data: data,
async: false,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
success: function (data) {
},
error: function (data, status, error) {
}
});
$.ajaxSetup({
headers: {
"X-CSRF-TOKEN":$('meta[name="csrf-token"]').attractive('content')
"Authorization":"Bearer"+localStorage.getItem('token')
}
});

React Native getting response 400 when post to oauth/token using laravel passport

I am trying to login through oauth/tokens from my React Native project. I have tested with POSTMAN When i send the data from axios it works well. But when i try to send from my app it gives me Error: Request failed with status code 400
my code is :
axios({
method: 'post',
url: 'http://183.172.100.84:8000/oauth/token',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
data: {
client_id : '2',
client_secret : 'secret',
grant_type : 'password',
email : this.state.userEmail,
password : this.state.userPassword
}
})
.then((response) => {
console.log(response.data);
})
I've solved the problem in this way:
axios({
method: 'post',
url: 'http://183.172.100.84:8000/oauth/token',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8'
},
data: 'client_id=2&client_secret=secret&grant_type=password&email=' + this.state.userEmail+'&password='+this.state.userPassword
})
.then((response) => {
console.log(response.data);
})
Seems Axios have some problem to process the data in json format.
If you use Webpack you must also configure the proxy.

Laravel 5.4 not able to parse FormData javascript object sent using Jquery Ajax

Lately I've been trying to solve an issue with no luck, basically I'm trying to submit a form to the server using AJAX, the form has files, so I'm using the FormData javascript object in JQuery 1.12. The data arrives to the server but in I way I don't know how to format it.
This is my AJAX function:
function saveMenu(id){
var formElement = document.getElementById("menu-form");
var formData = new FormData(formElement);
formData.append('_method', 'PUT');
$( "#form-wrapper" ).toggleClass( "be-loading-active" );
$.ajax({
type: 'PUT',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{url('myUrl')}}",
data: formData,
enctype: 'multipart/form-data',
processData: false,
success: function(response) {
toastr.success('Yai! Saved successfully!')
},
error: function(response) {
toastr.error('Oh oh! Something went really wrong!')
},
complete: function() {
$( "#form-wrapper" ).toggleClass( "be-loading-active" )
}
});
}
and when I perform a dd($request->all()); in my controller I get something like this:
array:1 [
"------WebKitFormBoundaryRCIAg1VylATQGx46\r\nContent-Disposition:_form-data;_name" => """
"_token"\r\n
\r\n
jtv4bnn8WQnP3eqmKZV3xWka2YOpnNc1pgrIfk0D\r\n
------WebKitFormBoundaryRCIAg1VylATQGx46\r\n
Content-Disposition: form-data; name="blocks[43][title]"\r\n
\r\n
...
Things I've tried:
Set the HTTP verb to POST. Same result.
Set the AJAX contentType: false, contentType: application/json. Empty response.
Remove enctype: 'multipart/form-data'. Same response.
Any help is appreciated.
This fixed it for me
data: form_data,
contentType: false,
processData: false,
processData: false prevents jQuery from parsing the data and throwing an Illegal Invocation error. JQuery does this when it encounters a file in the form and can not convert it to string (serialize it).
contentType: false prevents ajax sending the content type header. The content type header make Laravel handel the FormData Object as some serialized string.
setting both to false made it work for me.
I hope this helps.
$('#my-form').submit(function(e) {
e.preventDefault();
var api_token = $('meta[name="api-token"]').attr('content');
form_data = new FormData(this);
$.ajax({
type: 'POST',
url: '/api/v1/item/add',
headers: {
Authorization: 'Bearer ' + api_token
},
data: form_data,
contentType: false,
processData: false,
success: function(result,status,xhr) {
console.log(result);
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
}
});
});
also remember to use $request->all(); $request->input() excludes the files
I've been trying to debug that for 2 hours and i found out that method PUT is not working with formData properly.
Try changing
type : "PUT"
into
method : "POST"
Then change your method on your backend from put to post and you'll see the difference.
I used below codes to test it
$("#menu-form").submit(function (){
var fd = new FormData();
fd.append('section', 'general');
fd.append('action', 'previewImg');
fd.append('new_image', $('.new_image')[0].files[0]);
$.ajax({
method : 'POST',
headers: {
'X-CSRF-TOKEN': '{{ csrf_token()}}'
},
url: "{{url('upload-now')}}",
data : fd,
contentType: false,
processData: false,
success: function(response) {
console.log(response);
},
});
return false;
});
And in my controller
public function test(Request $request){
dd($request->all());
}
Ill try to research more about this issue.
Laravel 7,
if use method PUT in ajax, you can follow
1. change method method: 'PUT' to method: 'POST'
2. add formdata.append with _method PUT like this example :
$('#updateBtn').click(function(e){
e.preventDefault();
var frm = $('#tambahForm');
frm.trigger("reset");
$('.edit_errorNama_kategori').hide();
$('.edit_errorGambar').hide();
var url = "/pengurus/category/"+$('#edit_id').val();
var formdata = new FormData($("#editForm")[0]);
formdata.append('_method', 'PUT'); //*** here
$.ajax({
method :'POST', //*** here
url : url,
data : formdata,
dataType : 'json',
processData: false,
contentType: false,
success:function(data){
if (data.errors) {
if (data.errors.nama_kategori) {
$('.edit_errorNama_kategori').show();
$('.edit_errorNama_kategori').text(data.errors.nama_kategori);
}
if (data.errors.gambar){
$('.edit_errorGambar').show();
$('.edit_errorGambar').text(data.errors.gambar);
}
}else {
frm.trigger('reset');
$('#editModal').modal('hide');
swal('Success!','Data Updated Successfully','success');
table.ajax.reload(null,false);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Please Reload to read Ajax');
console.log("ERROR : ", e);
}
});
});
its works for me
Finally I gave up trying to make it work and tried a more vanilla approach, I still don't know the reason why the request is formated like that, but the XMLHttpRequest() function works perfectly and the migration is not a big deal.
The equivalent of the function I posted about would be:
function saveMenu(action){
var formElement = document.getElementById("menu-form");
var formData = new FormData(formElement);
formData.append('_token', $('meta[name="csrf-token"]').attr('content'));
var request = new XMLHttpRequest();
request.open("POST", "{{url('myUrl')}}");
request.send(formData);
request.onload = function(oEvent) {
    if (request.status == 200) {
      toastr.success('Yai! Saved successfully!');
    } else {
      toastr.error('Oh oh! Something went really wrong!');
}
$( "#form-wrapper" ).toggleClass( "be-loading-active" );
  };
}
Bit late, but;
This will solve your problem;
var formData = new FormData(document.getElementById('form'));
console.log(...formData);
var object = {};
formData.forEach(function (value, key) {
object[key] = value;
});
Then you can send this object to the server. This is much more readable and works great.
OR
You can simply send this directly;
JSON.stringify(Object.fromEntries(formData));
This is the newer approach.
And don't give up :-)

Passing from ajax to fetch on client side with a glassfish server

I have a phonegap application that uses
$.ajax(
type: 'POST,
dataType:"json",
url: 'test.com'
data: { mail: 'bob#test.com' }
)
which i get in my glassfish server doing something like
HttpServletRequest request;
request.getParameter('mail');
I'm moving my application in react native so i tryed
fetch('test.com', {
method: 'POST',
headers: {
'Content-Type': 'text/plain',
},
body: 'mail=bob#test.com',
})
and i tryed
fetch('test.com', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ mail: 'bob#test.com' }),
})
but neither of these worked, i'm deseperately having request.getParameter('mail') == null on server side.How can i do ?Note : i don't want to change the way the server handles things.

Iris CouchDB Post Cross Domain

I am trying out Iris Couch and I ma having problems posting cross domain.
I am posting some simple JSON from within a chrome extension to Iris' couchdb and I get the dreaded 405 (Method Not Allowed)
I have turned CORS on in the CouchDB config, as well as set CORS credentials TRUE
This is my JS code
_save = function (item) {
var rtrn = $.Deferred();
$.ajax({
type: "POST",
url: 'https://xxxxx.iriscouch.com/notes',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(item),
xhrFields: {
withCredentials: true
},
crossDomain: true,
success: function (e) {
rtrn.resolve();
console.log(e);
},
success: function (e) {
console.log(e);
}
});
return rtrn.promise();
}
Thank you!

Resources