I have a date field. It is necessary that when choosing a date under this field, the div is displayed using Javascript, this is the date.
Send the goal using javascript to the controller.
I need this code as a basis for other purposes. Help if you can
View
<input type="date" class="form-control ium_textbox" name="date_sched" value="" id="date_a" required>
Javascript
<script type="text/javascript">
$(document).ready(function() {
$('#date_a').change(function () {
var time = $(".ium_textbox").val();
$.ajax({
url:<?= base_url() ?>"application/controllers/frontend/get_datetime",
type: 'POST',
data: {date: time},
success: (function (data) {
$("#date_field").html(data);
})
});
});
});
Controller
public function get_datetime()
{
$this->load->view('frontend/get_datetime');
}
get_datetime.php
<? echo $_POST['date'] ?>
The URL you are calling should be in the same form as if you were calling it directly via the web browser.
A Side NOTE: You can prevent direct access if you only want it accessed via an AJAX call and not directly from the browser by using $this->load->is_ajax_request(). Something you may want to look up
So, if the controller is called Frontend and the method is get_datetime, then your AJAX Url should be
// Line to change in AJAX Call
url:<?= base_url() ?>"frontend/get_datetime",
Make sure you have configured base_url correctly.
I.E under /application/config/config.php ensure
$config['base_url'] = 'http://your_domain_name.com/';
Changing http://your_domain_name.com/ to suit your actual domain name.
Note: The trailing / on the URL.
For extra debug you can add in some console.log(); into your javascript and view the results in your Browsers Dev Tools - Console Tab.
I.E if you want to make sure that time is being set correctly you can...
<script type="text/javascript">
$(document).ready(function() {
$('#date_a').change(function () {
var time = $(".ium_textbox").val();
// Added Debug
console.log('The Time is : ' + time);
$.ajax({
url:<?= base_url() ?>"frontend/get_datetime",
type: 'POST',
data: {date: time},
success: (function (data) {
$("#date_field").html(data);
})
});
});
});
So I hope that helps.
It's important to learn how to debug your code to see what it's actually doing. So that's a start.
I am in a spot here trying to parse BBCode upon a AJAX success : item.message object. I am using jQuery 1.11. I have tried passing the var result in place of item.message, and only shows the [object] errors. I have tried wrapping item.message with XBBCODE and same thing.
Im not sure what to do, the script is great otherwise. We must parse bbcode to HTML or a method that can be managed PHP-side, but I don't think this is possible over JSON data.
Currently this is my jQuery code:
$(document).ready(function () {
$.ajax({
url: "/ajax/shoutbox.php",
method: "GET",
dataType: 'JSON',
success: function (data) {
var html_to_append = '';
$.each(data, function (i, item) {
// Object array repeated - not working
var result = XBBCODE.process({
text: 'item.message',
removeMisalignedTags: false,
addInLineBreaks: false
});
/*
currentPost = jQuery(this);
postHTML = bbcodeToHTML(currentPost.html());
currentPost.html(postHTML);
*/
html_to_append +=
'<div class="shoutbox-container"><span class="shoutDate">' +
jQuery.timeago(item.date) +
' <span style="color:#b3b3b3">ago</span></span><span class="shoutUser"><img src="' +
item.avatar +
'" class="shout-avatar" /></span><span class="shoutText">' +
item.message +
'</span></div><br>';
});
$("#shoutbox").html(html_to_append);
$(".shoutbox-container").filter(function () {
return $(this).children().length == 3;
}).filter(':odd').addClass('shoutbox_alt');
$(".shoutbox-container").each(function () {
$(this).parent().nextAll().slice(0, this.rowSpan - 1).addClass('shoutbox_alt');
});
}
});
});
As you see, I'm trying to make use of the following javascript:
https://github.com/patorjk/Extendible-BBCode-Parser
I've followed the instructions exactly, before moving into the JS above with no success either way. I get this:
[object][Object]
For each iteration of the message object coming back (its a custom AJAX shoutbox).
Commented, you can see another method I have tried to no success. Any help is appreciated!
Update: Working
Thank you, Quiet Nguyen for the suggestion for replacing item.message with result.html and updating text: object
I want to implement some functionality which is when I enter some text in
<input path="tags" id="input-search"/>
there should appear a list of suggested tags just like
after making ajax call. I have database query
public interface TagRepository extends JpaRepository<Tag, Integer> {
#Query("SELECT t FROM Tag t WHERE name LIKE CONCAT('%', :name, '%')")
List<Tag> findTagByName(#Param("name") String name);
}
and the controller code is
#RequestMapping(value = "/getTags", method = RequestMethod.POST, produces = "application/json")
public #ResponseBody List<Tag> getTags(#RequestBody Tag tag, HttpServletResponse response) {
System.out.println("Found " + String.valueOf(tagService.findTagByName(tag.getName()).size()));
return tagService.findTagByName(tag.getName());
}
javascript for ajax is
$(document).ready(function() {
$("#tag-search").autocomplete({
source: function(request, response) {
$.ajax({
url: "/app/getTags/",
type: "POST",
data: JSON.stringify({tag : request.term}),
dataType: "json",
success: function(data) {
response($.map(data, function(v,i){
console.log();
return {
label: v.empName,
value: v.empName
};
}));
}
});
}
});
});
<div class="col-md-10 col-md-push-1">
<label class="floating-label" for="login-username">Tags</label>
<form:input path="tags" cssClass="form-control" id="tag-search"/>
</div>
when I run the app I see this javaScript error in Developers Tools
Important
I'm using Daemonite/material for my front-end & jQuery-Autocomplete, finally a good thing is that the latest version of App is on GitHub
can any one tell me how can I get rid of that error any response is welcome.
for the problem above i mostly use select2 jquery plugin. it's has a lot of build in feature, so no need of reinventing the wheel. check this link out for a demo - http://select2.github.io/select2/#infinite
screen shot:
code sample:
$("#e7").select2({
placeholder: "Search for a repository",
minimumInputLength: 3,
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
quietMillis: 250,
data: function (term, page) { // page is the one-based page number tracked by Select2
return {
q: term, //search term
page: page // page number
};
},
results: function (data, page) {
var more = (page * 30) < data.total_count; // whether or not there are more results available
// notice we return the value of more so Select2 knows if more results can be loaded
return { results: data.items, more: more };
}
},
formatResult: repoFormatResult, // omitted for brevity, see the source of this page
formatSelection: repoFormatSelection, // omitted for brevity, see the source of this page
dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
});
now layout is not exactly same as screenshot you provided, but check if this layout work for you.
Update:
function repoFormatResult(repo) {
var markup = '<div class="row-fluid">' +
'<div class="span2"><img src="' + repo.owner.avatar_url + '" /></div>' +
'<div class="span10">' +
'<div class="row-fluid">' +
'<div class="span6">' + repo.full_name + '</div>' +
'<div class="span3"><i class="fa fa-code-fork"></i> ' + repo.forks_count + '</div>' +
'<div class="span3"><i class="fa fa-star"></i> ' + repo.stargazers_count + '</div>' +
'</div>';
if (repo.description) {
markup += '<div>' + repo.description + '</div>';
}
markup += '</div></div>';
return markup;
}
function repoFormatSelection(repo) {
return repo.full_name;
}
Another approach:
Hi if above solution not fit for your problem then you can use this one instead. it's called typeahead.js a JavaScript library provide by twitter. you can find examples here.
Check jquery vendor library is loaded properly or not.
To cross check:
<script>
if (window.jQuery) {
alert('jQuery is loaded');
} else {
alert('jQuery is not loaded');
}
</script>
It simply means that you are getting HTML instead of JSON in response.
"Unexpected <" is referring to the first character of your request's response.
in chrome console you can go to network tab and click on your request and in the right side see what exactly your server is returning back to client.
You missed jquery.js. Add it and you'll get it working.
I am adding the codes here so that it would be better readable;
Write a new method to parse json on Java side before returning to jquery. Current code returns Java list as output for Ajax and this would possibly throw Uncaught syntax error : Unexpected token.
public static String toJSON(Object object)
{
if ( object == null ){
return "{}";
}
try {
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(object);
}
catch (Exception e) {
e.printStackTrace();
}
return "{}";
}
for the above piece of code you need to include 3 jars jackson-core-2.2.3.jar, jackson-annotations-2.2.3.jar and jackson-databind-2.2.3.jar.
Change you controller as following;
#RequestMapping(value = "/getTags", method = RequestMethod.POST, produces = "application/json")
public #ResponseBody String getTags(#RequestBody Tag tag, HttpServletResponse response) {
System.out.println("Found " + String.valueOf(tagService.findTagByName(tag.getName()).size()));
return toJSON(tagService.findTagByName(tag.getName()));
}
$(document).ready(function() {
var autoCompleteResult = '';
$("#tag-search").autocomplete({
source: function(request, response) {
$.ajax({
url: "/app/getTags/",
type: "POST",
data: JSON.stringify({tag : request.term}),
dataType: "json",
success: function(data) {
autoCompleteResult = jQuery.parseJSON(data);
response($.map(autoCompleteResult, function(v,i){
console.log();
return {
label: v.empName,
value: v.empName
};
}));
}
});
}
});
});
Please share your results after trying this.
Try this:
https://github.com/tanwaniniranjan/autosuggest
It's a plugin made for the same purpose. very less documentation, but i hope to put up the documentation soon.
Yu can read the comments in the js file to get an idea on the usage
Edit:
I now read your question more carefully,
what is happening is:
the response that you are getting from the server side is giving an error.
the error will usually start like sorry bro, 404
since you are trying to map the data, jQuery just cant parse it, and it gives you the error.
check your server side first. use the postman plugin to make requests, verify your response and then implement jQuery: https://chrome.google.com/webstore/detail/postman-launcher/igofndmniooofoabmmpfonmdnhgchoka?hl=en
As i see there could be a issue of 500 internal server error because you have a dataType: "json", in your ajax while at your controller you aren't returning any json.
#RequestMapping(value = "/getTags", method = RequestMethod.POST, produces = "application/json")
public #ResponseBody List<Tag> getTags(#RequestBody Tag tag, HttpServletResponse response) {
System.out.println("Found " + String.valueOf(tagService.findTagByName(tag.getName()).size()));
return tagService.findTagByName(tag.getName());
}
Here at your conroller this: produces = "application/json" says it will return json as output and with this: return tagService.findTagByName(tag.getName()); you can producing any json.
Just add below tag to your ajax call
contentType: 'application/json; charset=utf-8',
This is the type for requested data,in your case it simply text format that you type in text box
And remove below line from your ajax call if your response data is not json type
dataType: 'json',
This may remove Json Parsing Error in your code
Change your JavaScript as the below
$(document).ready(function() {
$("#tag-search").autocomplete({
source: function(request, response) {
$.ajax({
contentType: 'application/json; charset=utf-8',
url: "/app/getTags/",
type: "POST",
data: JSON.stringify({'tag' : "'"+request.term+"'"}),
dataType: "json",
success: function(data) {
response($.map(data, function(v,i){
console.log();
return {
label: v.empName,
value: v.empName
};
}));
}
});
}
});
});
I added a recaptcha script on my Netsuite external form and it works on every browser except for Safari (using 5.1.7).
It gives this error:
"onSubmit (saveRecord) customform JS_EXCEPTION ReferenceError Can't find variable: onSubmit"
The code I'm using is below and the Safari error console doesn't give me anything. Any ideas?
function onSubmit() {
var captchaChallenge = $('#recaptcha_challenge_field').val();
var captchaResponse = $('#recaptcha_response_field').val();
var isToBeSubmitted = true;
$.ajax({
url: CAPTCHA_VERIFICATION_SUITELET_URL + '&challenge=' + captchaChallenge + '&response=' + captchaResponse,
type: 'POST',
accepts: 'application/json',
dataType: 'json',
cache: false,
async: false
}).done(function (data) {
if (!data.status.isSuccess) {
alert('Captcha Verification Failed.');
Recaptcha.reload();
isToBeSubmitted = false;
}
});
return isToBeSubmitted;
}
Images of script setup
Can you try to change the function to another name not so generic like
function onCustomerSubmit
Finally figured out the issue. When I attach a script to the online customer form, I needed to make sure the checkbox "Available Without Login" is checked. Never saw it before, but I checked it and it solved the issue with Safari. Attached a picture for reference.
I am trying to figure out how to fix a problem with a plugin called "REdmine Hooks Manager" that I have just added to my Redmine installation.
Whenever I attempt to click on one of the buttons to configure the plugin Chrome Developer Tools reports:
Uncaught ReferenceError: get is not defined
The HTML that is generating the exception looks like this:
<li>By location</li>'
and
<input id="show_all" name="show_all" onchange="$.ajax({url:'/hooks/tree', async:true, data:'hook=' + selected_hook + '&by=' + structured_by + '&all=' + ($('show_all').checked ? 1 : 0), type:get})" type="checkbox" value="1" />'
and
<a id="view_layouts_base_content" href="#" onclick="if ((html_code_changed == false) || confirm('HTML code has not been saved and going to be lost if you continue... Are you sure?')) { $.ajax({url:'/hooks/load?hook=view_layouts_base_content', async:true, type:get}).done(function() {updateSelectedHook('view_layouts_base_content')}); }" class="icon icon-file text-plain selected"> Content (bottom)</a>'
etc...
and I have located this javascript (that is being loaded) that seems to be related:
function updateSelectedHook(hook) {
var previousItem = $('#'+selected_hook);
if (previousItem) {
previousItem.removeClass('selected');
}
selected_hook = hook;
var nextItem = $('#'+selected_hook);
if (nextItem) {
nextItem.addClass('selected');
}
html_code_changed = false;
}
function updateHookPreview() {
$('#preview-content').html($('#html_code').val());
$('#preview').show();
}
function updateHooksTree(url, mode) {
$.ajax({
url: url,
type: 'get',
data: 'hook=' + selected_hook + '&by=' + mode + '&all=' + ($('#show_all').is(':checked') ? 1 : 0),
success: function(data) { structured_by = mode; }
});
}
function updateHookForm(url, hook, msg) {
if ((html_code_changed == false) || confirm(msg)) {
$.ajax({
url: url,
type: 'get',
success: function(data) { updateSelectedHook(hook); }
});
}
}
The plugin works on a clean installation so I strongly suspect that it is a compatibility problem between 2 plugins. After quite a bit of digging I have discovered that there seem to be 3 copies of jQuery being loaded. Version 1.8.3, 1.7.1 and 1.7.3 so this may be causing the problem.
I've also tried to break into the updateSelectedHook function using the Chrome script debugger but it's not being called. Perhaps because the $.ajax call itself is failing.
So... best guess right now is that a newer version of jQuery has changed the way that the ajax call is being made but I've run out of ideas regarding how to test further and hoped that someone here might be able to assist. Any ideas?
Thanks in advance.