POST a JSON data on a Server URL using Javascript - javascript

I have prepared a JSON data and I need to post it on the server so that a service can be called. URL to the server is available and I am making an AJAX call for the same to
POST the data.
But I dont know where to place the JSON string that is generated.
My Code is as Follows:
function postJSONData(JSONData, localMode)
{
var localJSONData = JSONData;
var postMode = localMode;
$.ajax({
type: 'POST',
url: 'https://tt.s2.com/tmobile/subscribe-service/uid=ankit_bharat_tanna',
dataType: 'xml',
success: function(data){
alert("SECOND POST JSON DATA");
} // Success Function
}); // AJAX Call
alert("POST JSON ------------> "+localJSONData +" "+postMode);
}
I want to post JSON data to the server URL. any Parameters to be used?
Thanks,
Ankit.

You should pass the values with data parameter $.ajax() jquery doc link
function postJSONData(JSONData, localMode)
{
var localJSONData = JSONData;
var postMode = localMode;
$.ajax({
type: 'POST',
url: 'https://tt.s2.com/tmobile/subscribe-service/uid=ankit_bharat_tanna',
contentType:"application/json; charset=utf-8",
dataType:"json"
data: JSONData
success: function(data){
alert("SECOND POST JSON DATA");
} // Success Function
}); // AJAX Call
alert("POST JSON ------------> "+localJSONData +" "+postMode);
}

You are missing the data parameter. Moreover you need to send json data so dataType parameter should be set to json. Below is an Example
function postJSONData(JSONData, localMode)
{
var localJSONData = JSONData;
var postMode = localMode;
$.ajax({
data: localJSONData,
type: 'POST',
url: 'https://tt.s2.com/tmobile/subscribe-service/uid=ankit_bharat_tanna',
dataType: 'json',
success: function(data){
alert("SECOND POST JSON DATA");
} // Success Function
}); // AJAX Call
alert("POST JSON ------------> "+localJSONData +" "+postMode);
}

Related

Ajax call not sending to POST

I have a function that includes an AJAX to send a JSON object retrieved from localStorage. For some reason, in my PHP script, it never shows anything in the $_POST variable, despite me being pretty sure the AJAX call goes through successfully. My code is as follows:
The javascript:
function processResults(){
var finalResults = localStorage.getItem('results');
finalResults = JSON.stringify(finalResults);
$.ajax({
type: 'POST',
url: '../DB_add.php',
dataType: 'json',
data: {'answers': finalResults},
success: function(data){
console.log(data);
console.log('Success');
}
})
}
The php script:
if(isset($_POST['answers'])){
$obj = json_decode($_POST['answers']);
print_r ($obj);
}
Any help as to why this isn't working would be greatly appreciated. Thank you.
I've tried all of the options given so far, and nothing seems to be working. I'm at a total loss.
For those asking, the finalResult variable is structured as:
[{"answer":0,"elapsed_time":1378,"stimulus_id":"8","task_id":1},{"answer":1,"elapsed_time":157,"stimulus_id":"2","task_id":1},{"answer":1,"elapsed_time":169,"stimulus_id":"1","task_id":1}, etc....
dataType: 'json' requires that what you output in PHP (data accepted in success section) must be valid json.
So valid json will be in PHP:
if(isset($_POST['answers'])){
echo $_POST['answers'];
}
No need to decode it, it is json string already. No var_dump, no print_r
I would remove the dataType property in your Ajax request and modify the structure of your data :
$.ajax({
type: 'POST',
url: '../DB_add.php',
data: 'answers='&finalResults,
success: function(data){
console.log(data);
console.log('Success');
}
})
And in a second time I would test what I receive on PHP side :
if(isset($_POST['answers'])){
var_dump(json_encode($_POST['answers']));
}
Remove dataType: 'json', if you sending with JSON.stringify
JS.
function processResults(){
var finalResults = localStorage.getItem('results');
finalResults = JSON.stringify(finalResults);
$.ajax({
type: 'POST',
url: '../DB_add.php',
data: {'answers': finalResults},
success: function(data){
console.log(data);
console.log('Success');
}
})
}
PHP CODE:
if (!empty($_REQUEST['answers'])) {
$answers = json_decode(stripslashes($request['answers']));
var_dump($answers);
}

returning requested data in C to ajax(jquery) CGI

Im returning specific data in to my jquery using C, how will i put the data in C?
str
function Run() {
$.ajaxSetup({ cache: false });
var obj = {"method":"pref-get","arguments":{"infos":["sys_info"]}};
alert("Post Json:" + JSON.stringify(obj));
$.ajax({
url: "http://localhost/cgi-bin/try.cgi",
type: 'POST',
data: JSON.stringify(obj),
dataType: 'text',
success: function(response){
alert(response);
}
});
}
Run();
the Value_in_C must have the data in the CGI.
Heres the code for C:
if(!end && !strcmp(method, "GET"))
printf(("%s"), str);
response = (("%s"), str);
fclose(fd);
How can I pass or return the value of str to the alert function?
Or should i add function in C to response in POST/GET method?
Thanks in advance!
Your question is an basic ajax problem, isn't it?
You have: client > call "try.cgi" in server > response data ("Value_in_C") to client > display it.
Then it should be:
$.ajax({
url: "http://localhost/cgi-bin/try.cgi",
type: 'POST',
data: JSON.stringify(obj),
dataType: 'text', // since your response is a string
success: function(responseData){
alert(responseData); // responseData should be "Value_in_C"
}
});
Updated: dataType: 'json' will parse response to json, so "Value_in_C" became null

Populate a html div with json data received from a server

I need to have a html div populated with the json data received from the server which is a json-rpc server and it retruns an application/jsson-rpc content type and i can see the result in the chrome and firefox dev tools... I need to view it as part of the page inside a given div
i have this script to populate the mybox div but it gives nothing
var returnedinfo;
var request = $.ajax ({
url: "/url",
type: "POST",
data: JSON.stringify(data),
success: function(json) {
alert("success sent ajax");
$("#mybox").html(json);
returnedinfo = json;
});
I also tied having the populating function outside the ajax block when the request is done
request.done(function(msg) {
$("#mybox").text(msg);
});
This just return an empty array like this
[object Object]
and nothing else help will be appreciated.
you need to append the key of the json item.
$("#mybox").html(json.key);
Add dataType to your ajax request.
var request = $.ajax ({
url: "/url",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
success: function(json) {
alert("success sent ajax");
$("#mybox").html(json);
returnedinfo = json;
});
try this my working example
look contentType and html function to replace html of mybox element
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
url: 'url',
success: function (dataRes) {
$('#mybox').html(dataRes);
},
error: function(a,b,c) {
}
});
Note that in this case dataRes in success function is an html string like <strong>test</strong>. If your server side function returns a json object you should add dataType: 'json' to ajax request and then you can use properties of dataRes object like here $('#mybox').html(dataRes.property1);

Get parameter from JSON

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

PHP -Ajax : send response data to php to convert jsonp to php array

$.ajax({
type: "GET",
url:"http://localhost:8080/privateTraining/getTrainingsJson",
data: { ListID: '1'},
dataType: "jsonp",
success: function(data)
{
anotherFunction(data);
}
});
function anotherFunction(data){
$.ajax({
type:"POST",
data:data,
url:"anotherFile.php,
success: function(data)
{
//do something elese;
}
});
}
here first one is cross domain ajax call.
here i want to send the result (jasonp response) of first ajax call to second ajax call to a php file .. where i need to convert jsonp data to php array .
is it possible to do like this?

Categories