extjs form.load using the url of different domain server to fetch the data and bind to fields - asp.net-web-api

I want to load the form fields using json data.
I am using extjs 4.1 for ui and asp.net webapi to fetch the data.
My objective is to load the data and bind it to the field dynamically which form.load is used for if the name of field corresponds to the data.fieldnameproperty.
i have taken the below link as reference :
Ext JS: FormPanel not populating fields with JSON data
It loads the data if the Webapi is on the same project :
i.e.
projectname:
--ui folder
-- webapi controller folder
but in my case the data is coming from different domain 2 different project for ui and webapi. My form.load code is as below
formCmp.getForm().load({
url: 'http://localhost/WebApiCore/api/Values/',
method: 'GET',
headers: {'Content-type': 'application/json'},
// params: {
// empId: '111'
// },
success: function (form, action) {
console.log(action.result);
//Ext.Msg.alert("Load success", action.result);
},
failure: function (form, action) {
//Ext.Msg.alert("Load failed", action.result.errorMessage);
}
});
I get the error as "NetworkError: 405 Method Not Allowed - "http://localhost/WebApiCore/api/Values/?_dc=1340261175475" in firebug.
my project is running on "http://localhost:54118/PreHospital.htm"
I am not sure is it the problem of extjs not sending the cross domain request using form.load or the problem with webapi doesn't allow cross domain request.
I am not sure how to set extjs to send the jsonp request using form.load.
any kind of help is appreciated.

If you just have regular form fields on your Ext Form, it will actually do an AJAX call to submit this data. I don't think there is a way to force a form.load to do a JSONP request. You will probably need to do a manual JSONP request like you would a manual AJAX request.
Ext.data.JsonP.request({
url : websiteURL,
scope : this,
params : {
empId: '111'
},
success : function(jsonData) {
},
failure : function(jsonData) {
Ext.Msg.show({
title : 'Warning',
msg : message,
buttons : Ext.Msg.OK,
icon : Ext.Msg.WARNING
});
}
});

Related

October CMS - API Generator - how to create and update data in database

I try to send data to the database using AJAX and plugin in October CMS called "API Generator".
I can't find in its documentation or in Google anything that will help me.
The code I have is this:
$data = [{'room_id': {{room.id}}, 'amount': amount, 'arrival': '2018-04-01', 'departure': '2018-04-03,', 'reservation_type': 'owner'}]
$.ajax({
url: '/api/v1/booking/create',
data: $data,
type: "post"
})
.done(function() {
console.log('Success')
})
.fail(function() {
console.warn('Something went wrong');
});
I don't get any error, in fact, I get 'Success' message in console, but data is not added to the database.
What am I doing wrong?
Please help.
Thanks.
Actually you are doing it little wrong [ You are firing Ajax request at wrong end-point ] that Api Plugin is based on https://laravel.com/docs/5.6/controllers#resource-controllers Resource Controller
So, To create an item you need to fire only POST request to Created Api-End Point. You don't need to send Array just send simple plain Object
Refactored your code ( this should work ):
// Plaing object no array
$data = {'room_id': {{room.id}}, 'amount': amount, 'arrival': '2018-04-01',
'departure': '2018-04-03,', 'reservation_type': 'owner'};
$.ajax({
url: '/api/v1/booking', // <- just your Api-End [no create/store]
data: $data,
type: "post" // <- this post request indicates that you want to create/insert
})
.done(function(response) {
// this will always fire when status code is 200
console.log('Success', response);
})
.fail(function() {
// when status code is not 200 this will execute
console.warn('Something went wrong');
});
Why you get success although its not Creating Record ?
Because according to Resource Controller there is no method create in api generator controller so October CMS is treating /api/v1/booking/create [POST] request as 404 page not found and its serving [200] status code with 404 page not found as ajax response.
And 404 page is having 200 status code so it fall in to success category and Ajax thinks it's a successful request and prints success message in console.
if any doubts please comment.

2nd AJAX call to same URL fails - but works randomly and rarely

I am trying to get a response from a web service, specifically to add two WFS layers from geoserver to a leaflet web map. The first layer gets added no problem every time, but most of the time, the second layer fails, complaining that the callback function is not defined:
ReferenceError: getJson is not defined
But what is very strange to me is that the second layer will be added, only sometimes. Refreshing the page and trying again will almost always fail.
This is the code making the ajax call:
$(document).ready(function() {
...
$("#add-network-button").on("click", function() {setLocation("Moscow")})
function setLocation(locationName) {
var networkParameters = {
service: 'WFS',
version: '1.0.0',
request: 'GetFeature',
typeName: 'netex:' + locationData[locationName].networkWFSName,
maxFeatures: 99999,
outputFormat: 'text/javascript',
format_options: 'callback: getJson'
};
addWebService(map, WFSURL, networkParameters)
var buildingParameters = {
service: 'WFS',
version: '1.0.0',
request: 'GetFeature',
typeName: 'netex:' + locationData[locationName].buildingWFSName,
maxFeatures: 99999,
outputFormat: 'text/javascript',
format_options: 'callback: getJson'
};
addWebService(map, WFSURL, buildingParameters)
}
And here is the addWebService function:
var addWebService = function(map, WFSURL, WFSParameters) {
var leafletWFSParameters = L.Util.extend(WFSParameters);
console.log(WFSURL + L.Util.getParamString(leafletWFSParameters));
$.ajax({
url: WFSURL + L.Util.getParamString(leafletWFSParameters),
dataType: 'jsonp',
jsonpCallback: 'getJson',
success: handleJson,
cache: false
});
// TODO: add style
function handleJson(data) {
L.geoJson(data, {}).addTo(map);
}
}
You're using jsonp, which means the data you're getting back is not JSON, but javascript code that makes a call to a globally-defined function (which name is defined by jsonpCallback).
jQuery automagically creates a function with that name, performs the network request, and when that function runs, it destroys its own reference from the global scope.
You're performing two calls to addWebService() in quick succession, which trigger two jQuery $.ajax({jsonpCallback: 'getJson'}) calls. The second call is overwriting the globally-defined getJson callback function. When the first jsonp payload is received by your browser, the globally-defined getJson callback is destroyed. When the second jsonp payload is received, it tries to call a globally-defined getJson function, and failing. A classic race condition.
Let me quote jQuery's documentation for the jsonpCallback parameter on $.ajax(), empasis mine:
jsonpCallback
Type: String or Function()
Specify the callback function name for a JSONP request.
This value will be used instead of the random name
automatically generated by jQuery. It is preferable to let
jQuery generate a unique name as it'll make it easier to manage the
requests and provide callbacks and error handling. You may want to
specify the callback when you want to enable better browser caching of
GET requests.
I suggest you either use other transport format than JSONP, or use different callback names for each request.

session.setAttribute only updates after page reload

I have an ajax request which invokes GetTierNamesServlet:
$('#application').change(function() {
$.ajax({
url : 'GetTierNamesServlet',
data : {
name : $('#application').find(":selected").text()
},
type : 'get',
cache : false,
success : function(data) {
},
error : function() {
alert('error');
}
}).done(function() {
var test = '<c:out value="${tiers}" />';
alert(test)
})
});
GetTierNamesServlet saves 'tiers' to a session attribute as follows and forwards back to the same page (index.html).
HttpSession session = request.getSession(false);
session.setAttribute("tiers", tiers);
getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
When alert(test) is called, it alerts the selected tiers from the previous time the ajax request was processed.
The session attribute 'tiers' always seems to "lag" one refresh behind.
What am I doing incorrectly here? I would expect that by placing the alert within the .done portion of the ajax request it would wait the asynchronous call to return before doing something.
This fragment of JavaScript:
var test = '<c:out value="${tiers}" />';
is rendered with the value of ${tiers} before your servlet is called. If you inspect the HTML on the page you will likely find something like:
...
}).done(function() {
var test = 'null'; // or some other "old" value
alert(test)
})
the JSP content is translated to HTML and sent to the browser (page 1)
some event on page 1 causes the JavaScript to be executed
the AJAX call results in the page being rendered again and returned to the browser (page 2)
the JavaScript in page 1 finishes executing via the .done(...) function.
You AJAX call is returning a page when it should probably return a JSON fragment containing your tiers content which will then be consumed by the .done function.

AJAX explained in detail

I found allot of examples of AJAX and I think I can get some code with it to work on my own. If only I knew what the use of all the terms of the AJAX code where.
I think in general it lacks the availability of these guides or special pages where constructed code is explained in detail for new programmers.
This would help enormously because of the misunderstanding of the syntax in many cases. Me for example spend 8 hours a day on my internship to learn PHP, Jquery, HTML from scratch and there is allot of information out there but its not structured and in most cases to technical. Any tips on that maby ? :)
$.ajax({
type: 'POST',
url: 'http://kyleschaeffer.com/feed/',
data: { postVar1: 'theValue1', postVar2: 'theValue2' },
beforeSend:function(){
// this is where we append a loading image
$('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
// successful request; do something with the data
$('#ajax-panel').empty();
$(data).find('item').each(function(i){
$('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
});
},
error:function(){
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
Ajax is asynchronous, which mean you can use it to get new informations from the server without reloading the whole page.
Here's an explanation of your code :
$.ajax({
$ is the JQuery object, on which you're calling the ajax function
type: 'POST',
You're gonna send your data by post, which mean that you'll have to get them in php with $_POST['variable_name']. You could also put GET instead
url: 'http://kyleschaeffer.com/feed/',
the url you want to reach
data: { postVar1: 'theValue1', postVar2: 'theValue2' },
as you're sending your request with POST, you cannot pass data directly from the URL.
So you have to pass them like that. { nameVar: 'value', .... }
If you were sending with GET, you could directly write them into url like : "http://my_url.php?var1=val1&var2=val2 etc ...
beforeSend:function()
You can define an action before sending your ajax request
$('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
Here, inside your div "ajax-panel" you want to write some content. (a div "loading" and a picture inside "loading").
success:function(data)
If your request is successful, you can do something. By successful it means if server answer 200 i guess, anyway ... If you have a response from server... ;)
$('#ajax-panel').empty();
You delete content into ajax-panel
$(data).find('item').each(function(i){
$('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
});
You're adding some html AFTER (append) the ajax-panel div
error:function()
Not sure you were looking for that, hope that help you ;)
AJAX is an acronym standing for Asynchronous JavaScript and XML and this technology help us to load data from the server without a browser page refresh.
If you are new with AJAX, I would recommend you go through our Ajax Tutorial before proceeding further.
JQuery is a great tool which provides a rich set of AJAX methods to develope next generation web application
Take a took at this
$.ajax({
type : varType, //GET or POST or PUT or DELETE verb
url : varUrl, // Location of the service
data : varData, //Data sent to server
contentType : varContentType, // content type sent to server
dataType : varDataType, //Expected data format from server
processdata : varProcessData, //True or False
success : function(msg) {//On Successfull service call
},
error : function() {// When Service call fails
}
});

Insert to SQL Server database from jquery mobile application using a server side script (coldfusion)

I've built a jQuery mobile app that gets its content from an external SQL server database via JSON and a server side script (ColdFusion CFC) that interfaces with the database. This app has been packaged as a native app using PhoneGap. I need to enable the jQuery mobile app to be able to write back to the external SQL server db.
Im new to mobile development but have several years of server side development using ColdFusion. I am guessing that the best way to do this is for the mobile app to send the results of the submitted form elements to a server side script for processing. I dont want the native app to send this "as a web page" but rather stay in the app to do it (via AJax I assume).
My server side script will be written in ColdFusion and handles input sanitation and database interaction...I just need to figure out what is the best way to submit from my jQuery app to the server side script, but do it while staying inside of my native application.
I'm pretty much doing the same thing. Server side Coldfuison8/MySQL, front end Jquery Mobile (, requireJS) with all forms submits routed through AJAX to avoid reloading a page.
I'm using a generic form submitter in my controller.js, which looks like this:
var ajaxFormSubmit =
function ( form, service, formdata, targetUrl, successHandler, dataHandler, errorHandler ){
$.ajax({
async: false,
type: "post",
url: service,
data: formdata,
dataType: "json",
success: function( objResponse ){
if (objResponse.SUCCESS == true ){
// alert("success!");
// this passes the response object to the success handler
// in case data needs to be ... handled.
dataHandler == "yes" ? successHandler( objResponse ) : successHandler();
} else {
// alert("AJAX failed!");
if ( errorHandler != "" ){
errorHandler();
}
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert("something else failed");
showErrors( [["server-request-error", "server_error"]], XMLHttpRequest, textStatus, errorThrown );
}
});
}
I'm returning results as a response object, which will contain Success = True/false, data (if there is any) and Error = error message.
A function call will look like this:
// the form
var form = $(this).closest('form'),
// trigger for cfcase inside my cfc
switcher = form.find('input[name="form_submitted"]').val(),
// which cfc to call
service = "../cfcs/form_handler_abc.cfc",
// the method in your cfc you are calling (validation/commit to database)
method = "process",
returnformat = "JSON",
// not using
targetUrl = "",
// serialized form plus any value you need to pass along
formdata = form.serialize()+"&method="+method+"&returnformat="+returnformat,
// specific error routine to run
errorHandler = function(){
// in my case, reset the whole form
cleanUp( $('form:jqmData(search="regular")'), "results" )
},
// inside my success handler I'm switching depending on submitted form
// `response` will be the AJAX object.response = whatever you send back from the server
successHandler = function( response ) {
switch (switcher) {
// form A - this is for a search form handling the results
case "getProducts":
// clean up
$('.ajaxContainer, .pagination').addClass('fade out').remove();
// AJAX data received
var makeUp = response.DATA;
// don't forget to trigger create to enhance all JQM elements you are sending
$('.results').append( makeUp ).trigger('create');
// redraw - will fire JQM updatelayout
$(window).trigger('dimensionchange');
// will set bindings on new elements
bindResults( $('.results').closest('div:jqmData(role="page")') );
break;
case "A":
// do sth else
break;
case "B":
// do sth else
break;
}
};
// now pass all of the above to the ajaxFormsubmit
ajaxFormSubmit( form, service, formdata, targetUrl, successHandler, handleData, errorHandler);
I have a number of CFCs, each with a main cfswitch and cfcase for each submitted form. I have built my backend using this sample. Took a while to get going, but now it's running more or less smooth.
Let me know if you have some questions regarding the above.

Resources