Post JSON data along with id in Jquery AJAX - javascript

I'm trying to post JSON data along with 2 ids through a Jquery AJAX post. But I am not able to do it.
Following is my code:
try {
var surveyID= localStorage.getItem("surveyId");
var userDetails = jQuery.parseJSON(localStorage.getItem("userdetails"));
var providerKey = userDetails["ProviderUserKey"];
var dataValue = { "str": StringJson};
var url = APP_URL+"EditSurvey?";
var param = "SurveyId="+surveyID+"&JSONData="+JSON.stringify(dataValue)+"&UserId="+providerKey;
$.ajax({
type: "POST",
contentType: "application/json",
url: url,
data: param,
async:true,
success: function (data) {
alert('sucess');
//}
},
error: function (err) {
alert("Err : " + err.error);
},
});
} catch (error) {
alert(error);
}
I get the following error when I debug this in Safari:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
and in simulator I get the following error:
Where am I getting wrong? How do I solve this? I have to 3 parameters for post
surveyID
JSON data
userID
Edited:
The webservice is now changed and all 3 params- i.e. 2 ids and one whole json data is passed to the webservice. Still jquery ajax post is not working. See my code below:
var surveyID= localStorage.getItem("surveyId");
var userDetails = jQuery.parseJSON(localStorage.getItem("userdetails"));
var providerKey = userDetails["ProviderUserKey"];
var dataValue = {"surveyID":surveyID, "userID":providerKey, "str": StringJson};
alert(dataValue);
var url = APP_URL+"EditSurvey";
var param = dataValue;
$.ajax({
type: 'POST',
contentType: "application/json",
url: url,
data: dataValue,
success: function (data) {
alert('sucess');
//}
},
error: function (err) {
alert("Err : " + err.text);
},
});
edited to include stringJson:
var StringJson = JSON.stringify(MainJSON);
alert(StringJson);

Check if the final json which is being passed is in the exact format as expected by the server.
Try giving:
contentType: 'application/json',
Accept: 'application/json'
See if it helps.

try this one
formData = {
// all your parameters here
param1: param1,
JSONData: formToJSON(),
UserId: providerKey
}
$.ajax({
type: 'POST',
contentType: 'application/json',
url: url,
dataType: "json",
data: formData,
success: function(data) {
//success handling
},
error: function(data) {
alert("Err : " + err.error);
}
});
function formToJSON() {
return JSON.stringify({
dataValue: dataValue
});
}

Related

Post AJAX API Javascript SAPUI5 failed

I want to use POST method with AJAX in SAPUI5 javascript but I found an error.
var url = "https://xxxx*xxxx.co.id:8877/TaspenSAP/SimpanDosirPunah";
$.ajax({
type: "POST",
url: url,
data: JSON.stringify({
nomorDosir: "01001961288",
kodeCabang: "A02"
}),
dataType: "json",
async: false,
contentType: 'application/json; charset=utf-8',
success: function(data, textStatus, xhr){
console.log("sukses: " + data + " " + JSON.stringify(xhr));
},
error: function (e,xhr,textStatus,err,data) {
console.log(e);
console.log(xhr);
console.log(textStatus);
console.log(err);
}
});
error:
I already did change code with dataType=text, or data: {nomorDosir: "01001961288", kodeCabang: "A02"} (without stringify), but I not yet find the solution. How to fix this problem?
Thanks.
Bobby
Not sure what your use case is but if you are trying to post to an oData service, it might be much easier to use SAPs createEntry method where the URL is the path to the model you want to post to and your JSON are the properties:
var oModel = new sap.ui.model.odata.v2.ODataModel("https://services.odata.org/V2/OData/OData.svc/");
//oModel should use your service uri
var url = "https://xxxx*xxxx.co.id:8877/TaspenSAP/SimpanDosirPunah";
oModel.createEntry(url, {
properties: {
nomorDosir: "01001961288",
kodeCabang: "A02"
}
}, {
method: "POST",
success: function(response) {
alert(JSON.stringify(response));
//do something
},
error: function(error) {
alert(JSON.stringify(error));
}
});
oModel.submitChanges();
What you have is wrong json format, you have:
data: JSON.stringify({nomorDosir: "01001961288", kodeCabang: "A02"}),
Which actually should be:
data: {"nomorDosir": "01001961288", "kodeCabang": "A02"},
Which then you don't need to do a json.stringify on, because it already IS a json format. Hope this will help you out.
Which you could also try is setting a variable outside like this:
var url = "https://xxxx*xxxx.co.id:8877/TaspenSAP/SimpanDosirPunah";
var json = {"nomorDosir": "01001961288", "kodeCabang": "A02"};
$.ajax({
type: "POST",
url: url,
data: json,
dataType: "json",
async: false,
contentType: 'application/json; charset=utf-8',
success: function(data, textStatus, xhr){
console.log("sukses: "+data+" "+JSON.stringify(xhr));
},
error: function (e,xhr,textStatus,err,data) {
console.log(e);
console.log(xhr);
console.log(textStatus);
console.log(err);
}
});

Fake path Javascript Issue

When I try to retrieve the File path it's shows me the result like this: "C:\fakepath\amine.jpeg" so the upload in the server is not working as a result of that problem.
$('input[type=file]').change(function () {
var filePath=$('#file-input').val();
$.ajax({
url : "{{path('upload_file')}}",
type : 'POST',
data: {
filePath : filePath,
method: 'post',
params: {
action: "uploadFile"
}
},
success : function(data, textStatus, jqXHR) {
alert(data);
}
});
});
You are doing this all wrong.
You have to create a form object and send it via $.ajax.
And I assume you have written the correct serverside code to save the image.
var f = new FormData();
f.append('img',document.getElementById("file-input").files[0]);
var url= "{{Your URL}}";
$.ajax({
url: url,
type:"post",
data: f,
dataType:"JSON",
processData: false,
contentType: false,
success: function (data, status)
{
console.log(data);
},
error: function (data)
{
if (data.status === 422) {
console.log("upload failed");
} else {
console.log("upload success");
}
});
Your file by default upload to a temporary folder. You need to move it to an actual location to get access to it like in php:
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)
For reference, see http://www.w3schools.com/php/php_file_upload.asp

JavaScript POST falls when connect to MVC controller

I'm new in MVC and trying to create a site for training.
I need to call a POST method in my controller through JavaScript.
This is my JavaScript method:
function ActivateAddStarAndRoleWithCategories(sender, args) {
var discID = $('#DiscID').val();
var starID = $('#StarID').val();
var desc = $("#Description").val();
var strID = "";
$(':checkbox').each(function () {
strID += this.checked ? this.id + "," : "";
});
strID = strID.substr(0, strID.length - 1);
$.ajax({
type: "POST",
url: 'CreateCategoriesID',
contentType: "application/json; charset=utf-8",
data: {
discID: discID,
starID: starID,
description: desc,
catID: strID
},
dataType: "json",
success: function () { alert("success!"); },
error: function () { alert("Fail!"); }
});
}
And this is my method in the controller:
[HttpPost]
public ActionResult CreateCategoriesID(string discID, string starID, string description, string catID)
{
entities.AddStarAndRoleAndCategories(int.Parse(starID), description, int.Parse(discID), catID);
return Json("OK", JsonRequestBehavior.AllowGet);
}
The view that activates the JavaScript function is already connected to the controller.
I always get error 500 - the server responded with a status of 500.
What am I doing wrong?
Thank you in advance!
I would go with the examples from the jQuery docs.
Did you try something like...?
$.ajax({
method: "POST",
url: "CreateCategoriesID", // Insert your full URL here, that COULD be the problem too
// This contentType is the default, so we can just ignore it
//contentType: "application/x-www-form-urlencoded; charset=UTF-8",
// I would also ignore the dataType unless your backend explicitly sends a JSON response header
//dataType: "json",
data: {
discID: discID,
starID: starID,
description: desc,
catID: strID
}
}).done(function(msg) {
alert('Success with message: ' + msg);
}).fail(function(jqXHR, textStatus) {
alert('Failed with status: ' + textStatus);
});

How to pass a list of id's in a AJAX request to the Server in MVC

In a AJAX request to the server in MVC, how can I pass a list of id's to the controller's action function?
I accept with or without use of Html helpers.
I know MVC's model binder has no problem when it comes to simple types like int, string and bool.
Is it something like I have to use and array instead in the action?
I don't care if I have to use an array or List and even if the strings I int or strings I can always convert them. I just need them on the server.
My List ids gives null at the moment.
Javascript:
var ids= [1,4,5];
// ajax request with ids..
MVC Action:
public ActionResult ShowComputerPackageBuffer(List<int> ids) // ids are null
{
// build model ect..
return PartialView(model);
}
EDIT: Added my AJAX request
$(document).ready(function () {
$('#spanComputerPackagesBuffer').on('click', function () {
var ids = $('#divComputerPackagesBuffer').data('buffer');
console.log('bufferIds: ' + bufferIds);
var data = {
ids: ids
};
var url = getUrlShowComputerPackageBuffer();
loadTable(url, "result", data);
});
});
// AJAX's
function loadTable(url, updateTargetId, data) {
var promise = $.ajax({
url: url,
dataType: "html",
data: data
})
.done(function (result) {
$('#' + updateTargetId).html(result);
})
.fail(function (jqXhr, textStatus, errorThrown) {
var errMsg = textStatus.toUpperCase() + ": " + errorThrown + '. Could not load HTML.';
alert(errMsg);
});
};
// URL's
function getUrlShowComputerPackageBuffer() {
return '#Url.Action("ShowComputerPackageBuffer", "Buffer")';
};
SOLUTIONS: // Thanks to #aherrick comment. I missed the good old "traditional"
$.ajax({
type: "POST",
url: '#Url.Action("ShowComputerPackageBuffer", "Buffer")',
dataType: "json",
traditional: true,
data: {
bufferIds: bufferIds
}
});
Use the traditional parameter and set it to true.
$.ajax({
type: "POST",
url: "/URL",
dataType: "json",
traditional: true,
data: {}
});
Try this one (I've checked it):
$(function () {
var ids = [1, 4, 5];
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '#Url.Action("YourAction", "YourController")',
data: JSON.stringify( { ids: ids })
}).done(function () {
});
});
You have to make sure your contentType is application/json and your data is stringified.
public ActionResult SaveSomething(int[] requestData)
//or
public ActionResult SaveSomething(IEnumerable<int> requestData)
Using Action Result you cannot receive JSON object:
Using Controler:
[HttpPost]
[Route( "api/Controller/SaveSomething" )]
public object SaveTimeSheet( int[] requestData )
{
try
{
doSomethingWith( requestData );
return new
{
status = "Ok",
message = "Updated!"
};
}
catch( Exception ex )
{
return new
{
status = "Error",
message = ex.Message
};
}
}
java script:
var ids = [1,4,5];
var baseUrl: 'localhost/yourwebsite'
$.ajax({
url: baseUrl + '/api/Controller/SaveSomething',
type: 'POST',
data: JSON.stringify(ids),
dataType: 'json',
contentType: 'application/json',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
if (result != undefined) {
window.location.href = window.location.href;
}
},
async: false,
});

Uploading a file via Yammer API

I'm able to post a message but when I add either the attachment or pending_attachment, I get an error saying:
TypeError: 'stepUp' called on an object that does not implement interface HTMLInputElement.
function post() {
yam.getLoginStatus( function(response) {
if (response.authResponse) {
yam.request(
{ url: "https://api.yammer.com/api/v1/messages.json" //note: the endpoint is api.yammer...
, method: "POST"
, data: {
"body" : document.getElementById("post_body").value,
"group_id" : document.getElementById("group_id").value
,"attachment1" : document.getElementById("attachment")
}
, success: function (msg) {
alert("Post was Successful!: " + msg.messages[0].id); //id of new message
}
, error: function (msg) { alert("Post was Unsuccessful..." + msg); }
}
);
} else {
yam.login( function (response) {
//nothing
});
}
});
}
yammer's javascript SDK doesn't work with attachment. (at least no working example has been seen on the internet) To upload an attachment, you can either upload the file to your server and then use og_url to post a link to that file on your server, or cook up your own ajax form upload. here is an example:
var data = new FormData();
data.append('body', document.getElementById("post_body").value);
data.append('group_id', document.getElementById("group_id").value);
data.append('attachment1', document.getElementById("attachment"), 'filename_of_your_choice');
$.ajax({
url: "https://api.yammer.com/api/v1/messages.json",
data: data,
beforeSend: function (xhr) {
// set authorization header
xhr.setRequestHeader("Authorization", "Bearer YOUR_AUTHORIZATION_TOKEN");
},
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function (data) {
console.log("ajax post success.");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("There was an error with the request.");
}
});
Notice that the authorization token is obtained in the response to a successful login. It is not your app ID. Also, I doubt document.getElementById("attachment") will work. You need to convert that object into an byte array blob.
It works for me:
function postAttach() {
var msg = $('#attach_body').val();
var m_data = new FormData();
m_data.append('body', msg);
m_data.append('group_id', 6194208);
m_data.append('attachment1', $('input[name=attachment1]')[0].files[0]);
yam.platform.request({
url: "messages.json",
contentType: "multipart/form-data",
data: m_data,
processData: false,
contentType: false,
type: 'POST',
dataType: 'json',
success: function (user) {
alert("The request was successful.");
},
error: function (user) {console.log(user);
alert("There was an error with the request.");
}
});
}
<div name="postYammer">
<input type="text" name="body" value="" id="attach_body" />
<input type="file" name="attachment1" id="attach_img"/>
<button onclick="postAttach()" type="button">Post</button>
</div>
//Example Nodejs in async function
// nota : you can get token from https://developer.yammer.com/docs/app-registration
const qs = require("qs");
const got = require("got");
const formData = require("form-data");
const fs = require("fs");
var json = {
is_rich_text: true,
topic1: 'tag1',
topic2: 'tag2',
body: 'body body',
group_id: 'group_id',
}
let querystring = qs.stringify(json);
var formData = new formData();
var aHeader = formData.getHeaders();
aHeader['Authorization'] = "Bearer token";
formData.append('attachment1', fs.createReadStream(path));
const response = await got.post('https://www.yammer.com/api/v1/messages.json?' + qs, {
headers: aHeader,
body: formData
});

Categories

Resources