Success or error call back in AJAX not working - javascript

$(document).ready(function () {
$("#loginForm").submit(function (e)
{
var Data = $(this).serializeArray();
var formURL = $(this).attr("action");
var PostData =
{
"CompanyName": $(this).serializeArray().CompanyName,
"Username": $(this).serializeArray().Username,
"Password": $(this).serializeArray().Password
}
$.ajax(
{
url: formURL,
data: PostData,
success: function (data, textStatus, jqXHR) {
alert("Data" + data);
alert("Jq" + jqXHR);
alert("textStatus" + textStatus);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Failed..ajax error response type " + textStatus);
}
});
e.preventDefault(); //STOP default action
})
});
$("#loginForm").submit(); //SUBMIT FORM
This is a simple Ajax request to the C# code,that i have.I know for sure that the C# is giving a correct value(according to the situation).
C# return true or false as per the situation.But in any case this Ajax script neither giving me a alert window which i have coded for.
Instead i get this response from
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<boolean xmlns="http://schemas.microsoft.com/2003/10/Serialization/">false</boolean>
When false and just the value in the tag changes when its true.
Can anyone tell me why neither success or error is not working.

Something that make work better is this:
$("#loginForm").submit(function (event) {
event.preventDefault();
$.post($(this).attr("action"), $(this).serialize())
.done(function (results) {
alert(results);
})
.fail(function (error) {
alert(error);
})
.always(function () {
alert("AJAX Complete");
});
});

As you can tell from it's name the .serializeArray() method returns an array -- not an object. The array is of the form:
[
{
name: "a",
value: "1"
},
{
name: "b",
value: "2"
},
{
name: "c",
value: "3"
}
]
array of objects
Ref: http://api.jquery.com/serializearray/
What you need: http://api.jquery.com/serialize/
Therefore to access the third value you would need to supply the index 2 -- ..[2].value ... name ...[2].name. Your code has errors that would prevent the ajax call from being made. Is it possible that error is coming from somewhere else?
Therefore change:
var PostData =
{
"CompanyName": $(this).serializeArray().CompanyName,
"Username": $(this).serializeArray().Username,
"Password": $(this).serializeArray().Password
}
To:
var PostDate = $(this).serialize();

Related

AJAX Post call no data

Hello wenn i want to send a post request to my Controller there is no data.
I tried to log my Json file and there is something. But when I send the post request my controller shows it is empty.
Here is my call:
var item = {};
var jsonObj = [];
item["ProductCategoryId"] = i;
item["Name"] = txtName;
item["Description"] = txtDescription;
item["Price"] = txtPrice;
item["Stock"] = txtStock;
item["ProductCategory"] = txtProductCategory;
item["Image"] = await getAsByteArray(txtImage);
jsonObj.push(item);
var jsonString = JSON.stringify(jsonObj);
console.log("jsonString : " + jsonString);
$.ajax({
url: "/Admin/SaveProductToDB",
type: "POST",
data: { dataToSend: jsonString},
success: function (data) {
if (data.status == "Success") {
BootstrapDialog.show({
title: 'Success!',
message: "Data Updated Successfully!",
buttons: [{
label: 'OK',
action: function (dialog) {
window.location.href = "/Admin/Product";
removeProdData(i);
$("#btnAddProd").attr("disabled",false);
dialog.close();
}
}]
});
}
}
});
//Here I make a breakpoint but my string is empty
public JsonResult SaveProductToDB(string dataToSend)
{
List<Product> _List = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Product>>(dataToSend);
}
the getAsByteArray
async function getAsByteArray(file) {
return new Uint8Array(await readFile(file))
}
function readFile(file) {
return new Promise((resolve, reject) => {
// Create file reader
let reader = new FileReader()
// Register event listeners
reader.addEventListener("loadend", e => resolve(e.target.result))
reader.addEventListener("error", reject)
// Read file
reader.readAsArrayBuffer(file)
})
}
I found out if I remove the Image. that the controller is then able to resize it. Thanks for the help so far. So I need to look at this place where the problem is.
You are checking against data.status as if it's a given that it exists. Just console.log(data) instead and you will see whether or not status is being returned.
Also, if you open the Network tab in Chrome you can click on the post request & see if your headers are going through accurately and also click on 'Preview' to see an unfiltered result from the controller.
You might want to modify your code to catch errors for debugging, ie:
$.ajax({
url: "/Admin/SaveProductToDB",
type: "POST",
data: { dataToSend: jsonString},
success: function (data) {
if (data.status == "Success") {
BootstrapDialog.show({
title: 'Success!',
message: "Data Updated Successfully!",
buttons: [{
label: 'OK',
action: function (dialog) {
window.location.href = "/Admin/Product";
removeProdData(i);
$("#btnAddProd").attr("disabled",false);
dialog.close();
}
}]
});
}
},
error:function (xhr, ajaxOptions, thrownError) {
// Set up whatever error reaction you want, here. ie:
console.log('An error was encountered.');
alert(xhr.status);
alert(thrownError);
}
});
Another tip is to validate empty data being submitted prior to the Ajax call, so you only touch the backend server when your data is valid - to avoid an error.

Ajax call showing error cant debug

this is how the javascript looks like
<script type="text/javascript">
$(document).ready(function () {
$('#loginButton').click(function () {
//this.disabled = true;
debugger;
var data = {
"userid": $("#username").val(),
"password": $("#password").val()
};
$.ajax({
url: "/Account/LoginPost",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
contentType: "application/json",
success: function (response) {
if (response.Success) {
$.get("#Url.Action("Search", "Home")", function (data) {
$('.container').html(data);
});
}
else
window.location.href = "#Url.Action("Index", "Home")";
},
error: function () {
alert('Login Fail!!!');
}
});
});
});
I am getting the alert('Login fail') also debugger not getting hit.
I am using jquery 1.9.1 and have included unobstrusive
my controller is this as you can i am passing string values not object values
to the controller so stringify is justified here
[HttpPost]
public JsonResult LoginPost(string userid, string password)
{
using (someentities wk = new someentities())
{
var LoginUser = wk.tblUsers.Where(a => a.Username.Equals(userid)&&a.Password.Equals(password)).FirstOrDefault();
if (LoginUser != null)
{
FormsAuthentication.SetAuthCookie(userid,false);
Session["Username"] = LoginUser.Username;
Session["Password"] = LoginUser.Password;
Session["Name"] = LoginUser.Name;
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
else
{
TempData["Login"] = "Please Enter Correct Login Details";
return Json(new { Success = false }, JsonRequestBehavior.AllowGet);
}
}
// If we got this far, something failed, redisplay form
}
when page is loading these error are shown
$(..) live is not a valid function in
(anonymous function) # jquery.unobtrusive-ajax.js:115
(anonymous function) # jquery.unobtrusive-ajax.js:163
take a look to the success function
success: function (response) {
if (response.Success) {
$.get("#Url.Action("Search", "Home")", function (data) {
$('.container').html(data);
});
}
else
window.location.href = "#Url.Action("Index", "Home")";
}
you are using multiple ", combine it with the single one ', this is a syntax error, try to check the code on an editor such as Atom, to avoid this kind of errors
Stringify converts an object to a string. Have you tried passing data an object instead of a string? Try replacing JSON.stringify(data), with data?

Not able to get data in the dataFilter function

I am trying to filter the json array received from the server. I'm able to receive the data properly in the success function however I get a "data is undefined error" within the filterdata block. [Uncaught TypeError: Cannot read property 'list' of undefined]
$(function () {
function log(message) {
$("<div>").text(message).prependTo("#log");
$("#log").scrollTop(0);
}
$("#city").autocomplete({
source: function (request, response) {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/find?mode=json&type=like",
dataType: "jsonp",
data: {
q: request.term
},
dataFilter: function (data, type) {
console.log(data);
alert(data.list.length);
alert(data.list[0].name + ', ' + data.list[0].sys.country);
jsonObj = [];
for (i = 0; i < data.list.length; i++) {
item = {}
item["city"] = data.list[0].name;
item["country"] = data.list[0].sys.country;
jsonObj.push(item);
}
return jsonObj;
},
success: function (data) {
//alert(data.list.length);
response(data);
}
});
},
minLength: 3,
select: function (event, ui) {
log(ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
});
As dataFilter is a function to be used to handle the raw response data of XMLHttpRequest. Since you are using JSONP request, which is not an XHR request so there is no XHR object and no raw data, which makes the behavior of dataFilter in your case perfectly valid. You should check the response in success callback instead.

Loading remote data only once with Select2

As the title suggests I would like to load remote data once only.
I thought about loading a data with independent ajax call and set it "locally" at the control but wonder if there is more "built in" way to do so...
a solution can be found here:
https://github.com/ivaynberg/select2/issues/110
$("#selIUT").select2({
cacheDataSource: [],
placeholder: "Please enter the name",
query: function(query) {
self = this;
var key = query.term;
var cachedData = self.cacheDataSource[key];
if(cachedData) {
query.callback({results: cachedData.result});
return;
} else {
$.ajax({
url: '/ajax/suggest/',
data: { q : query.term },
dataType: 'json',
type: 'GET',
success: function(data) {
self.cacheDataSource[key] = data;
query.callback({results: data.result});
}
})
}
},
width: '250px',
formatResult: formatResult,
formatSelection: formatSelection,
dropdownCssClass: "bigdrop",
escapeMarkup: function (m) { return m; }
});
Edit:
I might have misinterpreted your question. if you wish to load all data once, then use that is Select2, there is no built in functionality to do that.
Your suggestion to do a single query, and then use that stored data in Select2 would be the way to go.
This is for Select2 v4.0.3:
I had this same question and got around it by triggering an AJAX call and using the data returned as the initialized data array.
// I used an onClick event to fire the AJAX, but this can be attached to any event.
// Ensure ajax call is done *ONCE* with the "one" method.
$('#mySelect').one('click', function(e) {
// Text to let user know data is being loaded for long requests.
$('#mySelect option:eq(0)').text('Data is being loaded...');
$.ajax({
type: 'POST',
url: '/RetrieveDropdownOptions',
data: {}, // Any data that is needed to pass to the controller
dataType: 'json',
success: function(returnedData) {
// Clear the notification text of the option.
$('#mySelect option:eq(0)').text('');
// Initialize the Select2 with the data returned from the AJAX.
$('#mySelect').select2({ data: returnedData });
// Open the Select2.
$('#mySelect').select2('open');
}
});
// Blur the select to register the text change of the option.
$(this).blur();
});
This worked well for what I had in mind. Hope this helps people searching with the same question.
To load data once:
Assumptions:
You have a REST API endpoint at /services that serves a JSON array of objects
The array contains objects which have at least a "name" and "id" attribute. Example:
[{"id": 0, "name": "Foo"}, {"id": 1, "name": "Bar"}]
You want to store that array as the global 'services_raw'
First, our function to load the data and create the global 'services_raw' (AKA 'window.services_raw'):
fetchFromAPI = function() {
console.log("fetchFromAPI called");
var jqxhr = $.ajax(
{
dataType:'json',
type: 'GET',
url: "/services",
success: function(data, textStatus, jqXHR) {
services_raw = data;
console.log("rosetta.fn.fetchServicesFromAPI SUCCESS");
rosetta.fn.refreshServicesSelect();
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error inside rosetta.fn.fetchServicesFromAPI", errorThrown, textStatus, jqXHR);
setTimeout(rosetta.fn.fetchServicesFromAPI(), 3000); // retry in 3 seconds
}
}
)
.done(function () {
console.log("success");
console.log(jqxhr);
})
.fail(function () {
console.log("error");
})
.always(function () {
console.log("complete");
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function () {
console.log("second complete");
});
};
Second, our Select2 instantiation code which transforms our data into a format that Select2 can work with:
refreshServicesSelect = function () {
// ref: http://jsfiddle.net/RVnfn/2/
// ref2: http://jsfiddle.net/RVnfn/101/ # mine
// ref3: http://jsfiddle.net/RVnfn/102/ # also mine
console.log('refreshServicesSelect called');
$("#add-service-select-service").select2({
// allowClear: true
data: function() {
var arr = []; // container for the results we're returning to Select2 for display
for (var idx in services_raw) {
var item = services_raw[idx];
arr.push({
id: item.id,
text: item.name,
_raw: item // for convenience
});
}
return {results: arr};
}
});
};
Here's what the Select2 element in HTML should look like before your call the above functions:
<input id="add-service-select-service" type="hidden" style="width:100%">
To use all of this, call (in JS):
window.fetchFromAPI();
window.refreshServicesSelect();
Lastly, here's a JSFiddle where you can play with a similar thing: http://jsfiddle.net/RVnfn/102/
Basically, in my example above, we're just using ajax to populate the equivalent of window.pills in the Fiddle.
Hope this helps :)
Please reply if you know how to do this via the Select2 .ajax function, as that would be a bit shorter.
In my condition, it is working perfectly with the given code
$('#itemid').select2({
cacheDataSource: [],
closeOnSelect: true,
minimumInputLength: 3,
placeholder: "Search Barcode / Name",
query: function(query) {
// console.log(query);
self = this;
var key = query.term;
var cachedData = self.cacheDataSource[key];
if(cachedData) {
query.callback({results: cachedData});
return;
} else {
$.ajax({
url: "./includes/getItemSelect2.php",
data: { value : query.term },
dataType: 'json',
type: 'POST',
success: function(data) {
self.cacheDataSource[key] = data;
query.callback({results: data});
}
});
}
},
});
And my data return from the ajax is in this form
<?php
$arr = [
["id" => 1, "text" => "Testing"],
["id" => 2, "text" => "test2"],
["id" => 3, "text" => "test3"],
["id" => 4, "text" => "test4"],
["id" => 5, "text" => "test5"]
];
echo json_encode($arr);
exit();
?>

No indication jquery ajax call completes

I have the following ajax call
function update_ledger_amount(id) {
$.ajax({
type: "POST",
url: "/ledgeritems/UpdateAmount",
data: "Id=" + id + "&Amount=" + $('#ledger_edit_amount_input_' + id).val(),
success: function (str) {
var result = str.split('|');
alert(str);
if (result[0] == 'success') {
set_display_message('Item updated', 'success');
load_ledger_month($('#BankAccountId').val(), $('#StartDate').val());
}
else {
alert('bad');
set_display_message(result[1], 'error');
}
},
error: function (request, status, error) {
alert(error);
}
});
}
The problem I'm having is that I get no alerts on success or error. Watching the traffic via firebug I can see the response is a simple
success
I believe the problem could have to do with the content-type of the response, it shows as text/javascript. I'm thinking maybe I need to do something different to handle that content type.
use dataType as json and send the response as json in your controller(php).. you can do that by ...echo json_encode(array('success'=>'success'))
JQUERY
$.ajax({
type: "POST",
url: "/ledgeritems/UpdateAmount",
data: "Id=" + id + "&Amount=" + $('#ledger_edit_amount_input_' + id).val(),
dataType:'json',
success: function (str) {
alert(str.success); //in mycase.. you can do your stuff here
/*var result = str.split('|');
alert(str);
if (result[0] == 'success') {
set_display_message('Item updated', 'success');
load_ledger_month($('#BankAccountId').val(), $('#StartDate').val());
}
else {
alert('bad');
set_display_message(result[1], 'error');
}*/
},
error: function (request, status, error) {
alert(error);
}
});
PHP
.....
echo json_encode(array('success'=>'success'));
this sends success as json and you can get that in success function of ajax
put a try catch block in your success handler. I guess it is failing at this line
ar result = str.split('|');
You're doing a POST ajax not GET. The data part of the ajax should be in the form of:
data: { name: "John", location: "Boston" }
Remove the line
type = "POST",
because you want to append params to the url with your request.
As of jQuery 1.8 success, error and complete are deprecated, use done, fail and allways instead.
http://api.jquery.com/jQuery.ajax/#jqXHR
The syntax for a POST would be like:
data = {id:"something", Amount:"someval"};

Categories