We are trying to migrate from pure ext.js to a model that uses ext.js in the controller, but front end is pure html, bootstrap.
As we migrate, I am trying to make a ajax on a login request. I have a ajax call which is returning a empty requestPayload.
loginSubmit : function(param){
var me = this,
params = {
url: 'login/login',
method: "POST",
jsonData: Ext.JSON.encode(param.formValues) ,
success: function (response) {
var data = Ext.JSON.decode(response.responseText);
Insights.view.common.util.StorageUtil.setAppData(response.responseText);
me.getView().destroy();
Ext.create({
xtype: 'mainviewport'
});
},
failure: function (response) {
var errorMessage = "Network connect timeout error"
if (response.status == 401 || response.status == 500) {
var data = Ext.JSON.decode(response.responseText);
errorMessage = data.message;
}
if(param.loginButton){
var errMsg = form.queryById('login-error-msg');
errMsg.setText(errorMessage);
errMsg.setVisible(true);
param.loginButton && params.loginButton.enable();
}
}
};
Insights.view.common.util.RequestUtil.request(params, 'false');
},
I did a debug on Chrome and the requestPayload does not exist.
The pure ext.js project returns the following on debug on Chrome.
As you notice, this has the requestPayload with the username and password. Also failure: function (response) returns response.status=0. What am I missing in the pure javascript way of sending the request.
EDIT, adding RequestUtil Code
Ext.define('Insights.view.common.util.RequestUtil', {
singleton: true,
config: {
baseUrl: ''
},
request: function (params, component) {
var me = this,
headers = {
'ACCEPT': 'application/json'
};
var appData = Insights.view.common.util.StorageUtil.getAppData();
if (appData) {
headers.authToken = appData.token;
} else if (params.authToken) {
headers.authToken = params.authToken;
}
if(params.headers) {
Ext.Object.merge(headers, params.headers)
}
this.loadMask(component);
Ext.Ajax.request({
url: this.getBaseUrl() + params.url,
timeout: 60000,
headers: headers,
disableCaching: false,
method: params.method,
jsonData: params.jsonData,
params: params.extraParams,
binary: !params.binary ? false : params.binary,
success: function (response, opts) {
if (params.success) {
params.success(response, opts);
me.unLoadMask(component);
}
},
failure: function (response, opts) {
if (params.failure) {
params.failure(response, opts);
}
if (!Ext.isString(component)) {
me.unLoadMask(component);
if (params.url == "authenticate" || params.url == "userInfo") {
return;
}
var responseText = response.responseText && Ext.JSON.decode(response.responseText);
if (responseText && responseText.status === 'Failure') {
Ext.Msg.alert(i18nLabels.warning, responseText.message);
} else if (response.status == 401) {
me.handleSessionTimeout();
} else if (response.status == 404 || response.status == 500) {
me.errorHandler(responseText.message);
} else if (response.status == 405) {
} else {
me.errorHandler(i18nLabels.serverNotAvailable);
}
}
}
});
},
I debugged and checked, jsonData does have the username,password string. This ajax fails and enters failure segment.
The OPTIONS request in the first screen suggests that there is a CORS related problem. This problem can be solved by enabling CORS.
Author's solution (from comments): open -a Google\ Chrome --args --disable-web-security --user-data-dir="tmp/tmpChrome
Related
I am learning C# and jQuery AJAX. I'm currently having a problem where I cannot get Ajax to run correctly and I am not sure why.
Here is the error log:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Here is my code:
HTML
<button class="btn btn-primary btn-edit" id="{{SubjectId}}" id1="
{{StudentId}}" >Edit</button>
JavaScript AJAX code:
$('.btn-edit').off('click').on('click', function () {
$('#editModal').modal('show');
var id = parseInt($(this).attr('id'));
var id1 = parseInt($(this).attr('id1'));
ExamsController.LoadDetail(id, id1);
});
LoadDetail: function (id, id1) {
$.ajax({
url: '/Exams/LoadDetail',
type: 'GET',
data: {
id : id,
id1 : id1
},
dataType: 'json',
success: function (response) {
console.log(response.status);
if (response.status == true) {
var data = response.data;
$('#txtSubjectName').val(data.Subject.SubjectName);
$('#txtStudentName').val(data.Student.StudentName);
$('#numScore').val(data.Score);
} else {
alert("Error!")
}
},
Error: function (err) {
console.log(err);
}
});
},
And ExamsController
[HttpGet]
public JsonResult LoadDetail(int id, int id1)
{
bool status = false;
Exam exam = new Exam();
exam = db.Exams.Find(id, id1);
status = true;
return Json(new
{
data = exam,
status = status
}, JsonRequestBehavior.AllowGet);
}
Internal server error means you have error in C# script, please double check error logs.
And also your code isnt cleanest, missing semi-colons.
Try add semi-colons, add name to function , and check error log, it can be useful, we can make better answer.
Maybe try this code with semi colon :) :
$('.btn-edit').off('click').on('click', function () {
$('#editModal').modal('show');
var id = parseInt($(this).attr('id'));
var id1 = parseInt($(this).attr('id1'));
ExamsController.LoadDetail(id, id1);
});
LoadDetail: function (id, id1) {
$.ajax({
url: '/Exams/LoadDetail',
type: 'GET',
data: {
id : id,
id1 : id1
},
dataType: 'json',
success: function (response) {
console.log(response.status);
if (response.status == true) {
var data = response.data;
$('#txtSubjectName').val(data.Subject.SubjectName);
$('#txtStudentName').val(data.Student.StudentName);
$('#numScore').val(data.Score);
} else {
alert("Error!");
}
},
Error: function (err) {
console.log(err);
}
});
},
Thanks!
I am using the following code to save a row in a datatable using a save button
$(document).on('click','.updateOrder', function(){
var thisRow = $(this).closest('tr');
var rejectReasons = { PersistRejectReasons :[] }
var jsonReturnObj = new Object();
jsonReturnObj.OrderNumber = thisRow.find('.dt_orderNo').text();
jsonReturnObj.OrderLineNumber = thisRow.find('.dt_orderLineNo').text();
jsonReturnObj.RejectReasonCode = thisRow.find('.dt_researchOutcome').find("option:selected").prop("value");
jsonReturnObj.RejectReasonNotes = thisRow.find('.dt_researchNotes').find('input').val();
if(jsonReturnObj.RejectReasonCode != "" && jsonReturnObj.RejectReasonCode != null) {
if(jsonReturnObj.RejectReasonCode =="14. Other") {
if(jsonReturnObj.RejectReasonNotes == "" || jsonReturnObj.RejectReasonNotes == "null") {
alert(" Please add Research Notes");
jsonReturnObj.Processed = false;
$('#orderReportTable').append("call failed");
throw new Exception("Error message");
}
}
jsonReturnObj.Processed = true;
}else {
jsonReturnObj.Processed = false;
}
if($("#movedInput"+jsonReturnObj.OrderNumber+"-"+jsonReturnObj.OrderLineNumber).is(':checked')){
jsonReturnObj.IsAvailable = false;
}else{
jsonReturnObj.IsAvailable = true;
}
rejectReasons.PersistRejectReasons.push(jsonReturnObj);
var jsonReturnString = JSON.stringify(rejectReasons);
console.log("Rejecting Store Number is "+$("#storeNum").val())
var request2 = $.ajax({
headers: {
'RejectingStoreNum': $("#storeNum").val(), //thisRow.find('.dt_storeNo').text(), //thisRow.find("td").eq(16).text(),
'Content-Type': 'application/json'
},
type: "POST",
url: "persistStoreResearchOutcome", // REST endpoint. replace url1 with REST Endpoint
data : jsonReturnString,//json data. use data and contentType attributes for POST requests.
contentType: "application/json",
dataType: "text",
/*xhrFields: {
'withCredentials': true //Tell browser to provide credentials
},*/
crossDomain: true,// this is for cross domain requests*/
success: function (data, status, jqXHR){
console.log("status:"+status);
$('#orderReportTable').append("call successful");
if(jsonReturnObj.Processed){
thisRow.find('.dt_itemStatus').text("Researched");
table.draw();
}else{
thisRow.find('.dt_itemStatus').text("Active");
table.draw();
}
},
error: function (jqXHR, status, errorThrown){
//console.log("failed: status:"+status);
$('#orderReportTable').append("call failed, error"+errorThrown);
alert("There was an error while trying to save this item");
}
});
});
I want to do the same processing but for all the rows in the table with one single click.I used the each function to loop over the rows but keep getting an error
$("table tr").each(function (){
console.log(this);
var thisRow = $(this).closest('td');
var rejectReasons = { PersistRejectReasons :[] }
var jsonReturnObj = new Object();
jsonReturnObj.OrderNumber = thisRow.find('.dt_orderNo').text();
jsonReturnObj.OrderLineNumber = thisRow.find('.dt_orderLineNo').text();
jsonReturnObj.RejectReasonCode = thisRow.find('.dt_researchOutcome').find("option:selected").prop("value");
jsonReturnObj.RejectReasonNotes = $(this).find('.dt_researchNotes').find('input').val();
if(jsonReturnObj.RejectReasonCode != "" && jsonReturnObj.RejectReasonCode != null) {
if(jsonReturnObj.RejectReasonCode =="14. Other") {
if(jsonReturnObj.RejectReasonNotes == "" || jsonReturnObj.RejectReasonNotes == "null") {
alert(" Please add Research Notes");
jsonReturnObj.Processed = false;
$('#orderReportTable').append("call failed");
throw new Exception("Error message");
}
}
jsonReturnObj.Processed = true;
}else {
jsonReturnObj.Processed = false;
}
if($("#movedInput"+jsonReturnObj.OrderNumber+"-"+jsonReturnObj.OrderLineNumber).is(':checked')){
jsonReturnObj.IsAvailable = false;
}else{
jsonReturnObj.IsAvailable = true;
}
rejectReasons.PersistRejectReasons.push(jsonReturnObj);
var jsonReturnString = JSON.stringify(rejectReasons);
console.log("Rejecting Store Number is "+$("#storeNum").val())
var request2 = $.ajax({
headers: {
'RejectingStoreNum': $("#storeNum").val(), //thisRow.find('.dt_storeNo').text(), //thisRow.find("td").eq(16).text(),
'Content-Type': 'application/json'
},
type: "POST",
url: "persistStoreResearchOutcome", // REST endpoint. replace url1 with REST Endpoint
data : jsonReturnString,//json data. use data and contentType attributes for POST requests.
contentType: "application/json",
dataType: "text",
/*xhrFields: {
'withCredentials': true //Tell browser to provide credentials
},*/
crossDomain: true,// this is for cross domain requests*/
success: function (data, status, jqXHR){
console.log("status:"+status);
// $('#orderReportTable').append("call successful");
if(jsonReturnObj.Processed){
this.find('.dt_itemStatus').text("Researched");
table.draw();
}else{
this.find('.dt_itemStatus').text("Active");
table.draw();
}
},
error: function (jqXHR, status, errorThrown){
//console.log("failed: status:"+status);
$('#orderReportTable').append("call failed, error"+errorThrown);
alert("There was an error while trying to save this item");
}
});
});
});
How can I fix this?
The error message is
http://localhost:8080/persistStoreResearchOutcome 500 ()
send # jquery-3.2.1.min.js:4
ajax # jquery-3.2.1.min.js:4
(anonymous) # (index):544
each # jquery-3.2.1.min.js:2
each # jquery-3.2.1.min.js:2
(anonymous) # (index):509
dispatch # jquery-3.2.1.min.js:3
q.handle # jquery-3.2.1.min.js:3
I tried different ways to loop over the table including the every() function from datatables,but keep getting the same error
I have a program written in angularjs. I'm receiving json data from server when online. I'm developing offline mode now..
I have the problem here but i dont know why i cant fix.
I saved json info to localStorage when program to offline get this json string.
service.js - For webservicecall
webServiceCallPost: function(data, action) {
console.log("data "+JSON.stringify(data));
console.log("action "+JSON.stringify(action));
var deferred = $q.defer();
if (navigator.connection.type != "none") {
return $.ajax({
type: "POST",
url: appConst.serviceUrl.service + action,
crossDomain: true,
dataType: "json",
data: data,
timeout: 2000000,
async: true,
success: function(response) {
localStorage.setItem(data + action, JSON.stringify(response));
deferred.resolve();
},
error: function(xhr, ajaxOptions, thrownError) {
$ionicLoading.hide();
if (xhr.status == 0) {
window.plugins.toast.showShortBottom($translate.instant("timedOutError"));
} else if (xhr.status == 404) {
window.plugins.toast.showShortBottom($translate.instant("timedOutError"));
} else {
window.plugins.toast.showShortBottom($translate.instant("timedOutError"));
}
},
beforeSend: function() {},
complete: function() {}
});
} else {
window.plugins.toast.showShortBottom($translate.instant("checkNetWorkConnection"));
$ionicLoading.hide();
var response1 = JSON.parse(JSON.stringify(localStorage.getItem(data + action)));
return $http.get('').then(function(response) {
return response1;
});
}
}
Controller.js - Retriveing response.
Services.webServiceCallPost('', appConst.services.get_menu_card).then(function(response) {
$ionicLoading.hide();
console.log("Response: " + JSON.stringify(response));
if (response[1].response.status == 1) {
if (response[0].data.menu.length > 0) {
var categoryResponse = [];
angular.forEach(response[0].data.menu, function(value, key) {
if (value.menu_image_name != '') {
var extraData = {
imageUrl: appConst.serviceUrl.menu_image_url + value.menu_image_name
}
}
else {
var extraData = {
imageUrl: 'img/screen.png'
};
}
angular.extend(value, extraData);
categoryResponse.push(value);
});
$rootScope.categories = globalMethods.getDashboardGridView(categoryResponse, 2);
}
if (response[0].data.addons.length > 0) {
$rootScope.totalAddons = [];
angular.forEach(response[0].data.addons, function(value, key) {
var extraData = {
"finalCost": value.price,
"quantity": 1,
imageUrl: appConst.serviceUrl.addon_image_url + value.addon_image
};
angular.extend(value, extraData);
$rootScope.totalAddons.push(value);
});
}
$scope.getSiteSettings();
}
$rootScope.dashboardHistoryId = $ionicHistory.currentHistoryId();
});
Console Output :
When i check from json pretty print its looking same.
Online Response : https://codepaste.net/op0boq
Cached Response : https://codepaste.net/y3bkd6
Problem:
TypeError: Cannot read property 'status' of undefined
When i want to get response1.response.status ok is getting.
But when i'm offline and i get cachedResponse1.response.status its retriving status is undefined. But exactly same data, why ?
if this code
var cachedResponse = JSON.parse(JSON.stringify(localStorage.getItem('' + appConst.services.get_menu_card)));
uses an asynchronous call
console.log("Cached Response: " + cachedResponse);
won't wait for it to finish and would print undefined
Thanks for answer to #PatrickEvans
Then you might have not returned the right thing... but also you shouldn't be doing JSON.parse(JSON.stringify(localStorage.getItem()) it should just be JSON.parse(localStorage.getItem()) localStorage items are already strings, stringifying it is going to mess up what you are trying to do
and
return $q.when(response1);
In the AJAX call below, I am attempting to debug the JavaScript call to understand why I cannot get to the error block when checking for failures. Whenever I debug in Chrome Developer tools, it jumps to the last line of the function and not the error block. Is there a easier way to test why this isn't being hit?
$("#input-userName").blur(function () {
var userNameTxt = $("#input-userName").val();
if (userNameTxt != prevUserName) {
if (userNameTxt.length >= 6 && userNameTxt.length <= 20) {
$("#divVerifyUserName").show();
$("#input-userName").prop("disabled", true);
$.ajax
({
type: "GET",
url: BASE_URL + "MyCall",
async: true,
data: { 'userName': userNameTxt },
success: function (resultset) {
prevUserName = userNameTxt
$("#userNameValidationMessage").removeClass("error");
if (resultset != null) {
$("#divVerifyUserName").hide();
$("#input-userName").prop("disabled", false);
if (resultset.status) {
$("#userNameValidationMessage").addClass("message");
}
else {
$("#userNameValidationMessage").removeClass("message");
$("#userNameValidationMessage").addClass("error");
}
$("#userNameValidationMessage").text(resultset.msg);
}
},
error: function (xhr, error) {
$("#userNameValidationMessage").text("Error while processing the request. Please try again.");
}
});
}
}
});
I am trying to get a Twitter access token from their oauth api. The plugin I am using is this https://code.google.com/p/oauth/source/browse/#svn%2Fcode%2Fjavascript. So far I only get "401 failed to validate signature and token".
Strange thing is that my ajax call becomes 'GET' request even though I set type:'POST'. Seems like jquery is changing the type from POST to GET. I don't know why it does that. I am running it on my Mac. I appreciate your help/hints/suggestions/advises. Thanks!
$(function() {
function myCallback(resp) {
console.log(resp);
}
var TwitterAPI;
TwitterAPI = (function() {
var consumer_key = null;
var consumer_secret = null;
function TwitterAPI(cons_key, cons_secret) {
this.consumer_key = cons_key;
this.consumer_secret = cons_secret;
}
TwitterAPI.prototype._url = function (data) {
if (typeof data == 'array') {
return array_map([ // TODO
this, '_url'], data);
} else if ((/boolean|number|string/).test(typeof data)) {
return encodeURIComponent(data).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
} else {
return '';
}
}
TwitterAPI.prototype.myCallback = function(resp) {
console.log(resp);
}
TwitterAPI.prototype.getRequestToken = function() {
var accessor = {
consumerSecret: this.consumer_secret, //this.consumer.consumerSecret,
tokenSecret: ''
};
var message = {
method: "POST",
action: "https://api.twitter.com/oauth/request_token",
parameters: {
oauth_signature_method: "HMAC-SHA1",
oauth_consumer_key: this.consumer_key, //this.consumer.consumerKey
oauth_callback: this._url("http://127.0.0.1/foobar/libs/oauth/wtf.html"),
}
};
OAuth.setTimestampAndNonce(message);
OAuth.SignatureMethod.sign(message, accessor);
var target = OAuth.addToURL(message.action, message.parameters);
message.parameters.oauth_signature = this._url(message.parameters.oauth_signature);
console.log(message.parameters);
$.ajax("https://api.twitter.com/oauth/request_token",
{ url: "https://api.twitter.com/oauth/request_token",
type: 'POST',
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: "myCallback",
data: message.parameters,
success: function(data, textResp, xhr) {
console.log(data);
},
error: function(xhr, text, err) {
console.log(text);
}
});
};
return TwitterAPI;
})();
api = new TwitterAPI(key, secret);
$('button#request').on('click', function(e) {
e.stopPropagation();
api.getRequestToken();
});