I want to submit a form with jquery Ajax. But it does not show any kind of message. I have followed this question and this question. But I didn't get my solution. My jquery code is:
$(document).ready(function () {
$("#btnSave").submit(function (e) {
e.preventDefault();
var myTableArray = [];
$("table#vouchTable tr").not(':first').each(function () {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function () { arrayOfThisRow.push($(this).text()); });
myTableArray.push(arrayOfThisRow);
}
}); ///This Part works fine
///But this part does not work
$.ajax({
url: '/Accounts/VoucherEntry',
type: 'POST',
data: JSON.stringify(myTableArray),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert(msg);
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
return false;
////////////////////
});
});
Try this:
Missing end brackets for : $(document).ready(function () {
Missing end brackets for : $("#btnSave").submit(function (e) {
$(document).ready(function () {
$("#btnSave").submit(function (e) {
e.preventDefault();
var myTableArray = [];
$("table#vouchTable tr").not(':first').each(function () {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function () { arrayOfThisRow.push($(this).text()); });
myTableArray.push(arrayOfThisRow);
}
});
var data = JSON.stringify(myTableArray);
$.ajax({
url: '/Accounts/VoucherEntry',
type: 'POST',
data: data,
dataType: 'json',
success: function (msg) {
alert(msg);
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}); // <----- Missing brackets!!!
}); // <----- Missing brackets!!!
Format you data like:
data: {data:myTableArray},
in c# get the data by the key data
Related
How to get All the elements of the Listbox when Button Click event is fired by using ajax call
I am using a function and trying to call the function in ajax call my function is working fine it returning all the elements from the List box when I am trying to bind it with the ajax call its not working i need to call the elements in the code behind:
function responseData2() {
debugger;
var oListbox = $("#submitlistbox2").each(function () {
var data = $(this).text() + " " + $(this).val()+"\n";
alert("The Names are: " + data);
});
var jobsheet = data;
$.ajax({
url: "OnlineBiddingofExtraBoardDaysOff.aspx/Details4",
type: "POST",
contentType: "application/json; charset=utf-8",
cache: false,
data: "{ 'selectedJobSheet': '" + jobsheet + "'}",
success: function (data) {
alert(data);
alert("success");
},
error: function (response) {
alert(response);
alert("error");
}
});
}
My code-behind data:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static object Details4(string selectedJobSheet)
{
try
{
string constr = ConfigurationManager.ConnectionStrings["Constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("select customer_id,first_name from jobsheetDetails", con))
{
string _data = "";
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
_data = JsonConvert.SerializeObject(ds.Tables[0]);
}
return _data;
}
}
}
catch (Exception)
{
throw;
}
}
It seems your variable data was inside the loop. Try to use object method to fix your problem.
function responseData2() {
debugger;
var holder_all_data = [];
var oListbox = $("#submitlistbox2").each(function () {
var data = $(this).text() + " " + $(this).val()+"\n";
alert("The Names are: " + data);
holder_all_data.push({
var_name_data : data,
});
});
$.ajax({
url: "OnlineBiddingofExtraBoardDaysOff.aspx/Details4",
type: "POST",
contentType: "application/json; charset=utf-8",
cache: false,
data: "{ 'selectedJobSheet': '" + holder_all_data + "'}",
success: function (data) {
alert(data);
alert("success");
},
error: function (response) {
alert(response);
alert("error");
}
});
}
And then next, if you want to get the individual name value which's thrown by AJAX, you should use foreach loop and it should look like this. :D
e.g
foreach( selectedJobSheet as $item ){
var name = $item['var_name_data']; //include the object variable name
console.log(name);
}
Try this:
function responseData2() {
debugger;
var jobsheet = [];
$("#submitlistbox2").each(function () {
var data = $(this).text() + " " + $(this).val();
jobsheet.push(data);
alert("The Names are: " + data);
});
$.ajax({
url: "OnlineBiddingofExtraBoardDaysOff.aspx/Details4",
type: "POST",
contentType: "application/json; charset=utf-8",
cache: false,
data: { "selectedJobSheet": JSON.stringify(jobsheet) },
dataType: "json",
success: function (data) {
alert(data);
alert("success");
},
error: function (response) {
alert(response);
alert("error");
}
});
}
Code Behind:
[WebMethod]
public void Details4(string selectedJobSheet)
{
List<string> selectedJobSheetList = new List<string>();
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new DynamicJsonConverter() });
dynamic data = serializer.Deserialize(selectedJobSheet, typeof(object));
foreach (var item in data)
{
selectedJobSheetList.Add(item);
}
}
It seems your data variable is overwritten in a loop and that is the issue. Hope below will help you.
function responseData2() {
var data = [];
var oListbox = $("#submitlistbox2").each(function (i) {
var data[i] = $(this).text() + " " + $(this).val()+"\n";
alert("The Names are: " + data[i]);
});
var jobsheet = JSON.stringify(data);
$.ajax({
url: "OnlineBiddingofExtraBoardDaysOff.aspx/Details4",
type: "POST",
contentType: "application/json; charset=utf-8",
cache: false,
data: "{ 'selectedJobSheet': " + jobsheet + "}",
success: function (data) {
alert(data);
alert("success");
},
error: function (response) {
alert(response);
alert("error");
}
});
}
I have the following javascript code it works sfine the problem the dropdown list only shows [object object]
how do i go about fixing this error.
<script type="text/javascript">
$(document).ready(function () {
$("#RepfocusModelDropdown").change(function () {
var Id = $(this).val();
if (Id != null) {
$.ajax({
type: "POST",
url: "./Create?handler=UserSelect",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
Id: Id
},
dataType: "json",
success: function (response) {
$("#Repfocususerdropdown").empty();
alert(response);
$.each(response, function (i, item) {
$("#Repfocususerdropdown").append("<option>" + { value: item.Name, text: item.Name } + "</option>");
});
},
error: function (response) {
alert(response);
}
});
}
})
})
Use this code inside success function:
var user = $('#Repfocususerdropdown').empty(), opt = null;
$.each(response, function (i, item) {
opt = $('<option/>', {"text": item.Name, "value": i});
user.append(opt);
});
$(document).ready(function() {
$("#movieForm").submit(function(e) {
e.preventDefault();
var symbol = $("#movieInput").val();
$.ajax({
url: 'http://api.rottentomatoes.com/api/public/v1.0/movies.jsonapikey=x78wnu3hc3ve7amqeffws693&q=' + symbol dataType:'jsonp',
success: function(data) {
console.log(data);
}
});
});
});
try this:
$(document).ready(function() {
$("#movieForm").submit(function(e) {
e.preventDefault();
var symbol = $("#movieInput").val();
$.ajax({
url: 'http://api.rottentomatoes.com/api/public/v1.0/movies.jsonapikey=x78wnu3hc3ve7amqeffws693&q=' + symbol, // you missed this comma. supprised it didn't throw an error
dataType:'jsonp',
success: function(data) {
console.log(data);
}
});
});
});
but check this: Is your key still active?
http://developer.rottentomatoes.com/docs/read/JSON
I am having jquery code to invoke ashx file. Its perfectly working while page load. When i call the function from another function means not working.I have place the two codes here.
Please check and help me.
<script type="text/javascript">
$(document).ready(function () {
try {
$("#submit").click(function () {
var user = $("#login").val();
var pass = $("#password").val();
CallLoginHandler(user, pass);
}
}catch(ex){
}
</script>
<script type="text/javascript">
function CallLoginHandler(user, pass) {
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx?MainPage=GetUserDetails&Type=2&user=" + user + "&pass=" + pass + "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.length > 0) {
alert(response[0]["FLD_ID"]);
//successCallback(response);
} else {
alert(response[0]["FLD_ID"]);
}
}
});
}
</script>
I think you are missing the proper jquery syntax . Try the following modified code :-
<script type="text/javascript">
$(document).ready(function () {
try {
$("#submit").click(function () {
var user = $("#login").val();
var pass = $("#password").val();
CallLoginHandler(user, pass);
});
} catch (ex) {
}
});
function CallLoginHandler(user, pass) {
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx?MainPage=GetUserDetails&Type=2&user=" + user + "&pass=" + pass + "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.length > 0) {
alert(response[0]["FLD_ID"]);
//successCallback(response);
} else {
alert(response[0]["FLD_ID"]);
}
}
});
}
</script>
I've two javascript classes (Controller.js & Events.js).
From Events.js i call a XML Parser in Controller.js. The Parser works but does not return anything:
SceneEvent.prototype.handleKeyDown = function (keyCode) {
switch (keyCode) {
case sf.key.ENTER:
var itemList = null;
itemList = Controller.ParseXML("app/data/Event.xml");
alert("itemList = " + itemList);
}
};
Controller.js looks like that:
Controller.ParseXML = function (url) {
var itemList = null;
$.ajax({
type: "GET",
url: url,
dataType: "xml",
async: false,
success: function(xml) {
$(xml).find("event").each(function() {
var _id = $(this).attr("id");
var _eventItemDay = $(this).find("eventItemDay").text();
...
var _eventItemLocation = $(this).find("eventItemLocation").text();
itemList = {
id: _id,
eventItemDay: _eventItemDay,
eventItemLocation: _eventItemLocation,
...
eventItemLocation: _eventItemLocation
};
});
return itemList;
},
error: function(xhr, ajaxOptions, thrownError){
alert("XML ERROR");
alert(xhr.status);
alert(thrownError);
}
});
};
When I print out the itemList in Controller.js everything works fine.
Any suggestions?
You have to return the value at the end of the ParseXML function, not at the end of the success function.
Controller.ParseXML = function (url) {
var itemList = null;
$.ajax({
type: "GET",
url: url,
dataType: "xml",
async: false,
success: function(xml) {
$(xml).find("event").each(function() {
var _id = $(this).attr("id");
var _eventItemDay = $(this).find("eventItemDay").text();
...
var _eventItemLocation = $(this).find("eventItemLocation").text();
itemList = {
id: _id,
eventItemDay: _eventItemDay,
eventItemLocation: _eventItemLocation,
...
eventItemLocation: _eventItemLocation
};
});
},
error: function(xhr, ajaxOptions, thrownError){
alert("XML ERROR");
alert(xhr.status);
alert(thrownError);
}
});
return itemList;
};
You might want to consider making your ajax call async and add a callback to your ParseXML function. Something like this in event handler:
itemList = Controller.ParseXML("app/data/Event.xml", function(itemList){
alert("itemList = " + itemList);
});
And in ParseXML:
Controller.ParseXML = function (url, callback) {
var itemList = null;
$.ajax({
type: "GET",
url: url,
dataType: "xml",
async: true,
success: function(xml) {
$(xml).find("event").each(function() {
var _id = $(this).attr("id");
var _eventItemDay = $(this).find("eventItemDay").text();
...
var _eventItemLocation = $(this).find("eventItemLocation").text();
itemList = {
id: _id,
eventItemDay: _eventItemDay,
eventItemLocation: _eventItemLocation,
...
eventItemLocation: _eventItemLocation
};
callback( itemList );
});
},
error: function(xhr, ajaxOptions, thrownError){
alert("XML ERROR");
alert(xhr.status);
alert(thrownError);
callback( "XML ERROR " + xhr.status + " " + thrownError );
}
});
};
You'll want to check the value in the callback for errors of course.