i am trying to implement an ajax call using jquery.when i am submitting the call, it is throwing 400 Bad Request..Not sure where i am doing wrong in my ajax call..Need help in fixing this..
submitHandler:function(form){
var emailSub = $("#emailSubTxtArea").val();
var emailBody = $("#emailBodyTxtArea").val();
if(confirm("You are about to send Email Communication, Are you sure..?")){
$.ajax({
type: "POST",
url: $("#applicationUrl").val() +"/web/utilities/sendEmailMessage",
dataType: "json",
//cache:false,
contentType: "application/json; charset=utf-8",
data:JSON.stringify({emailSubject : emailSub,emailMsg : emailBody}),
success:function(data)
{
console.log("Sending Email Notification was success.");
},
error: function(x, t, m) {
console.trace();
if (!(console == 'undefined')) {
console.log("ERROR: " + x + t
+ m);
}
}
});
}
my Controller code:
#RequestMapping(value="/sendEmailMessage",method=RequestMethod.POST)
public ModelAndView sendEmailCommunication(#RequestParam("emailSubject") String emailSubject,#RequestParam("emailMsg") String emailBody,HttpServletRequest request){
ModelAndView view = null;
StringBuffer sMsg = new StringBuffer();
StringBuffer eMsg = new StringBuffer();
boolean isAdmin = false;
try{
String loggedInUser = request.getHeader("sm_user").trim();
isAdmin = getUserAdminRights(request);
if(isAdmin){
boolean status = emailService.sendEmailCommuncation(emailSubject,emailBody);
if(status){
sMsg.append(" Sending SiteMinder Notification Email was Success.");
}
else{
eMsg.append(" Oops! Something went wrong while sending Email Notification. Pls check logs");
}
}
else{
view = new ModelAndView("redirect:/web/utilities/not_authorized");
return view;
}
}
catch(Exception ex){
ex.printStackTrace();
eMsg.append("Oops! Something went wrong while sending Email Notification. Pls check logs");
}
view = new ModelAndView("EmailCommunication");
view.addObject("isAdmin", isAdmin);
view.addObject("sMsg", sMsg.toString());
view.addObject("eMsg", eMsg.toString());
return view;
}
cheers guys...
Very Simple
submitHandler:function(form){
if(confirm("You are about to send Email Communication, Are you sure..?")){
$.ajax({
type: "POST",
url: $("#applicationUrl").val() +"/web/utilities/sendEmailMessage",
data:$(form).serializeArray(),
success:function(data)
{
console.log("Sending Email Notification was success.");
},
error: function(x, t, m) {
console.trace();
if (!(console == 'undefined')) {
console.log("ERROR: " + x + t
+ m);
}
}
});
}
var strResponse=$.ajax({ type: "POST", url: $("#applicationUrl").val() +"/web/utilities/sendEmailMessage",
data: JSON.stringify({emailSubject : emailSub,emailMsg : emailBody}), async: false,
contentType: "application/json;
charset=utf-8", dataType: "json" });
if (strResponse.readyState == 4 && strResponse.status == 200)
return ((strResponse.responseText.indexOf("d") >= 0) ? eval('(' + strResponse.responseText + ')').d : strResponse.responseText);
Related
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);
}
});
I am trying to implement an ajax call using jquery.when i am submitting the call, it is throwing 400 Bad Request..Not sure where i am doing wrong in my ajax call..Need help in fixing this..
submitHandler:function(form){
var emailSub = $("#emailSubTxtArea").val();
var emailBody = $("#emailBodyTxtArea").val();
if(confirm("You are about to send Email Communication, Are you sure..?")){
$.ajax({
type: "POST",
url: $("#applicationUrl").val() +"/web/utilities/sendEmailMessage",
dataType: "json",
//cache:false,
contentType: "application/json; charset=utf-8",
data:JSON.stringify({emailSubject : emailSub,emailMsg : emailBody}),
success:function(data)
{
console.log("Sending Email Notification was success.");
},
error: function(x, t, m) {
console.trace();
if (!(console == 'undefined')) {
console.log("ERROR: " + x + t
+ m);
}
}
});
}
return false;
}
my Controller code:
#RequestMapping(value="/sendEmailMessage",method=RequestMethod.POST)
public ModelAndView sendEmailCommunication(#RequestParam("emailSubject") String emailSubject,#RequestParam("emailMsg") String emailBody,HttpServletRequest request){
ModelAndView view = null;
StringBuffer sMsg = new StringBuffer();
StringBuffer eMsg = new StringBuffer();
boolean isAdmin = false;
try{
String loggedInUser = request.getHeader("sm_user").trim();
isAdmin = getUserAdminRights(request);
if(isAdmin){
boolean status = emailService.sendEmailCommuncation(emailSubject,emailBody);
if(status){
sMsg.append(" Sending SiteMinder Notification Email was Success.");
}
else{
eMsg.append(" Oops! Something went wrong while sending Email Notification. Pls check logs");
}
}
else{
view = new ModelAndView("redirect:/web/utilities/not_authorized");
return view;
}
}
catch(Exception ex){
ex.printStackTrace();
eMsg.append("Oops! Something went wrong while sending Email Notification. Pls check logs");
}
view = new ModelAndView("EmailCommunication");
view.addObject("isAdmin", isAdmin);
view.addObject("sMsg", sMsg.toString());
view.addObject("eMsg", eMsg.toString());
return view;
}
I am really beating my head for last 4 hrs..help needed .
thanks..
You need quotes around your data keys. Change emailSubject: emailSub,emailMsg : emailBody to "emailSubject" : emailSub, "emailMsg" : emailBody.
You're also missing a closing } at the very end of your submitHandler, could just be a paste error?
dont stringify the data
Change
data:JSON.stringify({emailSubject : emailSub,emailMsg : emailBody}),
to
data:{emailSubject : emailSub,emailMsg : emailBody},
i made the changes to my ajax call and the controller which now user #RequestBody and now it is working fine...
my ajax code:
submitHandler:function(form){
var jsonObj = getData();
if(confirm("You are about to send Email Communication, Are you sure..?")){
$.ajax({
type: "POST",
url: $("#applicationUrl").val() +"/web/utilities/sendEmailMessage",
dataType: 'json',
cache:false,
headers: {
'Content-Type': 'application/json'
},
data:JSON.stringify(jsonObj),
//data: ({emailInfo : JSON.stringify({emailSubject:emailSub,emailMsg:emailBody})}),
success:function(response)
{
response.html();
},
error: function(x, t, m) {
console.trace();
if (!(console == 'undefined')) {
console.log("ERROR: " + x + t
+ m);
}
}
});
}
return false;
}
function getData(){
var object ={
emailSubject : $("#emailSubTxtArea").val(),
emailMsg : $("#emailBodyTxtArea").val()
};
return object;
}
controller:
#RequestMapping(value="/sendEmailMessage",method=RequestMethod.POST)
public ModelAndView sendEmailCommunication(#RequestBody EmailReqInfo emailInfo){
ModelAndView view = null;
StringBuffer sMsg = new StringBuffer();
StringBuffer eMsg = new StringBuffer();
boolean isAdmin = false;
try{
String loggedInUser = request.getHeader("sm_user").trim();
isAdmin = getUserAdminRights(request);
String emailSubject = emailInfo.getEmailSubject();
String emailMsg = emailInfo.getEmailMsg();
--
----
domain:-
public class EmailReqInfo implements Serializable
{
private static final long serialVersionUID = 1L;
private String emailSubject;
private String emailMsg;
//getters and setters
}
I am making a email contact form with a ajax post on a umbraco site, I am halway thru it and was just testing the ajax part and I get a "Web Service method name is not valid" error when it runs.
I have a booking.cs in app_code, then booking.asmx in a webservice folder,
[WebService(Namespace = "http://localhost/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Booking : System.Web.Services.WebService
{
public string Email { get; set; }
[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public string SaveIt(string Email)
{
try
{
return "success";
}
catch (Exception er)
{
return "error";
}
}
}
javascript:
$("#email_popup_submit").click(function (e) {
$.ajax({
url: '/webservice/Booking.asmx/SaveIt',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: { 'Email': 'testemail' },
beforeSend: function () {
},
success: function (data) {
//console.log(data.d);
if (data.d == "success") {
e.preventDefault();
// console.log('SUCCESS!');
} else {
}
},
error: function (jqXhr, textStatus, errorThrown) {
console.log("Error '" + jqXhr.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
}
});
})
Uncomment following line from your service code to be enabled to call from javascript/ajax
[System.Web.Script.Services.ScriptService]
you could try to change data parameter to this:
data: '{ "Email":"testemail"}'
trying to retrieve data from data.d but not able to access data from data.d as it says data.d is undefined
this is my jquery function
$("body").on("click", "#aProfile", function () {
$("#divProfile").show();
$("#divChangePassword").hide();
$("#txtProfileUserName").val('<%=HttpContext.Current.Session["UserName"].ToString()%>').prop('disabled', true);
var UserName = $("#txtProfileUserName").val();
$.ajax({
type: "POST",
url: "StudentPanel.aspx/GetUserDetails",
data: JSON.stringify({ UserName: $('#txtProfileUserName').val() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
alert(data.d);
$('#txtProfileName').val(data.d.Name);
$('#txtProfileEmail').val(data.d.Email);
$('#txtProfileGender').val(data.d.Gender);
$('#txtProfileContact').val(data.d.Contact);
$('#txtProfileCountry').val(data.d.Country);
$('#txtProfileState').val(data.d.State);
$('#txtProfileCity').val(data.d.City);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
$('#txtProfileCountry').prop('visible', false);
$(".Profile").prop('disabled', true);
});
this is my c# function
[System.Web.Services.WebMethod]
public static User GetUserDetails(string UserName){
User u = new User();
string CS = ConfigurationManager.ConnectionStrings["BBCS"].ConnectionString;
using(SqlConnection con = new SqlConnection(CS)){
SqlCommand cmd = new SqlCommand("spGetSISUserByName",con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "#UserName",
Value = UserName
});
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
u.Name = dr["Name"].ToString();
u.UserName = UserName;
u.Email = dr["Email"].ToString();
u.Gender = dr["Gender"].ToString();
u.Contact = dr["Contact"].ToString();
u.Country = dr["Country"].ToString();
u.State = dr["State"].ToString();
u.City = dr["City"].ToString();
}
}
return u;
}
I want to assign value from data.d but it returns undefined data.d
Problem solved
Inside ~/App_Start/RouteConfig.cs I changd :
settings.AutoRedirectMode = RedirectMode.Permanent;
To:
settings.AutoRedirectMode = RedirectMode.Off;
or you can just comment the line and its done
Always getting the 'save error' message when I call the Ajax web method.But I can save the data to database.I couldn't find any errors.How can I get alert 'Saved' .
my web method is
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "paygrade.aspx/SavePayGrade",
data: JSON.stringify({ value: rec, arr: arr }),
success: function (msg) {
console.log(msg.d);
alert(msg.d);
},
error: function (msg) {
alert("Save error");
}
});
[WebMethod]
public static string SavePayGrade(string value, params string[] arr)
{
string res = "";
using (FlairEntities context = new FlairEntities())
{
tblPayGrade obj = new tblPayGrade();
obj.salaryGrade = arr[0];
obj.salary = arr[1];
obj.note = arr[2];
context.tblPayGrades.Add(obj);
context.SaveChanges();
res = "Saved";
}
return res;
}
try following
console.log(msg);
alert(msg);
As you are sending response in string( return res;), you cant use msg.d
You need to use only msg.