Reading Json Form data golang - go

I am sending form data in JSON & serialize format to golang server using ajax. I am not able to read those data.
I am using kataras/iris golang framework.
Below is my code -
(function ($) {
$.fn.serializeFormJSON = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
var Contact = {
sendMessage: function() {
return m.request({
method: "POST",
url: "/send/message",
data: JSON.stringify(jQuery('#contact-form').serializeFormJSON()),
withCredentials: true,
headers: {
'X-CSRF-Token': 'token_here'
}
})
}
}
<!-- Data looks like below, what is sent -->
"{\"first_name\":\"SDSDFSJ\",\"csrf.Token\":\"FjtWs7UFqC4mPlZU\",\"last_name\":\"KJDHKFSDJFH\",\"email\":\"DJFHKSDJFH#KJHFSF.COM\"}"
And I am trying to fetch the data from server using below code -
// Contact form
type Contact struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Email string `json:"email"`
}
contact := Contact{}
contact.FirstName = ctx.FormValue("first_name")
contact.LastName = ctx.FormValue("last_name")
contact.Email = ctx.FormValue("email")
ctx.Writef("%v", ctx.ReadForm(contact))
My all data is blank, How to grab the data? I am using https://github.com/kataras/iris golang framework.

One the one hand, you are sending a JSON to the server, but when fetching the parameters you are fetching them as "application/x-www-form-urlencoded", first, send the JSON parameters as JSON and not as string, remove the stringifying, i.e:
instead of:
JSON.stringify(jQuery('#contact-form').serializeFormJSON())
do:
jQuery('#contact-form').serializeFormJSON()
and in your Go file, bind it to your object:
var contact []Contact
err := ctx.ReadJSON(&contact)
good luck :)

Related

Django json loads fails because of empty query dict in request Object

I have ajax call posted to /cart/total where I am dumping JSON string stored in local storage using post when I run json loads it shows me the error.
TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not QueryDict
and my JSON string before parsing looks like having an empty feild, which I am not aware of in Django
<QueryDict: {'{"32":1,"33":1,"34":2}': ['']}>
<script>
function addtocart(mitem, mprice) {
if(localStorage.getItem('cart')==null){
// var mobj = {}
// var countQ ={}
var price = String(mprice)
var mobj = { [String(mitem)]: 1 }
var countQ = {'Quantity':1}
var storeobj = JSON.stringify(mobj)
var storeCountq = JSON.stringify(countQ)
localStorage.setItem('cart', storeobj)
localStorage.setItem('quantity',storeCountq)
console.log(localStorage.getItem('cart'))
}else{
var data = localStorage.getItem('cart')
var quant = localStorage.getItem('quantity')
var obj = JSON.parse(data)
var parsequant = JSON.parse(quant)
if(obj.hasOwnProperty(String(mitem))){
obj['%s',mitem]++
parsequant['Quantity']++
var storeobj = JSON.stringify(obj)
console.log(localStorage.getItem('cart'))
var storeCountq = JSON.stringify(parsequant)
localStorage.setItem('cart', storeobj)
localStorage.setItem('quantity', storeCountq)
}
else{
obj[String(mitem)] = 1
parsequant['Quantity']++
var storeobj = JSON.stringify(obj)
console.log(localStorage.getItem('cart'))
var storeCountq = JSON.stringify(parsequant)
localStorage.setItem('cart', storeobj)
localStorage.setItem('quantity', storeCountq)
}
}
}
function ajaxcall(){
$.ajax(
{
type: "POST",
url: "/cart/total",
data: localStorage.getItem('cart'),
success: function () {
console.log("sent tdata")
}
})
}
ajaxcall()
</script>
<p style="position: absolute; bottom: 0px"><button class="button" style="width: 200px" onclick="addtocart( '{{M.Menu_Item_Id}}', '{{M.Menu_ItemPrice}}' )" >Add to cart</button>
view function
#csrf_exempt
def cartpricecalculator(request):
if request.method == 'POST':
data = json.loads(request.POST)
print(request.POST)
return HttpResponse('200 Okay')
I am not sure what I am doing wrong, any help is appreciated.
request.POST is for form data. You need;
data = json.loads(request.body)
Try:
In JS, pass a dict instead of a string. As per the documentation of ajax, data must be an Object with key and value or stringify of an Object with key and value.
Ref: https://api.jquery.com/jQuery.ajax/
function ajaxcall(){
$.ajax(
{
type: "POST",
url: "/cart/total",
data: {'cart': localStorage.getItem('cart')},
success: function () {
console.log("sent tdata")
}
})
}
In python
#csrf_exempt
def cartpricecalculator(request):
if request.method == 'POST':
cart_data = json.loads(request.POST.get('cart', '{}'))
print(request.POST)
print(request.POST.get('cart'))
return HttpResponse('200 Okay')

Web API Post Type action is not getting called by jquery ajax

This is how my web api action look like.
[System.Web.Http.HttpPost, System.Web.Http.Route("BookAppointment/{email}/{id}")]
public System.Net.Http.HttpResponseMessage BookAppointment(string email, int id = 0)
{
System.Net.Http.HttpResponseMessage retObject = null;
if (id > 0 && email!="")
{
UserAppointmentService _appservice = new UserAppointmentService();
bool success = _appservice.BookAppointment(email,id);
if (!success)
{
var message = string.Format("error occur for updating data", id);
HttpError err = new HttpError(message);
retObject = Request.CreateErrorResponse(System.Net.HttpStatusCode.NotFound, err);
retObject.ReasonPhrase = message;
}
else
{
retObject = Request.CreateResponse(System.Net.HttpStatusCode.OK, "SUCCESS");
}
}
else
{
var message = string.Format("doc id and emial can not be zero or blank");
HttpError err = new HttpError(message);
retObject = Request.CreateErrorResponse(System.Net.HttpStatusCode.NotFound, err);
retObject.ReasonPhrase = message;
}
return retObject;
}
This is my jquery ajax code which suppose to call web api action but throwing error. the error is
No HTTP resource was found that matches the request URI
'http://localhost:58782/api/Appointments/BookAppointment'.
My jquery ajax code as follows.
$('#tblAppointments').on('click', '#btnbook', function () {
var docid = $(this).closest('tr').find("input[id*='hdndocid']").val();
var email = $(this).closest('tr').find("input[id*='hdnpatientemail']").val();
var baseurl = '#ConfigurationManager.AppSettings["baseAddress"]' + 'api/Appointments/BookAppointment';
// + encodeURIComponent(email) + '/' + docid;
alert(baseurl);
$.ajax({
url: baseurl,
type: 'POST',
dataType: 'json',
contentType: "application/json",
data: JSON.stringify({ email: encodeURIComponent(email), id: docid}),
success: function (data, textStatus, xhr) {
console.log(data);
},
error: function (xhr, textStatus, errorThrown) {
var err = eval("(" + xhr.responseText + ")");
alert('Error ' + err.Message);
console.log(textStatus);
}
}).done(function () {
});
});
I have only default route in web api config.
Please tell me what kind of mistake i have done for which it is not working. thanks
There are more problems with your code so I will try to explain them step by step.
1.Based on the code you have provided, you must have decorated your controller with a route like
[RoutePrefix("api/appointments")]
in order to correctly call the BookAppointment method.
If you decorate your controller with this attribute, then you can simply call
http://localhost/api/appointments/BookAppointment/testemail#domain.com/1
and the method would be 100% called.
2.The following code:
var baseurl = '#ConfigurationManager.AppSettings["baseAddress"]' + 'api/Appointments/BookAppointment';
// + encodeURIComponent(email) + '/' + docid;
translates into something like
http://localhost/api/Appointments/BookAppointment
so the necessary part (email/id) are not given (that's why the error message is given).
3.The javascript code makes a POST with JSON in body but your API is not accepting JSON body.
I recommend that you create a separate class like this:
public class BookAppointmentRequest
{
public string Email { get; set; }
public int ID { get; set; }
}
And after that, you modify the method in order to specify that you are accepting data from body.
[HttpPost, Route("BookAppointment")]
public HttpResponseMessage BookAppointment([FromBody] BookAppointmentRequest request)
After that, you can simple make a POST to api/Appointments/BookAppointment with the JSON from your javascript code.
I recommend you to use IHttpActionResult instead of HttpResponseMessage. See this link.

I need to connect my front-end Javascript code to my sever-side NodeJS code. How do I do this?

We are very new to programming and have a simple question. We are developing a very simple Google search app that searches strings on Google using client-server communication. We have a simple subset of Javascript here:
var firstName = some_string
var lastName = some_string
var googleSearch = firstName + lastName;
googleSearch = JSON.stringify(googleSearch);
We need to link this code to our NodeJS code to do the actual searching.
var google = require('google');
google.resultsPerPage = 25;
var nextCounter = 0;
google(googleSearch, function(err,res) { // Note googleSearch is from
// the frontend Javascript code
// that we want to pull the data from.
if (err console.error(err)
var link = res.links[0];
console.log(link.href);
var myLink = link.href;
})
We want to take the data from the googleSearch variable from our front-end code and utilize it in our server-side code. Then we want to display the data from myLink , which is in our server-side code, back into our front-end code.
What you need to do is make an Ajax request from your front end to your server.
If you use jquery, you can do something like this
$.ajax({
url: YOUR_SERVER_URL+"/getData",
data: {
"google_search": googleSearch,
},
method: "GET",
//use data type json if your server returns json
dataType: "json",
success: function(result) {
console.log("data fetched Successfully");
//result is the data your server returned.
console.log(result);
},
error: function() {
console.log("Something went wrong, data could not be fetched");
}
});
On your server side if you are using Express with Node,
you can return JSON by doing something like this:
var app = express();
app.get('/getData', function(req, res, next) {
var google = require('google');
google.resultsPerPage = 25;
var nextCounter = 0;
//getting query data that you passed from front end
var googleSearch = req.query.google_search;
google(googleSearch, function(err, res) {
if (err console.error(err) var link = res.links[0]; console.log(link.href);
var myLink = link.href;
})
//sending json data as response
res.json(myLink);
});
If you are using localhost, then your server url will be something like "https://localhost:5000".

Unable to extract the string i want from the ajax post

In my asp mvc project i've got an ajax call that posts the value of a dropdown list and i want the session to be set with this value.
$('#dropDownMenu').on('click', 'li', function () {
var txt = $('#schoolButtons').text();
data = {session: txt};
var requestValue = JSON.stringify(data);
$.ajax({
url: '#Url.Action("SetSession")',
type: 'POST',
data: "requestValue="+requestValue ,
}).success(function (data, textStatus, jqXHR) {
});
});
public ActionResult SetSession(string requestValue)
{
var sessionVal = Convert.ToString(requestValue);
if (sessionVal==null)
{
Debug.WriteLine("session is null");
}
Session["key"] = sessionVal;
return Json(requestValue);
}
When I output the value of the session i'm getting the string {"session":"State School"} when all i want is "State School". I know in the function data is set to {session: txt} but how do i just extract that txt?
Regards,
Mike.
To read the JSON value you need to read it this way
var requestValue = data.session
Since you pass it as a string into the function and want to read it in the function, this is what I sugggest you do. You need to convert the string to JSON and extract the value.
public ActionResult SetSession(string requestValue)
{
var JSONData = JSON.parse(requestValue);
var sessionVal = JSONData.session;
...
...

Node.js modified AJAX insertion to MongoDB

I am succesfully posting an AJAX insert in my MondoDB database.
The user is supposed to fill in 3 fields,
Full Name
Email
Phone
What I would like to do is:
generate a random number in server-side and save it as a 4th field in my MongoDB.
Also I would like to post it as a response back to the user.
Here is my users.js file (server-side)
* POST to adduser.
*/
router.post('/adduser', function(req, res) {
var db = req.db;
var codeResponse = generateCode();
db.collection('userlist').insert(req.body, function(err, result){
res.send(
(err === null) ? { msg: '',code: codeResponse } : { msg: err }
);
});
});
function generateCode(){
var code = Math.random() *1000000;
code = Math.floor(code);
return code;
}
And this is my AJAX call(client-side)
var newUser = {
'id2': id2,
'fullname': $('#addUser fieldset input#inputUserFullname').val(),
'email': $('#addUser fieldset input#inputUserEmail').val(),
'phone': $('#addUser fieldset input#inputUserPhone').val(),
}
$.ajax({
type: 'POST',
data: newUser,
url: '/users/adduser',
dataType: 'JSON'
}).done(function( response ) {
// Check for successful (blank) response
if (response.msg === '') {
console.log(response);
}
else {
alert('Error: ' + response.msg);
}
});
Easy enough, add it to your object before insert and post back the object:
router.post('/adduser', function(req, res) {
var db = req.db;
var document = req.body;
var codeResponse = generateCode();
document.code = codeResponse;
db.collection('userlist').insert(document, function(err, result){
if (err) //do something
return;
else
res.send(document);
});
});

Resources