Sending data to the backend - javascript

I have used AngularJS and I am a beginner .
I have tried to send the text field and drop down value to the back end (Java). I have successfully sent the text with out no problem. But I have failed to send the drop down value to the back end.
When I turn on the debugger mode in browser it successfully showed the text field value which is "firstName":"mike" but drop down value showed me "stream" "". Can you please give me a solution?

You send JSON object by using POST or PUT methods.
sample example will be
$http({
url: 'Home/Index',
method: "POST",
data: user
})
.then(function(response) {
// success
},
function(response) { // optional
// failed
});
You do not need to convert model objects to JSON the angular does that for you.
see the fiddle for working example
http://jsfiddle.net/bkUEu/458/

Use valid JSON format to send data from front-end to back-end,
{"firstName":"mike", "stream":"aaa"}

As per my knowledge,you cannot send object directly,you need to change the object into json.
JSON.stringify(obj);

Related

Recieving data sent by ajax.post

I would like to send data to a Node.js server running on localhost with ajax. To test this, I wanted to send the input of type text to the server and just log it there.
This is my Post-Function (which is called by clicking on a button):
function answer(){
let data = {
name : $('#send').val()
};
console.log(data);
$.ajax({
type: 'POST',
url: 'http://localhost:3456/MyWebApp/Test',
dataType: 'text',
data: data.name,
success: console.log('post was successfull'),
error: function(textStatus, errorTrown){
console.log(textStatus + " " + errorTrown);
}
});
}
On my Server I try to collect the data with the following function:
app.post('/MyWebApp/Test', function(request,response){
console.log(request.body.data);
});
app.listen(3456);
My problem is, that the value on my server (in the above console.log) is always undefined.
I already tried to send the whole json-Object with dataType-Parameter json instead of text, but then I get an error in my server for trying to read a property value of something undefined. How do I have to implement the app.post function, to make the data readable and work with it?
I hope it is possible to understand what I am trying to achieve and what my problem is, I dont really know much about Node.js or Ajax, still I would be thankful for any help.
You're sending one string value data.name so your http request Content-Type would be plain/text
At NodeJS side you're using express library and it doesn't provide post request body by default.
You need to collect post request body using "data" event
request.on("data", callback);

Google spreadsheet showing undefined values when submitting through an AJAX request

I'm trying to send the data I gathered from my web app to a google spreadsheet.
I'm using the script from Martin Hawksey:
https://gist.github.com/mhawksey/1276293
I've set it up and did everything as shown in the manual. And I am getting data back, but it's showing up as undefined values:
This is the code I use to send the JSON string to my spreadsheet:
function sendData(){
var url = 'https://script.google.com/macros/s/AKfycby3SUJvfEjdHWVoEON0L5hN4uXod8M4Jv1LAIWH3Ny16MIUz9o/exec';
var data = JSON.stringify(member);
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
data: data,
success: function (response) {
console.log("succes! I sent this: " + data);
console.log("got this back: " + JSON.stringify(response));
},
});
}
This gives me a success message, it even tells me which row it was placed on.
This is the JSON string I'm sending:
{"Voornaam":"Name","Achternaam":"Name","Mail":"x#x.com","Verjaardag":"0/0/0000","Foto":"https://graph.facebook.com/xxxxx/picture?width=1020","School":"School X","Richting":"Course X"}
I even checked this JSON with a JSON parser online and it didn't return any errors.
For starters, I'm not entirely sure how to check which string I'm receiving at my spreadsheet. If it's still correct when it arrives. I tried logging it, but can't seem to get any response from the google logger.
If anyone could point out what I'm doing wrong, you would be greatly appreciated!
The Web script expects a JSON object. However, Ajax call is made with a string using the stringify function
var data = JSON.stringify(member);
Modifying the script to make the GET call with JSON object as is resolved the issue, like so
var data = member;

How do I pass form data to PHP and return a json string to Javascript?

Does anyone know how pass form values into PHP and still return the data to JavaScript? (For use in Google Charts if anyone is wondering.)
I have an HTML form with 4 radio boxes. I'd like to pass the value of the form so that my PHP request will be modified based on the user's selection.
The results from the PHP request need to be passed to JavaScript for processing.
In the radio button on click event place a javascript function that will perform an XMLHttpRequest to the php page and have the PHP page echo some JSON content that can be decoded in the return of the XHR in Javascript.
Example of such
May this can help you.
I think that you must do an Ajax request
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( data) {
alert( "Data Saved: " + data);
});
You send data to server form your form (here sent are name and location). You read this data with javascript with OnSelect and transfert it to your PHP code and,
You get back data from server into your JavaScript code and you can do what you want with it.
Sorry if my solution use JQuery, it is better for cross-browser with less code writing !
You could use this line to parse an array into json and use it later in javascript:
json_encode($rows); //format array named $rows into json data
More info: http://php.net/manual/en/function.json-encode.php

How to open a popup and send a JSON object to it

I want to send a JSON object to a PHP file while my script opens that PHP file in a new popup window. Is it possible to send it via POST method (by jQuery or without it)?
If not, how do I convert JSON to a URL encoded string? Is there any JavaScript function?
You may create a form (on the fly) with an input (where you fill the value with the JSON) and a target-attribute regarding to name of the popup (second parameter of window.open()).
Then send this form.
Open the popup: var popup = window.open(...)
Assign the json object to a new variable in the new window: popup.json = ...
Use the variable json in your popup (it will be accessible as window.json or just json from JavaScript code running in the popup).
There's a JSON encoder/decoder that looks like it would do the job. You could call this to encode your object before adding it to your querystring.
Example
alert(JSON.encode([0,1,false,true,null,[2,3],{"some":"value"}]));
// [0,1,false,true,null,[2,3],{"some":"value"}]
alert(JSON.decode('[0,1,false,true,null,[2,3],{"some":"value"}]'))
// 0,1,false,true,,2,3,[object Object]
You can use the Ajax API to do so... In the Ajax API, you can specify the data property and set it a JSON, and it will send the data to the server based on the type you have set, that is, GET or POST.
For example:
$.ajax(
{
url: url, // Your post URL
type:"POST", // or GET
data: {a:1} // In your case, your JSON object
success:function(response){}, // Function that will be called when your posted URL responds
crossDomain: true, // If it's a cross-domain request
dataType: "json" // Response datatype: JSON, text, HTML, XML, etc.
}
);
One thing to note is that if your response needs to be processed, you need to get around the same origin policy set by the browser. Please read about the same. You could use something called JSONP. It's part of the Ajax API.
I hope this is what you want.

How to modify the ajax Post data in a beforeSend event?

Hello I have a form that submits remotely with the jQuery UJS for rails. I binded to the beforeSend event to allow me to modify the data submitting to the serve. It's not working. Here is what I have in the beforeSend:
settings.data = JSON.stringify({
'list_item[title]' : 'hi?? there'
})
This doesn't work. In the server logs I see this:
Started POST "/lists/9/list_items" for 127.0.0.1 at 2011-10-24 14:04:36 -0700
Processing by ListItemsController#create as JSON
Parameters: {"{\"list_item"=>{"title"=>{"\":\"hi?? there\"}"=>nil}}, "list_id"=>"9"}
Any idea what I'm doing wrong? I want to customize the settings.data with added fields that aren't in the form. Thanks
You don't need to stringify anything to put it in settings.data. The data is:
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. [...] Object must be Key/Value pairs.
What you're doing is putting this string:
"{"list_item[title]":"hi?? there"}"
into data but that string is not a query string so things are going to get confused. You should be able to simply assign your JavaScript object to settings.data:
settings.data = { 'list_item[title]' : 'hi?? there' };
and let jQuery sort it out from there.
Update based on evidence rather than documentation:
However, further investigation reveals that this doesn't work. If I send a GET request, any changes I make to settings.data are ignored but if I send a POST request, then changes to settings.data stick but you have to use the query string format to get anything sensible through:
settings.data = encodeURIComponent('list_item[title]')
+ '='
+ encodeURIComponent('hi?? there');
The version of settings.data combined with a POST request gets me this:
Parameters: {"list_item"=>{"title"=>"hi?? there"}}
on the server and that looks like what you're after. If you want to preserve some of the original parameters then you'll have to unpack and repack the query string by hand.

Categories