Converting fetch to ajax for use in stripe integration - javascript

I have a problem with fetch on mobile google chrome. I want to try to convert it to ajax. I am using it for stripe implementation in php. This what I have done using fetch :
var createCheckoutSession = function(planId) {
var plan = {
plan_id: planId
};
var data = new FormData();
// we call the create my session page by providing a Plan ID which in turn will return a session object whose ID will be useful later on to redirect to checkout.
data.append( "plan", JSON.stringify( plan ) );
return fetch("/create-my-session", {
method: "POST",
body: data
}).then(function(result) {
console.log(result);
return result.json();
});
};
in create-my-session page I have this code:
$stripeService = new StripeService();
$plan = json_decode($_POST["plan"]);
$planId = $plan->plan_id;
$session = $stripeService->createCheckoutSession($planId);
echo json_encode($session);
The above code is executed on click of this button :
$('#subscribe').on('click',function(e){
createCheckoutSession(MyChosenPlanID).then(function(data) {
stripe.redirectToCheckout({
//we redirect the user to a checkout page hosted by stripe that uses the session ID returned above
sessionId: data.id
}).then(handleResult);
});
});
what i have done so far in converting to ajax:
var createCheckoutSession = function(planId) {
var plan = {
plan_id: planId
};
var datastream = new FormData();
datastream.append( "plan", JSON.stringify( plan ) );
$.ajax({
type: "POST",
url: "/create-my-session",
data: {
'info': datastream,
},
dataType: 'json',
success: function(data){
var sessionobj = data;
},
error:function(response)
{
console.log("Data sending failed");
console.log(response);
}
});
return sessionobj ;
}).then(function(result) {
console.log(result);
return result.json();
});
};
and I kept everything else as it is.

Related

store binary data of media(image/video) received from whatsapp cloud API

i have to store binary data of which i received from whatsapp cloud api. i am using node js but unable to send the file data using form data
here is reference i have referred https://developers.facebook.com/docs/whatsapp/cloud-api/reference/media#example-2
function handleMedia(id, number) {
mediaServiceApi(id).then((res) => {
console.log(res.data.url);
console.log(res.data.mime_type);
getMediaData(res.data.url).then((res) => {
var datafm = new FormData();
datafm.append("mobile_number", `${number}`);
datafm.append("category", "1");
datafm.append("ticket_type", "1");
datafm.append("subject", "Device not working");
datafm.append("description", "my device is not working");
datafm.append("document", res);
var config = {
method: "post",
url: "",
headers: {
"Access-Token": "",
"Content-Type": "multipart/form-data",
...datafm.getHeaders(),
},
data: datafm,
};
axios(config)
.then(function (response) {
console.log(
"this is JSON data of ticket created",
JSON.stringify(response.data)
);
})
.catch(function (error) {
console.log(error);
});
});
let textmsg = `We have registered your query with refrance of a media`;
textServiceApi(textmsg, number);
});
}
in the getMediaData() api call we have to define "responseType" as a "streame" which will get the binary data as a streme format axios call and we have to pass "res.data" instead of just res.
thanks

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',
});

AJAX: send data from webpage to PHP API

I'm trying to send data to the server API from a webpage but it keeps falling to
'No Connection!' as you will see in the code.
Note:The server, database and the API are working, because I also use it on a phone application that do the same as I'm trying to do here which is post an event to the database.
Here is the webpage code:
function onAddEvent(){
var title = document.getElementById("title").value;
var desc = document.getElementById("desc").value;
var date = document.getElementById("date").value;
var userid = localStorage.getItem("userid");
$.ajax({
url: API_URL,
type: 'POST',
data: {eventname: title, eventdate: date, eventdesc: desc, user_id: userid},
async: true, // set the property here
success: function(data) {
if(data.result == "success"){
alert("Add Event Successfully!");
}
else{
alert("Can't add event");
}
},
error: function(xhr, error) {
//It is falling here
alert('No Connection!');
}
});
}
And here is the PHP API that it will connect to:
function addevent()
{
$new_member_insert_data = array(
'eventname' => $this->input->post('eventname'),
'eventdate' => $this->input->post('eventdate'),
'eventdesc' => $this->input->post('eventdesc'),
'user_id' => $this->input->post('user_id')
);
$insert = $this->db->insert('event', $new_member_insert_data);
return $insert;
}
Remove the code from the function or try calling the function in the API.
//Call the function from your API
addevent();
function addevent()
{
$new_member_insert_data = array(
'eventname' => $this->input->post('eventname'),
'eventdate' => $this->input->post('eventdate'),
'eventdesc' => $this->input->post('eventdesc'),
'user_id' => $this->input->post('user_id')
);
$insert = $this->db->insert('event', $new_member_insert_data);
return $insert;
}

res.send not working properly

I am working with a simple CRUD app with jquery ajax and node.js, just to improve my skills with node and ajax. The thing is that I am doing a post request that is handled with my post router in the node server, and everything is working fine. It adds 1 more product to my products.json file, but in the end it doesn't send the response back to the client, the final res.send("done") doesn't work and I don't know why..
here is the code:
ajax
$("#create-form").on('submit',function(){
event.preventDefault();
var createIn = $("#create-input").val();
$.ajax({
url: '/products',
method:'POST',
data:JSON.stringify({name:createIn}),
contentType: "application/json",
dataType: "json",
success: function(data){
console.log(data);
$("create-input").val("");
$("get-button").click();
}
});
})
node
app.post('/products',function(req,res){
fs.readFile('products.json','utf8',function(err,data){
var result = JSON.parse(data);
var productName = req.body.name;
console.log(req.body.name);
currentId++;
var productId = currentId;
var product = {
name: productName,
id: productId
}
result.products.push(product);
fs.writeFile(__dirname + "/products.json",JSON.stringify(result),'utf8');
});
res.send("post done");
});
This is just the important part of the code, it works and just fails at the end in the res.send.
Your client code is looking for a json response, but you are returning a string.
$("#create-form").on('submit',function(){
event.preventDefault();
var createIn = $("#create-input").val();
$.ajax({
url: '/products',
method:'POST',
data:JSON.stringify({name:createIn}),
contentType: "application/json",
dataType: "json", <--------------
success: function(data){
console.log(data);
$("create-input").val("");
$("get-button").click();
}
});
})
Either delete this line or add on the server side
res.send({"message":"post done"});
This does not answer your question directly but you should ideally not send back the response until you know the work has been done, and you should handle errors. In other words you should use the callbacks. (Too many callbacks can be problematic and you should investigate other patterns - eg promises - bit no need here)
app.post('/products',function(req,res){
fs.readFile('products.json','utf8',function(err,data){
if (err) return res.send("error");
var result = JSON.parse(data);
var productName = req.body.name;
console.log(req.body.name);
currentId++;
var productId = currentId;
var product = {
name: productName,
id: productId
}
result.products.push(product);
fs.writeFile(__dirname + "/products.json",JSON.stringify(result),'utf8', function(err, res) {
if (err) return res.send("error");
res.send("post done");
});
});
});

Categories