Javascript AJAX + JQuery posts empty data - javascript

I am new to web programming and am struggling with a basic task. I am trying to do a simple POST from my frontend to my backend and with it send data in the form of a JSON object. I specifically do not want to embed my javascript code in my HTML file. Please note that all the code shown is all the code used for this POST purpose, so if it looks like I am missing something I most likely am. My frontend JS code is as follows:
/**/
function Test_Button_Pressed() {
$.ajax({
type: "POST",
url: "/test",
dataType: "json",
data: {Name: "Rikus", Value: 123},
contentType: "application/json",
dataType: "json",
success: function (result) {
console.log(result);
},
error: function (err) {
console.log("Error: ", err); //just use the err here
}
});
}
/**/
function Activation_Button_Pressed(Button_ID) {}
/**/
function Button_Pressed(Button_ID) {}
The following is logged in the Chrome console when the backend response was made:
Error: [object Object]
The backend code is as follows:
const Api = require("./Api");
var Communication = {};
/**/
Communication.SetUp = function (PanelApp, DataApp) {
PanelApp.post('/test', (req, res) => {
console.log(req);
console.log(req.params);
console.log(req.body);
res.send("Done");
});
};
module.exports = Communication;
Bothe the
console.log(req.body)
and
console.log(req.params)
returns: {}
so from what I can see my routing is correct, it's only my data sending that does not work. Please help and thank you in advance.

After some help the working code is as follows:
Frontend:
/**/
function Test_Button_Pressed() {
$.ajax({
type: "POST",
url: "/test",
dataType: "json",
data: {Name: "Rikus", Value: 123},
dataType: "json",
success: function (result) {
console.log(result);
},
error: function (err) {
console.log("Error: ", err); //just use the err here
}
});
}
/**/
function Activation_Button_Pressed(Button_ID) {}
/**/
function Button_Pressed(Button_ID) {}
Backend
const Api = require("./Api");
var Communication = {};
/**/
Communication.SetUp = function (PanelApp, DataApp) {
PanelApp.post('/test', (req, res) => {
console.log(req.body.Name);
console.log(req.body.Value);
res.json("Done");
});
};
module.exports = Communication;

Related

ajax type : patch is not working 400 (Bad Request)

i'm trying to update data in my local database server using ajax query in client server with api but it's not working i always get this error
jquery.min.js:4 PATCH http://127.0.0.1:3000/todo/62ff7276c2776726906f49d9 400 (Bad Request)
and this my code
const _update = (docId,itemId,content) => {
$.ajax({
type: 'PATCH',
url: docId + "/" + itemId,
data: {content:content},
contentType: 'application/json',
success: function (response, textStatus, xhr) {
console.log(response)
},
error: function (xhr) {
console.log(xhr);
}
});
}
i tested my api by postman and it worked perfectly , this id my router
router.patch('/todo/:id', async (req, res) => {
try {
const id = req.params.id
const todo = await Todo.findByIdAndUpdate(id, req.body, { new: true })
if(!todo)res.status(404)
res.send(todo)
} catch (e) {
res.status(400).send(e)
}
})

React - WP_Mail works with jQuery but not axios

I have a contact form in my React app and I am attempting to have the form send an email using WP_Mail. I am trying to do that using Axios, but I can't seem to get it to work. I get a 400 error on the admin-ajax call.
axios.post(url, {
action: 'send_form',
data: {
email: 'test#test.com',
message: 'testing'
}
})
.then(function (response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
I am able to get it to work using jQuery, but I'd rather not have to use that if possible:
$.ajax({
url: url,
dataType: 'json',
data: {action: 'send_form', email: 'test#test.com'},
cache: false,
success: function(data) {
console.log(data);
}.bind(this),
error: function(xhr, status, err) {
alert(err.toString());
}.bind(this)
});
I think the issue has to do with the format of the payload header. When I use Axios, the data comes through as JSON payload header, but when I use jQuery it comes through as query string parameters.
Can you try:
let form_data = new FormData;
form_data.append('action', 'send_form');
form_data.append('email', 'test#test.com');
form_data.append('message', 'testing');
axios.post(url, {
form_data
})
.then(function (response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});

failed to send and recieve form data object with react and nodejs

I am trying to sent my form data to node js and retrieve at there.But I am failed to do it with form data object.
handleSubmit(data) {
console.log(data);
const forms=new FormData();
forms.append('fname','pranab');
let promise=fetch('http://localhost:8080/reactTest', {
method:'POST',
mode:'CORS',
body:JSON.stringify(forms),
headers:{
'Content-Type':'application/json',
'Accept':'application/json'
}
}).then(res =>res.json()).then(result => console.log(result))
}
in the above code I am sending form data object to the serve side.At the server side I am trying to retrieve it using below code.
app.post('/reactTest',function(req,res) {
var contents=req.body;
console.log(contents);
return res.send({status:'working'});
})
but it displays nothing in the console.What the issue here is?
output is
titech#titech-System-Product-Name:/var/www/html/nodejs$ node index.js
port listening on 8080
{}
when i trying to console it with 'req.body.fname' it gives 'undefined' as output in place of '{}'.
Looks like you need some function to convert formData to JSON. Like this one:
function formData2Json(formData){
let ret={};
for(let pair of formData.entries()) {
let val=ret[pair[0]];
if (!val) {
ret[pair[0]]=pair[1];
}
else {
if (Array.isArray(val)) {
val.push(pair[1]);
}
else {
ret[pair[0]]=[val,pair[1]];
}
}
}
return ret;
}
and than replace body:JSON.stringify(forms) with body:JSON.stringify(formData2Json(forms))
try this it may help
var bodyFormData = new FormData();
bodyFormData.set('userName', 'Fred');
axios({
method: 'post',
url: 'myurl',
data: bodyFormData,
config: { headers: {'Content-Type': 'multipart/form-data' }}
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});

Sending data to Firebase Cloud Function via Ajax

I am trying to send data through post OR get to firebase cloud function but couldn't get it work.
Here is my ajax:
$.ajax({
url: 'https://us-ceXXX1-reXXXts-fXXa-pr.cloudfunctions.net/helloWorld',
dataType: "json",
method: 'GET',
crossDomain: true,
body: {
mobileNo: "WzkyMzXXXXXXXXXXXc5ODBd"
},
success: function(data){
console.log('succes: '+data);
}
});
And Here Is Cloud Function:
exports.helloWorld = functions.https.onRequest((request, response) => {
var responsez = response;
console.log("DATA IS:"+request.data); //prints undefined
console.log("BODY IS:"+JSON.stringify(request.body)); //prints BODY ID: {}
var mobNo = request.body.mobileNo;
var options = {
body: {mobileNo: mobNo, applicationVersion: "1.0"},
url: 'http://nxxxpi.fixxxa.wxb.pk/GetxxxxxxoUxr',
headers: {
'appKey':'jDxxxxxxxOr',
'appId':'2xxxxx9'
},
json: true
}
cors(request, response, () => {requestz.post(options, function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
responsez.send(JSON.stringify(body));
})});
});
And It console logs.
DATA IS: undefined
BODY IS: {}
EDIT: HERE IS THE FIREBASE CONSOLE:
After adding:
console.log("BODY MOBILE:"+JSON.stringify(request.body.mobileNo));
console.log("ONLY MOBILE:"+JSON.stringify(request.mobileNo));
There are few issues in your code
change the method to POST instead of GET in your ajax call as you are passing the data in request body
use the data property instead of body in the ajax call . it should work now. The data will be available in request.body inside the firebase function
$.ajax({
url: 'https://us-ceXXX1-reXXXts-fXXa-pr.cloudfunctions.net/helloWorld',
dataType: "json",
method: 'POST',
crossDomain: true,
data: {
mobileNo: "WzkyMzXXXXXXXXXXXc5ODBd"
},
success: function(data){
console.log('succes: '+data);
}
});

Asynchronous Javascript Request Issue (Node, request-promise module)

I am building an application and having an issue with making a request from the client, sending it to my server, having the server make the API call and then send the result back to the client. I am using Node and the Request-Promise module.
Here is the client side code:
$(document).ready(function() {
var artistSearch = () => {
const q = $('.artistName').val();
$.ajax({
type: "POST",
url: "http://localhost:3000/request",
data: {artist: q},
})
.done(function(data) {
console.log('data: ', data)
})
};
$(".artistSearch").submit( () => {
artistSearch();
});
});
This successfully makes a request to the server:
app.post('/request', (req, res) => {
const artist = req.body.artist;
const searchURL = "https://api.spotify.com/v1/search? q="+artist+"&type=artist";
var targetObj;
var options = {
uri: searchURL
};
rp(options)
.then(function (data) {
console.log(data);
res.send(data);
})
.then(function() {
console.log('complete');
})
.catch(function (err) {
console.log('error')
});
});
Which ultimately successfully grabs the data from the API call, but never sends it back to the client! If I do res.send() outside of my .then promise, I can receive data on the client end.
Is there something I am missing? Thanks in advance!
Try this
var options = {
uri: searchURL,
simple: false,
};
rp(options)
.then(function (data) {
console.log(data);
res.status(200).send(data).end();
})
.then(function() {
console.log('complete');
})
.catch(function (err) {
console.log('error')
});
I think the client did receive data, but the connection didn't terminate correctly as it thinks there are more data. This is because you didn't specify the header and the module http couldn't figure out the content-length.
rp(options)
.then(function (data) {
console.log(data);
// res.send(data);
// assume data is JSON.
res.setHeader (200, {'Content-Type': 'application/json',
'Content-Length':data.byteLength});
res.end(data); //Send data immediately.
})
...
If data is a string, you will need to use data.length instead. In fact, if data is a string, then by default the header is {'Content-Type': 'application/json', 'Content-Length':data.length}

Categories

Resources