Send JSON data over 2000 characters - javascript

Is that possible to send JSON data over 2000 chars?
My url length is 5260, and I get error GET 404().
Is there any solution to send this data in json?
update: {
url: ServiceBase + "Coating/updateTestResult",
dataType: "json",
complete: function (jqXHR, textStatus) {
if (jqXHR.status == "200") {
showNotification("Alert", "Records updated.", "upload-success");
} else {
showNotification("Error", "Couldn't update records.", "info");
}
}
}
if (operation === "update") {
$.each(dataSource._data, function () {
var row = $("#grid tbody").find("tr[data-uid='" + this.uid + "']");
if (row.hasClass("blur")) {
row.removeClass("blur");
}
this.dirty = false;
});
return { models: kendo.stringify(options.models) };
}

Try to perform a POST request instead. Max. URL length is 2000 chars (SO answer) that's why you get an error 404.

Related

window.location.replace is always undefined

I have a ajax post that I need to redirect to redirect url on success.
In the browser debugger I do c the correct url but I'm always getting "MYURL/undefined".
$.ajax({
type: 'POST',
url: "/NewsLetter/Create",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: data,
success: function(result) { //debug >result={urlOne:'https://localhost:7077'}
// alert('Successfully received Data ');
if (result.UrlOne !== undefined) {
window.location.replace(result.UrlOne);
} else {
window.location.replace(result.UrlTwo);
}
console.log(result);
},
error: function(error) {
alert('Failed to receive the Data');
console.log(JSON.stringify(error));
console.log('Failed ');
}
});
In my controller:
if (ModelState.IsValid && isNewUser == null)
{
//remove for clear code
return Json(new { UrlOne = Url.ActionLink("Index","Home")});
}
TempData["ErrorMes"] = "You are allready register";
return Json(new { UrlTwo = Url.ActionLink("_RegNews", "NewsLetter") });
Pass the JsonSerializerOptions as a parameter when creating the Json object to make property's name case-sensitive during deserialization. The JsonSerializerOptions has PropertyNameCaseInsensitive property that by default set to false. This will prevent the Json serializer to change names to be camel-cased.
var options = new System.Text.Json.JsonSerializerOptions();
if (ModelState.IsValid && isNewUser == null)
{
//remove for clear code
return Json(new { UrlOne = Url.ActionLink("Index","Home")}, options);
}
TempData["ErrorMes"] = "You are allready register";
return Json(new { UrlTwo = Url.ActionLink("_RegNews", "NewsLetter") }, options);
JsonSerializerOptions Class
Please check the return json from controller:
You will find that the key is urlOne instead of UrlOne.
Javascript is case sensitive, So you need to change your code like:
if (result.urlOne !== undefined) {
window.location.replace(result.urlOne);
} else {
window.location.replace(result.urlTwo);
}

Laravel Submitting form with same input name ajax

I need help with my ajax function. I have a form that submits data with the same input name
When I run my code without javascript, I can insert multiple input data with the same name,
Submitted structure
{"_token":"CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu","id":"7","service_name":["asfd","safd"]}
When I implement javascript, a concatenated string is sent to the controller and this makes the service_name inaccessible.
formdata:"_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=7&service_name%5B%5D=sdfg&service_name%5B%5D=gfds&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=8&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=9&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=10&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=11&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=18"
My javascript function
jQuery("form.ajax").on("submit", function (e) {
e.preventDefault();
jQuery.ajax({
url: "/admin/adminpanel/insertService/",
type: "post",
data: {
formdata: $(".ajax#servicesForm").serialize()
},
dataType: "JSON",
success: function (response) {
console.log(response);
},
error: function (jqXHR, exception) {
var msg = "";
if (jqXHR.status === 0) {
msg = "Not connect.\n Verify Network.";
} else if (jqXHR.status === 404) {
msg = "Requested page not found. [404]";
} else if (jqXHR.status === 500) {
msg = "Internal Server Error [500].";
} else if (exception === "parsererror") {
msg = "function Requested JSON parse failed.";
} else if (exception === "timeout") {
msg = "Time out error.";
} else if (exception === "abort") {
msg = "Ajax request aborted.";
} else {
msg = "Uncaught Error.\n" + jqXHR.responseText;
}
}
});
});
My PHP Controller Function
public function insert(Request $request)
{
return response()->json($request);
}
use FormData Object, to send fromdata
fd = new FormData();
fd.append("input-name", value1);
fd.append("input-name2", value2 OR arry of value);
jQuery.ajax({
url: "/admin/adminpanel/insertService/",
type: "post",
data: {
formdata: fd
}
I found a workaround:
First, I created an array, and pushed all instances of input[name='service_name[]'] into the array.
Then I passed the data with ajax and was able to insert the data.
var serviceArray = new Array(), id;
jQuery.map($("input[name='service_name[]']"), function(obj, index) {
serviceArray.push($(obj).val());
});
My ajax script then:
jQuery.ajax({
url: "/admin/adminpanel/insertService/",
type: 'post',
data: {
'service_name': serviceArray,
'id': id
},
dataType: 'JSON',
success: function(response) {
console.log(response);
}
});

Why is my requestPayload empty on my ajax request

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

Save multiple table rows with one save button in javascript

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

Response string JavaScript undefined

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

Categories