How I write data in span when i am using jQuery EasyUI - java

I am using AJAX for data communication from server but in case of success i want to write the data into span(id=cartcount) but it's not worked please help how i achieve this concept
function addToCart(pid, name) {
if (confirm("Are you sure to add "+name + " to cart?")) {
$.ajax({
type: 'POST',
url: 'addcart',
data: {
pid: pid
},
success: function(obj) {
$('#cartcount').val(obj);
}
});
}
}

try:
$('#cartcount').html(obj);
or
$('#cartcount').text(obj);

Related

Partial not found when attempting to render it from an Ajax call in Rails app

Rails 5.2.3
I have the following Ajax call:
function renderSalesDayDashboard(date_target) {
$.ajax({
type: "POST",
url: "sales_day_dashboard",
data: JSON.stringify({
"date_target": date_target
dataType: 'json',
contentType: "application/json; charset=utf-8",
remote: false,
success: function(day_results) {
try{
$("#dayDashboard").html("<%= escape_javascript(render partial: 'sales/show/day_dashboard', locals: { day_results: #day_results } ) %>");
}catch(e){
alert(e)
}
}
});
}
I verified that it's working, and that the #day_results variable is created at the controller.
I also verified that the partial:
sales/show/_day_dashboard.html.slim
exits, and I know it does, because this Ajax function re-renders it, but it initially renders as part of the sales/show.html.slim view.
I am, however, getting the error message:
Missing partial sales/show/_day_dashboard with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :slim, :coffee, :jbuilder]}
Any ideas?
Edit:
Here's what sales/show/_day_dashboard.html.slim looks like for now:
#dayDashboard
.panel.panel-default
.panel-title
= day_results.day
Here's the entire error message:
Showing ...../app/views/sales/show/_period_sales.html.erb where line #58 raised:
Missing partial sales/show/_day_dashboard.html with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :slim, :coffee, :jbuilder]}. Searched in:
* "..../app/views"
* "/Users/xxxx/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/devise-4.7.1/app/views"
* "/Users/xxxx/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/kaminari-core-1.1.1/app/views"
Line 58 is:
$("#dayDashboard").html("<%= escape_javascript(render partial: 'sales/show/day_dashboard', locals: { day_results: #day_results } ) %>");

Add compiler to java pages

i would like to add a compiler to my jsp pages where the user can enter his code and compile it. Any idea whats the method to add a compiler to jsp pages?
Heh. I tried to put in where I got this approach from, but the spam filter prevented it. I can't vouch for whether the urls below are open for anyone to use, but this is one way to do it:
function submitForm(){
jQuery.support.cors = true;
$('#wait').show();
if ($.browser.webkit || $.browser.mozilla) {
var url = "http://www.compileonline.com/compile_new.php";
}else{
var url = "col_proxy.php";
}
$.ajax({
type: "POST",
cache: false,
crossDomain: true,
url: url,
target: "view",
data: $("#ff").serialize(),
success:function(data)
{
$('#view').contents().find("html").html(data);
$('#wait').hide();
return false;
},
error:function (data, status, error) {
alert(error);
return false;
}
});
return false; // avoid to execute the actual submit of the form.
}

Use ajax success return formatted data to populate easyUI form

I am trying to use backend returned data to populate textboxes in the form. If I replace the "result" var with full raw
data(eg.{
name:'myname',
email:'mymail#gmail.com',
subject:'subject',
message:'message',
language:'en'
}
it works... So it make wonder whether the returned data is not formatted properly or what?
$.ajax({
type: "post",
cache: false,
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
url: "<%=path%>/storeRace",
data:{
type:'query', venue:'<%=race.getVenue()%>', date:'<%=race.getDate().toString()%>', race_num:'<%=race.getRaceNum()%>'
},
success:function(result){
if(result=="none"){
}
else{
alert(result);
$('#raceForm').form('clear');
$('#raceForm').form('load', result);
}
},
error:function(result){
$.messager.alert('Error',result,'error');
}
});

ajax success function is printing [object Object] instead of plain text. Why?

jQuery code:
function ajaxsubmit(){
$.ajax({
url: "/update",
type: "POST",
dataType: "html"
}).success(function(data) {
$('#result').html(data);
});
}
and my Java function:
public static Result ajaxupdate() {
String done = "very good";
return ok("very good").as("text/plain");
}
the alert is giving [object Object], instead of plain text "very good". why?
you want to use:
alert(JSON.stringify(data));
so you JavaScript will look like:
function ajaxsubmit(){
$.ajax({
url: "/update",
type: "POST",
}).complete(function(data) {
alert(JSON.stringify(data));
});
}
Your Java code looks like it is wrapping your string into an object before it sends it back to the client, JSON.stringify() will show you the structure of the object that is being returned and from there you can work out what property of the returned object contains your return variable (Probably something like data.data or data.return)
add dataType: "text" and change complete() with success()
function ajaxsubmit(){
$.ajax({
url: "/update",
type: "POST",
dataType: "html"
}).success(function(data) {
$('#result').html(data);
});
}
The jQuery documentation clearly answers your question. From http://api.jquery.com/jQuery.ajax/
complete(jqXHR, textStatus)
<...>
two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string
You can find more about jqXHR in documentation.
If you want to use the response string, consider opting for .success method. You may have to explicitly provide .contentType

JavaScript - how to display error message from backend system based on Spring MVC

I have a web application with HTML / jQuery which ic connected with AJAX / JSON to a backend system with Java EE / Spring MVC.
In the frontend, a Person can be created by fill in the form fields and then it is submitted and this jQuery code executed:
var person = $(this).serializeObject();
$.postJSON("add/", person, function(data) {
alert("Person with ID "+data.person.id+"' added successfully");
});
In the best case, the Person is created and I'll get a Person object and I can access the values with data.person.*.
Now I want to validate the data which is sent to the backend system and in a case of an error, I want to display in the first step an alert error message.
I did this in the backend system:
#RequestMapping(value="add/", method=RequestMethod.POST)
public #ResponseBody Map<String, ? extends Object> addPerson(#RequestBody Person p, HttpServletResponse response) {
Set<ConstraintViolation<Person>> failures = validator.validate(p);
if (!failures.isEmpty()) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return validationMessages(failures);
} else {
Person person = this.personService.addPerson(p);
return Collections.singletonMap("person", new SerialPerson(person.getId(), person.getName(), ...));
}
}
// internal helpers
private Map<String, String> validationMessages(Set<ConstraintViolation<Person>> failures) {
Map<String, String> failureMessages = new HashMap<String, String>();
for (ConstraintViolation<Person> failure : failures) {
failureMessages.put(failure.getPropertyPath().toString(), failure.getMessage());
System.out.println(failure.getPropertyPath().toString()+" - "+failure.getMessage());
}
return failureMessages;
}
My Person object is annotated, and I get the System.out.println(failure.getPropertyPath().toString()+" - "+failure.getMessage()); on the console, that for example, "name - must be between 1-30 chars"
But how can create an alert message in jQuery in the frontend system?
Thank you in advance for your help & Best Regards.
Update: Link to the Spring MVC AJAX example, where I found the validationMessages method. But there is also no solution how to get the error message.
SOLUTION:
I have to call:
jQuery.ajax({
'type': 'POST',
'url': "add/",
'contentType': 'application/json',
'data': JSON.stringify(person),
'dataType': 'json',
'success': function(data) {alert("success");},
'error': function(xhr) {alert(xhr.responseText);}
});
You can do something like this:
var person = $(this).serializeObject();
$.postJSON("add/", person, function(data) {
if(data.person) {
alert("Person with ID "+data.person.id+"' added successfully");
}
else {
var errors = "";
for(var key in data) if(data.hasOwnProperty(key)) {
errors += data[key] + "\n";
}
alert(errors);
}
});
You shouldn't need to send back a bad request either. Is this what you want?
UPDATE
You can use the code shown in Spring Source, but you'd have to use jQuery.ajax
jQuery.ajax({
type: 'POST',
url: "add/",
data: person,
dataType: "json",
success: function(data) {
alert("Person with ID "+data.person.id+"' added successfully");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
var errorJSON = JSON.parse(XMLHttpRequest.responseText); //if this is JSON otherwise just alerting XMLHttpRequest.responseText will do
var errors = "";
for(var key in errorJSON) if(errorJSON.hasOwnProperty(key)) {
errors += errorJSON[key] + "\n";
}
alert(errors);
}
});

Categories