I am successfully calling a server side function from the client side with Ajax, but i cant figure out how to pass an array with the function call. As you can see, i am trying to get data out of the data tag on the server side but i am not getting the values i passed.
How do i get the "hi", "hello" text passed to the server function?
Client Side Ajax Calling Function:
function ClientSide()
{
var info = [];
info[0] = 'hi';
info[1] = 'hello';
var json = JSON.stringify(info); //pass this
$.ajax({
type: 'post',
url: '/save',
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (html) {
// use data
}
})
}
Server Side Function:
app.post('/save', function(req,res,data)
{
var Passed_value = data;
console.log(Passed_value);
});
First... your data is stored in req.body, not in third argument that you added.
Second... if you are getting JSON in string, you got to parse it before using it as an object...
Code:
app.post('/save', function(req,res)
{
var Passed_value = JSON.parse(req.body);
console.log(Passed_value);
});
Related
This will be an easy one for you, but after ages of looking online I can't find a solution, or at least one I'm understanding.
result and users variables both alert correctly.
The data contents shows empty - why?
How should I be inserting these two variables into data ?
(also if it is right - how do I view the data content without going into server side)
Thank you in advance.
var result = result.text;
var users = localStorage.getItem('user');
alert("1");
$.ajax({
url:'********',
method: 'POST',
data: {user: users, serial: result},
dataType: "text",
contentType: "application/json",
success: function(data){
alert (data);
alert(users);
alert(result);
In your code alert(data) will refer to the data returned by the server. Not the data of your ajax request.
$.ajax() takes a settings object as its parameter. It's a set of key/value pairs that configure the Ajax request. data is just one of the keys of the object you are passing to the $.ajax() method.
To simplify your code, this is what is happening:
// this is what you're sending to the server
var dataSentToTheServer = {
user: users,
serial: result
}
// creating an object where data, url, success etc are keys.
var settings = {
url:'api/method',
method: 'POST',
data: dataSentToTheServer,
dataType: "text",
success: function (dataSentFromTheServer) {
alert(dataSentFromTheServer); // this argument will have the data returned by your server
alert(dataSentToTheServer); // data which was sent *to* the server
alert(data); // doesn't exist
}
....
}
$.ajax(settings);
I am working on a cordova mobile application and I want to take all the data from a php page which displays the data in JSON and stores it in a global variable for local access.
here my JSON data:
{"success":1,"message":"Details Available!","details":[{"ID":"4","cohort_name":"Stuart Little","pin":"53870","start_date":"2014-08-02"},{"ID":"5","cohort_name":"Lexi Belle","pin":"19224","start_date":"2014-08-04"},{"ID":"6","cohort_name":"Joe Bloggs","pin":"12345","start_date":"2014-08-04"}]}
The method of which I am going to get this data is as follows:
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': URL goes here,
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();
The problem is that I am borrowing a web server to run the backend where I pull the data from and I only have an IP address to route the ajax request to the page. Is there any other way for me to get the data and store it? Or how do I use an IP address in this kind of request?
If you only request JSON data via a GET request, this shortcut might work, too:
$.getJSON("http://127.0.0.1/script.php?output=json", function(json) {
console.log("JSON Data:" + json);
});
jQuery.getJSON
Alternative:
var url = 'http://127.0.0.1/script.php?output=json';
return $.ajax({
type: "GET",
url: url,
}).done(function (data) {
console.log("JSON Data:" + data);
});
I have an key value pair array which I need to send to another function through ajax. My array looks something like this
var vitals=new Array();
var vitals["height"]=170;
var vitals["weight"]=55;
the ajax function is
$.ajax({
type: "POST", //GET or POST or PUT or DELETE verb
url: url, // Location of the service
data: JSON.stringify({ccdEntity: vitals }), //Data sent to server
contentType: "application/json; charset=utf-8", // content type sent to server
dataType: "json", //Expected data format from server
processdata: true, //True or False
success: function (msg) {//On Successfull service call
ServiceSucceeded(msg);
}
and the function receiving the value is
public bool GenerateCcd( Array ccdEntity)
when I run the program the function does not display the array with key-values but when I transfer a normal array (i.e) vitals[0]=170, it works fine . Do I need to make an changes for sending the above data to function?
Edit:
Tried passing the above array as a JSON object
var vitals= {
"height": "170",
"weight": "55"}
but results still the same
Use something like this::
function TestAjax() {
var vitals= [];
for (var i = 0; i < 5; i++) {
vitals.push({ Height: (170+i), Weight: (55+i) });
}
$.ajax({
type: 'POST',
url: url,
contentType: "application/json",
data:JSON.stringify( {vitals: vitals}),
success: function (data) {
alert("Succeded");
}
});
}
Make your vitals an object array rather than an array;;
var vitals={'height': '170', 'weight': '55'};
And post your data like:
data: JSON.stringify(vitals)
In data from server I get the following JSON:
{
"response": {
"upload_url": "http:\/\/cs9458.vk.com\/upload.php?act=do_add&mid=6299927&aid=-14&gid=0&hash=73e525a1e2f4e6a0f5fb4c171d0fa3e5&rhash=bb38f2754c32af9252326317491a2c31&swfupload=1&api=1&wallphoto=1",
"aid": -14,
"mid": 6299927
}
}
I need to get upload_url. I'm doing:
function (data) {
var arrg = JSON.parse(data);
alert(data.upload_url);
});
but it doesn't work (alert doesn't show).
How do I get parameter upload_url?
It looks like you need to access arrg, not data. Also you need to access the 'response' key first.
function (data) {
var arrg = JSON.parse(data);
alert( arrg.response.upload_url);
}
There are several correct answers here, but there is one trigger that decides how you should handle your returned data.
When you use an ajax request and use JSON data format, you can handle the data in two ways.
treat your data as JSON when it returns
configure your ajax call for JSON by adding a dataType
See the following examples:
returned data string:
{"color1":"green","color2":"red","color3":"blue"}
ajax call without dataType:
$.ajax({
method: "post",
url: "ajax.php",
data: data,
success: function (response) {
var data = JSON.parse(response);
console.log(data.color1); // renders green
// do stuff
}
});
ajax call with dataType:
$.ajax({
method: "post",
url: "ajax.php",
dataType: "json", // added dataType
data: data,
success: function (response) {
console.log(response.color1); // renders green
// do stuff
}
});
In your case you probably used JSON.parse() when the call was already configured for JSON. Hope this makes things clear.
If response is in json and not a string then
alert(response.id);
or
alert(response['id']);
otherwise
var response = JSON.parse('{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}');
response.id ; //# => 2231f87c-a62c-4c2c-8f5d-b76d11942301
Your code has a small error. try:
function (data) {
var arrg = JSON.parse(data);
alert(arrg.response.upload_url);
});
Let me start by saying I am not extremely familiar with Javascript and I cannot figure out what is going on here.
I have the following function:
self.search = function () {
var searchTerms = {
"City": this.cityName,
"State": this.stateName,
"StoreNumber": this.storeNumber,
};
$.ajax("/api/SearchApi", {
data: searchTerms,
type: "POST", contentType: "application/json",
success: function (result) {
alert(result);
}
}
});
When I submit, what happens is that instead of submitting a nice JSON object as expected, it submits a JSON objected formatted as so: "City=testing&State=AL&StoreNumber=test "
Ideally I would like to use a GET method that passes the object to my server so that I can return the results, but when I use a get method, it simply appends the above to the API call url resulting in a URL request formed as so: http://localhost:57175/api/SearchApi?City=testing&State=AL&StoreNumber=test
Any help would be appreciated.
Make sure you add the dataType of JSON to your $.ajax({ }); object. That should solve the problem!
$.ajax({
// ...
data : JSON.stringify( searchTerms ), // Encode it properly like so
dataType : "json",
// ...
});
2 Things
Add the json content type(not the data type) to your ajax object important to note is the charset your server is using in this case utf-8.
Use the Json2 Library to stringify and parse Json when sending and retrieving it can be found here : https://github.com/douglascrockford/JSON-js/blob/master/json2.js
$.ajax({
url: URL,
type: "POST",
//Stringify the data you send to make shure its properly encoded
data: JSON.stringify(DATA),
//This is the type for the data that gets sent
contentType: 'application/json; charset=utf-8',
//This is for the data you receive
dataType: "json"
}).done(function(data) {
var dataYouGet = JSON.parse(data);
}).fail(function(xhr, ajaxOptions, thrownError) {
}).always(function(data) {
});