JQuery ajax to invoke method in controller and store the data - javascript

I have this code in JS:
$("#send_button").click(function(){
var isitArray = getObjectsRequest('isit', isitID);
var ecArray = getObjectsRequest('ec', ecID);
var bcArray = getObjectsRequest('bc', bcID);
var bbArray = getObjectsRequest('bb', bbID);
var ioArray = getObjectsRequest('io', ioID);
function getObjectsRequest(type, compId){
var array = [];
for (var i = 0; i<compId; i++) {
var comp = mainLayer.find('#'+ type + i)[0];
array.push({
xposition: comp.getX(),
yposition: comp.getY(),
titleid: comp.getId(),
description: comp.find('.textDescription')[0].getText(),
leftrelationsids: comp.leftCRelations,
rightrelationsids: comp.rightCRelations
});
};
return array;
}
var datatosend = {
isit: isitArray,
ec: ecArray,
bc: bcArray,
bb: bbArray,
io: ioArray
};
var diagramName = $("#diagramName").val();
if(diagramName==''){
alert("Enter the diagram name!");
} else {
datatosend.diagramname = diagramName;
$.ajax({
type: "POST",
url: "insertdata.php",
data: datatosend,
dataType: "text"
})
.done(function( msgReply ) {
alert("Data saved with success.");
//alert( "Data Saved: " + msgReply );
displayDiagrams();
});
}
return false;
});
This ajax jquery example uses a php file. I'm integrating this tool into an application in ruby on rails. My objective is to store the diagram data using a method in Diagram controller.
Is it possible to store the data using this kind of ajax request? More like this:
$.ajax({
type: "POST",
url: "/diagrams",
data: datatosend,
dataType: "html"
Invoking the create method in the Diagram controller.
How should I do this?

Related

sum values from multiple ajax requests

im trying to get the total value of the data returned by the ajax requests, but it is showing total:0 because it is executing the totalRev before completing the ajax requests.
var totalRev = 0;
$.ajax({
type: "POST",
url: "cloudmobi.php",
data: {action: 'cloudmobi'},
dataType:'JSON',
success: function(response){
document.getElementById('cloudmobi').innerHTML = response.cloudmobi;
console.log(response.cloudmobi);
var cloudmobi = parseInt(response.cloudmobi);
console.log('CLOUDMOBI:'+cloudmobi);
totalRev += cloudmobi;
}
});
$.ajax({
type: "POST",
url: "mobusi.php",
data: {action: 'mobusi'},
dataType:'JSON',
success: function(response){
document.getElementById('mobusi').innerHTML = response.mobusi;
console.log(response.mobusi);
var mobusi = parseInt(response.mobusi);
totalRev += mobusi;
console.log('MOBUSI:'+mobusi);
}
});
$.ajax({
type: "POST",
url: "appnext.php",
data: {action: 'appnext'},
dataType:'JSON',
success: function(response){
document.getElementById('appnext').innerHTML = response.appnext;
console.log(response.appnext);
var appnext = parseInt(response.appnext);
totalRev += appnext;
console.log('APPNEXT:'+appnext);
}
});
console.log('TOTAL:'+totalRev);
I do not want to use async because the whole purpose of using ajax here is to load the site fast then dynamically load the data
jQuery "when" solves your problem:
$.when( d1, d2 ).done(function ( v1, v2 ) {
console.log( v1 ); // "Fish"
console.log( v2 ); // "Pizza"
});
It would be far better to send all the data in a single request so you can do the sum on the server and send it in a single property in the response.
Assuming, for whatever reason, you cannot do that, then you could instead store all the promises from the AJAX requests and then execute your code after all of them have completed and added their values to an array. Then you can sum the array. Something like this:
var values = [];
var promises = [
$.ajax({
// ajax settings...
success: function() {
values.push(parseInt(response.cloudmobi), 10);
}
}),
$.ajax({
// ajax settings...
success: function() {
values.push(parseInt(response.mobusi), 10);
}
}),
// Nrequests...
];
$.when.apply(this, promises).done(function() {
var sum = values.reduce(function(a, b) {
return a + b;
}, 0);
// work with sum here...
});

How to read data using JSONP, Ajax and jquery?

I am trying to read data from this API, but it is not working, I have an input box where I enter the isbn number and then get the data, using jsonp. Could you possibly help me in identifying where my error("Cannot read property 'title' of undefined") is?
function add(){
var isbn = parseInt($("#isbn").val());
var list = $("#list");
console.log(parseInt(isbn));
$.ajax({
url: "https://openlibrary.org/api/books?bibkeys=" + isbn + "&jscmd=details&callback=mycallback",
dataType: "jsonp",
success: function(isbn){
var infoUrl = isbn.info_url;
var thumbnailUrl = isbn.thumbnail_url;
var title = isbn.details.title;
var publishers = isbn.details.publishers;
var isbn13 = isbn.details.isbn_13;
console.log(isbn.info_url);
}
});
}
Open Library's API expects bibkeys to be prefixed with their type and a colon, rather than just the number alone:
function add(){
var isbn = 'ISBN:' + $("#isbn").val();
// ...
The colon also means the value should be URL-encoded, which jQuery can do for you:
$.ajax({
url: "https://openlibrary.org/api/books?jscmd=details&callback=?",
data: { bidkeys: isbn },
dataType: "jsonp",
Then, the data it returns reuses the bibkeys you provided as properties:
{ "ISBN:0123456789": { "info_url": ..., "details": { ... }, ... } }
To access the book's information, you'll have to first access this property:
success: function(data){
var bookInfo = data[isbn];
console.log(bookInfo.details.title);
// etc.
}
Example: https://jsfiddle.net/3p6s7051/
You can also retrieve the bibkey from the object itself using Object.keys():
success: function (data) {
var bibkey = Object.keys(data)[0];
var bookInfo = data[bibkey];
console.log(bookInfo.details.title);
// ...
}
Note: You can use this to validate, since the request can be technically successful and not include any book information (i.e. no matches found):
success: function (data) {
var bibkeys = Object.keys(data);
if (bibkeys.length === 0)
return showError('No books were found with the ISBN provided.');
// ...
Example: https://jsfiddle.net/q0aqys87/
I asked a professor, and this is how she told me to solve it:
function add(){
var isbn = parseInt($("#isbn").val());
var list = $("#list");
console.log(parseInt(isbn));
$.ajax({
url: "https://openlibrary.org/api/books?bibkeys=" + isbn + "&jscmd=details&callback=mycallback",
dataType: "jsonp",
success: function(data){
var thumb=data["ISBN:"+isbn+""].thumbnail_url;
....
}
});
}

Pass Json Object and String Value at once in Ajax

I want to pass a Json Object and String Value together in ajax call. I have attached my code below.
$('#ddcountryid').change(function () {
var jdata = ko.mapping.toJSON(viewModel);
var Cid = $(this).val();
//alert(intCountry);
$.ajax({
url: '#Url.Action("PopulateDropDown", "Pepmytrip")',
type: 'POST',
data: jdata,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.redirect) {
location.href = resolveUrl(data.url);
}
else {
ko.mapping.fromJS(data, viewModel);
}
},
error: function (error) {
alert("There was an error posting the data to the server: " + error.responseText);
},
});
});
My Action Method
public JsonResult PopulateDropDown(Wrapper wrapper, string cID)
{
wrapper.Destinations = new SelectList(context.Destinations.Where(c=>c.CountryId == cID), "id", "Name").ToList();
return Json(wrapper);
}
I am getting wrapper object with Values, but how can get the CID as well. Can anyone please help me on this??.
you can pass it as query string parameter:
var Cid = $(this).val();
$.ajax({
url: '#Url.Action("PopulateDropDown", "Pepmytrip")' + '?cID=' + Cid,
...
server side:
public JsonResult PopulateDropDown(Wrapper wrapper, string cID)
{
wrapper.Destinations = new SelectList(context.Destinations.Where(c=>c.CountryId == cID), "id", "Name").ToList();
return Json(wrapper);
}
OR add a new property to your Wrapper object as Gavin Fang suggested:
var Cid = $(this).val();
viewModel.Cid = Cid;
var jdata = ko.mapping.toJSON(viewModel);
server side code:
public JsonResult PopulateDropDown(Wrapper wrapper)
{
var cid = wrapper.Cid;
wrapper.Destinations = new SelectList(context.Destinations.Where(c=>c.CountryId == cID), "id", "Name").ToList();
return Json(wrapper);
}
I think you can add a property to store you 'CID' to your viewModel.
and you can get the CID in the 'success' function in javascript in here, I think.
You can achieve this is two ways:
You can add extra field for existing json 'jdata' by defining field jdata.cid = null; and assigning it as jdata.cid = $(this).val();.
Prepare an object to hold both json data and string value:
var obj = {"json": jdata, "string":$(this).value()};
then pass obj in data parameter

Assigning JSON value to a Variable that Resides Outside JavaScript Function

I have a question regarding JSON Web Services and AJAX Function. I have declared a JavaScript Function below.
function setJsonSer(){
formData = {
'Email': 'clientlink#russell.com',
'Password': 'russell1234',
'URL': getVaria()
};
$.ajax({
url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
type: 'POST',
data: formData,
complete: function(data) {
alert("This is Set JSON In "+JSON.stringify(data));
}
});
$.ajax({
url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
type: 'GET',
data: formData,
complete: function(data) {
alert("This is Get JSON Out "+JSON.stringify(data));
}
});
}
As you can see I have alert the JSON.stingify(data) statement and it gave me the result as I expected.
Now I want to get that JSON response out of that particular function SetJsonSer() to assign to avariable that resides out side the SetJsonSer() function.
I already tried return JSON.stringify(data)) and JSON.stringify(data) statements but they did not put the result out from the SetJsonSer() function.
The output must grab from a variable like the below.
function Load(){
//-----------------------------------------------
setJsonSer();
var labels = new Array();
var values = new Array();
var catogories = new Array();
var arrayOfArray = new Array();
var rowData = "return value of JSON.stringify(data)";
This variable will be used as the query to draw a chart using HighCharts. So could you someone give me a clue how to get the result of the SetJsonSer() function?
Thanks and regards,
Chiranthaka
You're getting a bit mixed up with asynchronous nature of AJAX.
The AJAX event is being fired, but it won't be causing any pause in the execution of your code, as such, you need to implement a callback.
This code isn't particularly nice, but it should give you an idea of how the data needs to be handled.
function setJSONSer() {
formData = {
'Email': 'clientlink#russell.com',
'Password': 'russell1234',
'URL': getVaria()
};
$.ajax({
url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
type: 'POST',
data: formData,
complete: function(data) {
console.log("Successfullly set JSON!");
getJSONSer();
}
});
}
function getJSONSer()
{
$.ajax({
url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
type: 'GET',
complete: function(data) {
//alert("This is Get JSON Out "+JSON.stringify(data));#
Load(data);
}
});
}
function BeginLoad()
{
setJSONSer();
}
function Load(data)
{
setJsonSer();
var labels = new Array();
var values = new Array();
var catogories = new Array();
var arrayOfArray = new Array();
var rowData = "return value of JSON.stringify(data)";
}
BeginLoad();

Issue related to getting value from AJAX Call in Famo.us

I am new in Famo.us framework. i have small Application in Famo.us framework.
I have following Code:
define(function (require, exports, module) {
var Surface = require('famous/core/Surface');
var Modifier = require('famous/core/Modifier');
var Transform = require('famous/core/Transform');
var View = require('famous/core/View');
var HeaderFooterLayout = require('famous/views/HeaderFooterLayout');
var App = require('./App');
var apps = [];
GetContent.prototype = Object.create(View.prototype);
GetContent.prototype.constructor = GetContent;
GetContent.DEFAULT_OPTIONS = {};
function GetContent() {
View.apply(this, arguments);
GetData();
}
function GetData() {
$.ajax({
type: "GET",
url: "/LocalPlatFormService.svc/GetJobRCompanies",
contentType: "application/json; charset=utf-8",
success: ajaxCallSucceed,
dataType: "json"
});
}
function ajaxCallSucceed(response) {
var finalStr = '';
var a = response[0].Success;
if (a.toString().toLowerCase() == "true") {
for (var i = 0; i < response.length; i++) {
var strId = response[i].Id;
var strSuccess = response[i].Success;
finalStr += i + '.' + strId + ' , ' + strSuccess + ' ';
var app1 = new App({});
app1.AddPages(response[i].ImageLarge, response[i].Description, response.length, i);
apps.push(app1);
}
}
else {
alert("No Data Found.");
}
}
module.exports = GetContent;
});
The Ajax call in GetData() is works fine, and it also calls ajaxCallSucceed() on successful Call. but problem is that ajaxCallSucceed() executes after executing all other function, even after executing module.exports = GetContent; in last line.
I want to bind some values in ajaxCallSucceed() based on getting data from database
but how to fetch value from ajaxCallSucceed(), as it is executing after all other operation.
Thanks.
Set ajax async to false. Like this:
$.ajax({
type: "GET",
async: false,
url: "/LocalPlatFormService.svc/GetJobRCompanies",
contentType: "application/json; charset=utf-8",
success: ajaxCallSucceed,
dataType: "json"
});
Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called. If you set async: true then that statement will begin it's execution and the next statement will be called regardless of whether the async statement has completed yet.

Categories

Resources