converting an fetch api call to ajax - javascript

i am using a code from a site where onsubmit the call is made and a call is made
$(":submit").click(async (event) => {
i am not aware of this syntax.
my example using the simple $.ajax call and making a post call to the page
so the above function is like this
$(":submit").click(async (event) => {
event.preventDefault();
let response = await fetch("page.cfm");
const reader = response.body.getReader();
const len = response.headers.get("Content-Length") * 1;
my ajax call is like this
$.ajax({
url: "page.cfm",
cache: false,
data : $('#form').serialize(),
method: "post",
beforeSend: function() {
$('div.results').html('Please wait');
},
success: function(response){
$('div.results').html(response);
}
how can i format the above to my ajax call

Include form data in the body. Make sure that your await fetch is inside async functions.
$('document').ready( async function() {
$("#test_fetch").submit( async function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
let response = await fetch(url,{
method:"post",
body: $(form).serialize()
});
...
});
});

You have to change the request to POST and pass the data.
Then read the data from the response
$(":submit").click(async (event) => {
event.preventDefault();
$('div.results').html('Please wait');
let response = await fetch("page.cfm", {method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: $('#form').serialize()});
const html = await response.text();
$('div.results').html(html);
});

Related

ajax promise gets overidden

first i call getLiveData which gets data from the server
then some parts of ui are rendered and these parts calls bindLiveData with Id
sometimes data comes later then some parts of UI thats why i wait till request is done.
The problem gots tricky when there is an exception, since the method is called itself again (in realilty up to couple of times)
I will not have calls from UI again , since they call bindLiveData once after render
so In fail method i could grab all Ids and on next successfull ajax reqest i could assinged data.
But what happens then with my infoDataPromise ?? since it will be overidden on error
Does all 'fails' of the previous reqest will fire ? How to avoid this promise gets overriden?
var infoDataPromise;
var mydata;
function getLiveData() {
infoDataPromise = $.ajax({
type: "POST",
dataType: 'JSON',
contentType: 'application/json',
url: "someUrl",
success: function (data) {mydata = data; },
error: function () {
getLiveData();
}
});
}
function bindLiveData(Id) {
infoDataPromise.done(() => {
if (mydata) {
var item = mydata.find(x => x.Id === Id);
adjustUIForId(item);
}
}).fail(() => {
mydata = null;
});
}
Don't write functions that manipulate globals.
Return promises from functions instead
Use async/await syntax to make promises easier to manage
Use recursion to handle your retry attempts
const getLiveData = async () => {
const config = {
type: "POST",
dataType: 'JSON',
contentType: 'application/json',
url: "someUrl"
};
try {
return await $.ajax(config);
} catch (e) {
console.log(e);
return getLiveData();
}
}
const handleData = async () => {
const data = await getLiveData();
if (!data) return;
const item = data.find(x => x.Id === Id);
adjustUIForId(item);
};
handleData();
Now getLiveData returns a single promise that resolves when there is a successful request and you don't need to worry about any other promises. There's no overwriting going on.

send post and get request on click using NEXT JS

i need to post and get my data when clicking on the same button [like write and show comment] , but when i click the button everything is going well but a request with 304 status code is running with infinite loop, can someone help ?
const addCommentHandler = (commentData) => {
axios({
url: `/api/comment/${eventId}`,
method: "post",
data: commentData,
headers: {
"Content-type": "application/json",
},
}).then((res) => {
const data = res.data;
console.log(data);
});
axios({
url: `/api/comment/${eventId}`,
method: "get",
}).then((res) => {
const data = res.data;
setComments(data.comments);
});
};
useEffect(() => {
addCommentHandler();
}, []);
It seems like You want to Post the Data and then want to get the Updated Comments.But you are creating Two Asynchronous Api Calls..
304 Status Code Means " The requested resource has not been modified since the last time you accessed it "
Please Refresh Cache and try Again..
const addCommentHandler = async (commentData) => {
// add Try Catch for Errors..
const responseData = await axios({
url: `/api/comment/${eventId}`,
method: "post",
data: commentData,
headers: {
"Content-type": "application/json",
},
})
const resData = await axios({
url: `/api/comment/${eventId}`,
method: "get",
})
setComments(resData.data.comments);
};
useEffect(() => {
// Pass CommentData as Params in addCommentHandler
addCommentHandler();
}, []);`

How to return JSON data on successfull async ajax request in javascript

I am submitting a form using ajax, How can I pass successful data back to the submission page? I am submitting a transaction over the TRON network so the response is an array with the transaction ID that I would like to return to the submission page.
In php I would use -
$exchange_array = array(
'success' => '1',
);
echo json_encode($exchange_array);
Then in JS
var success = data['success'];
But now I am returning data in JS like follows -
$(".form").submit(function(e) {
var url = "submit.php";
$.ajax({
type: "POST",
url: url,
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function (data) {
// check if successful and return txid
}
});
e.preventDefault();
});
Submit.php -
const sentTx= async () => {
const tx = await tronWeb.transactionBuilder.tradeExchangeTokens(exchangeID, tokenName, tokenAmountSold, tokenAmountExpected, ownerAddress)
const signedtxn = await tronWeb.trx.multiSign(tx, privateKey, 0);
const receipt = tronWeb.trx.sendRawTransaction(signedtxn);
var txid = signedtxn.txID;
// Return txid to ajax request result
};
sentTx();
So how would I return the txid to the ajax request on a successful request?
You may be misunderstanding the concept of asynchrony in javascript.
success method for ajax is not intended for returning anymore. It can run callback - a function, that a doin something.
For example you can write a function that doin something with data:
var myDataReader = function(data) {
console.log(data)
}
and call it from success:
$.ajax
...
success: myDataReader

Ajax from jquery to javascript

I want to convert an ajax function from jquery to plain javascript
I have tried this but it doesn't react the same way as the url doesn't receieve the response when i try with my plain js
Here is my jquery
(function ($){
try{
var event_category = 'a';
var event_name = 'b';
var page_url = 'c';
var url = "myurl";
var data = {
event_category: event_category,
event_name: event_name,
page_url: page_url
};
$.ajax({
crossDomain: true,
type: "POST",
url: "myurl",
data : {event_category: event_category,
event_name: event_name,
page_url: page_url
}
});
} catch(e){console.log(e)};
})(jQuery);
And here is what i tried
var event_category = 'action';
var event_name = 'click';
var page_url = 'test';
var request = new XMLHttpRequest();
request.open('POST', 'myurl');
request.setRequestHeader("Content-Type", "application/json; utf-8");
params = {
event_category: event_category,
event_name: event_name,
page_url: page_url
}
request.send(JSON.stringify(params));
not sure what i should change
Edit:
Base on one of the comments i check the network data on the developer tools
The jquery is having a response on the header of this format
enter image description here
enter image description here
But the javascript is sending the data is this format
enter image description here
Basically the javascript is not sending it on a url params format. Not sure how to force it on how to send it on the same format
Is there any reason not to use the fetch API (it can be polyfilled in crappy browsers...)?
const ajax = async function(url, data) {
try {
const response = await fetch(url, {
credentials: 'include', // like jQuery $.ajax's `crossDomain`
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
// this mimics how jQuery sends POST data as querystring by default
body: Object.entries(data).map(([key, val]) => `${key}=${val}`).join('&'),
});
data = await (
response.headers.get('content-type').includes('json')
? response.json()
: response.text()
);
console.log(data);
return data;
} catch(err) { console.log(err) };
}
ajax('myurl', {
event_category: 'a',
event_name: 'b',
page_url: 'c',
});

How to get multiple ajax responses in one function

I don't know if it's possible, but i'm trying to get multiple ajax responses and access it's values in another function.
I actually get the responses (twice each), but i'm not able to return the responses individual values.
JSFiddle
function firstResponse() {
const response1 = $.ajax({
url: 'https://cors-anywhere.herokuapp.com/http://api.icndb.com/jokes/random',
method: 'GET',
contentType: 'application/json',
});
response1.done(function(response1) {
test(response1);
})
}
function secondResponse() {
const response2 = $.ajax({
url: 'https://cors-anywhere.herokuapp.com/https://official-joke-api.appspot.com/random_joke',
method: 'GET',
contentType: 'application/json',
});
response2.done(function(response2) {
test(response2);
})
}
firstResponse();
secondResponse();
function test(response1, response2) {
console.log('Response 1', response1);
console.log('Response 2', response2);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
There are various ways to achieve that. I personally would go with promises.
function firstResponse() {
return $.ajax({
url: 'https://cors-anywhere.herokuapp.com/http://api.icndb.com/jokes/random',
method: 'GET',
contentType: 'application/json'
});
}
function secondResponse() {
return $.ajax({
url: 'https://cors-anywhere.herokuapp.com/https://official-joke-api.appspot.com/random_joke',
method: 'GET',
contentType: 'application/json'
});
}
function test() {
Promise.all([
firstResponse(),
secondResponse()
]).then(result => {
console.log(result);
});
}
test();
In the test function you call a Promise.all which waits for all the individual promises to be resolved and outputs the result as an array in the order the of the promises passed to it at the time of calling.
let urls = ['https://cors-anywhere.herokuapp.com/http://api.icndb.com/jokes/random',
'https://cors-anywhere.herokuapp.com/https://official-joke-api.appspot.com/random_joke'];
let structure = {
method: 'GET',
contentType: 'application/json',
};
async function first() {
try {
const response = await $.ajax({
url: urls[0],
structure,
});
return response;
} catch(error) {
// Error
}
}
async function second() {
try {
const response = await $.ajax({
url: urls[1],
structure,
});
return response;
} catch(error) {
// Error
}
}
async function test() {
let response = await ('s')
return response
}
first()
.then(() => second());
Ajax calls are asynchronous so if you want to handle the two results in one function you have to do a counter yourself, something like this for the simplest kind:
function firstResponse() {
const response1 = $.ajax({
url: 'https://cors-anywhere.herokuapp.com/http://api.icndb.com/jokes/random',
method: 'GET',
contentType: 'application/json',
});
response1.done(function(response1) {
test("response1", response1);
})
}
function secondResponse() {
const response2 = $.ajax({
url: 'https://cors-anywhere.herokuapp.com/https://official-joke-api.appspot.com/random_joke',
method: 'GET',
contentType: 'application/json',
});
response2.done(function(response2) {
test("response2", response2);
})
}
var responses = [];
firstResponse();
secondResponse();
function test(index, data) {
responses[index] = data;
if (Object.keys(responses).length === 2) processResponses();
}
function processResponses() {
console.log(responses);
}
There are various more advanced way to handle it, like using async/await or something, but this should get your work done without much modification to your existing code.
UPDATE: for the async/await way which is my preferred way of doing things nowadays:
(async () => {
const response1 = await $.ajax({
url: 'https://cors-anywhere.herokuapp.com/http://api.icndb.com/jokes/random',
method: 'GET',
contentType: 'application/json',
});
const response2 = await $.ajax({
url: 'https://cors-anywhere.herokuapp.com/https://official-joke-api.appspot.com/random_joke',
method: 'GET',
contentType: 'application/json',
});
console.log(response1);
console.log(response2);
})();

Categories