jQuery-ui Autocomplete not finding control on Master page - javascript

I'm struggling with the jQuery-UI Autocomplete on a master page.
I've loaded the jQuery.js and jQuery-ui.js in that order, in the head section of the master page.
What I need to do is very common, I'm sure, but perhaps the idea it's on a master page is getting in the way.
Here is <body> code that will fill the autocomplete input (id=autocomplete) with hard-coded values outside an ajax call.
I realize it's useless to call ajax for data and not use it, but I'll deal with that later...baby steps
<%-- Trying some autocomplete stuff --%>
<label for="autocomplete" style="color:yellow;">Language: </label>
<input id="autocomplete" />
<script type="text/javascript">
var wsUrl = '<%= ResolveUrl("http://localhost/CommonContent/CCWebService.asmx/HelloWorld") %>';
var fillMe = "[id$='autocomplete']";
$.ajax({
type: "POST",
url: wsUrl,
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function (dave) {
alert(dave);
//FillAutocomplete(fillMe);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("1!\n" + errorThrown + "\n" + jqXHR + "\n" + textStatus);
}
});
FillAutocomplete(fillMe);
function FillAutocomplete(id) {
autodata = ["c++-001", "java-002", "php-003", "coldfusion-004", "javascript-005", "asp-006", "ruby-007"];
alert(autodata);
//$("[id$='autocomplete']").autocomplete({
$(id).autocomplete({
source: autodata,
select: function (event, ui) {
var label = ui.item.label.split('-')[0];
alert(label);
var value = ui.item.value.split('-')[1];
alert(value);
//store in session
document.valueSelectedForAutocomplete = value
}
});
alert("Filled");
}
</script>
Again, this WORKS (but the data is hardcoded). I get the alerts in the following order: success from ajax, then the autodata, then the filled notice.
Additionally, it works if I use the fillMe variable set to "#autocomplete" or if I hard code it in the FillAutocomplete function.
Obviously, since it works, the input is able to have the autocomplete property.
Here's everywhere else where I tried that I simply get
Object doesn't support property or method 'autocomplete'
Putting the autocomplete code directly inside the success
Call the filling of the autocomplete INSIDE the success of the ajax call (uncomment //FillAutocomplete) (comment the other call)
Starting with $(function() {
$('#autocomplete).autcomplete({...
Using some form of <#='autocomplete.ClientID()'#>
I have a sneaking suspicion it's not finding the control, not really that the control doesn't have support it.
Any ideas?
UPDATE: More Information
I've added the screenshot below to show the error in its full glory. And sorry for repeating myself but I'm wondering if it's due to master page somehow, or somehow the jquery-ui is NOT loading before the call to the autocomplete method (since it's "object doesn't support....")
The Cause and Solution:
It seems that the Ajax call was trying to complete before the remote file jQuery-UI was loaded. As RAM suggested in the comments below, I downloaded all remote files and they're part of the project now. Now the scripts load in the correct order and the autocomplete method is available on the input. Thanks RAM.

Here is an example to how to use jquery autocomplete in asp.net
http://www.dotnetlearners.com/blogs/view/102/JQuery-ajax-autocomplete-extender-textbox-using-json-response-type.aspx

The Ajax call was trying to complete before the remote file jQuery-UI was loaded. As RAM suggested in the comments, I downloaded all remote files and they're part of the project. Now the scripts load in the correct order and the autocomplete method is available on the input.
Thanks RAM - that did it.

Related

Save HTML DOM to file on server

I have an html5 web page that allows users to drag-n-drop objects between divs. After a user has moved objects around, I would like to save the current DOM to a file on my web server.
I know I can get the current HTML DOM using javascript but of course, I cannot save to a file on my server using javascript. So I thought about passing the html to a PHP page to do the "save" function, but I cannot figure out how to get the html passed to a PHP page. I've tried sending it as an argument in the URL with URI encoding, but the PHP page is not properly getting the entire string from the URL.
Should this approach work? If so, what am I missing to get the html string passed correctly to a PHP page? Or should I be using some other method?
ajax is the way to go here. If you are not familiar with ajax, please google it and learn it well. Any modern web app needs to have ajax integration in some way.
Here is how you can use javascript to communicate with the server.
Please Note I'm using JQuery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".draggableDivs").mouseup(function(event){
var documentStructure = ''; // whatever js you use to get document structure
var d = {"document_structure": documentStructure};
$.ajax({
url: "test.php", //Your url both relative and fixed path will work
type: "POST", // you need post not get because you are sending a lot of data
data: d,
success: function(response) {
alert('saved');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
</script>
on the server you would then do your php and save the data.
After you are done you can just respond with a json object if needed, if not just exit
you can use the approach like
after the drag and drop with javascript, show a button to save the dom.
on click event on the button, take the current dom in a variable.
use ajax to transfer your current dom to a php file(ajax file).
in the ajax file , save it into database.

Updating webpage with real-time database value using AJAX+PHP response

I’m creating a Javascript game and I’m currently trying to write some code that will show the player’s “Gold Balance” in real time on a html webpage.
The Gold amount is contained in my SQL database, so I’m using setInterval with a Javascript function that contains an AJAX call which calls a PHP script that grabs the current balance amount for the player and sends it back as “response”.
I’m able to have this amount appear as a Javascript alert, however I need to have the response appear as text on the webpage inside a <div> instead.
This is my current code:
<script>
setInterval("checkGold()",5000);
function checkGold()
{
$.ajax({
url: 'scripts/checkGold.php',
data: "",
dataType: 'json',
success: function(response){
alert(response);
}});
};
</script>
I have this in my html source code, I would like to place the function in a separate file and call it from there, but when I tried this I wasn't able to send the response back to the html page correctly.
I was wondering if anyone knows how to have this response appear as text on the page inside <div> </div>?
Also, I was wondering if this method will really update the div in real time (ie, will it auto-refresh the div part of the webpage, showing an up to date value (every 5000 milliseconds)?
Thanks in advance!
Since you are using jQuery, you can use text() to alter the contents of an existing div (which id is "yourDiv"):
setInterval("checkGold()",5000);
function checkGold()
{
$.ajax({
url: 'scripts/checkGold.php',
data: "",
dataType: 'json',
success: function(response){
$('div#yourDiv').text(response);
}
});
};
You have two questions here, so I will try to address both
1) How to append to the DOM using jQuery, instead of an alert:
in the success callback function, instead of alerting the response, you can simply call
$('body').append("<div>"+response+"</div>")
2) "Real time" Gold Balance
You should use websockets. Racthet is a good websocket PHP library to help you with this: http://socketo.me/

jQuery.ajax({type:'POST' in grails

First of all thanks to you all for your valuable suggestion.I got stuck one problem that is in jQuery ajax call in grails remote function call on controller.
The plug-ins installed in my project are: jQueryUi - 1.10.3, jQuery - 1.11.0.
My controller this method:
def loadamount(){...}
And for ajax call method:
def ajaxCallBalance(long id){
def userBalances=loadamount(id)
def userBalance=userBalances[0] //it returns in array
return [usreBalance:userBalance]
}
These are nothing but my database call to load user amount in his a/c that should load on page load inside user profile html page. So for that i use this:
Point 677:
<g:if test="${session.LogedUser}">
<script>
${remoteFunction(
controller:'user',
action:'ajaxCallBalance',
update:[success:'uresult',failure:'uresult'],
id:session.LogedUser.id
)}
</script>
In HTML:
<li id="uresult"><!-- Want to see hare what result either value or error it returns --></li>
In firebug console I see get this error:
SyntaxError: syntax error
<script>
jQuery.ajax({
type:'POST',
url:'/...../..../ajaxCallBalance/10000000',
success:function(data,textStatus) {jQuery('#uresult').html(data);},
error:function(XMLHttpRequest,textStatus,errorThrown)
jQuery('#uresult').html(XMLHttpRequest.responseText);
}
});
</script>
[Note:This is generated by grails ajax plugin what i have wrote is see point 677.]
Here is my Question:
Why is this $#39; appearing even though I have no space, nor any symbol. Is it a bug or my mistake?
Is there any way to handle this kind of scenario as user onLoad/(document).ready() call for such conditions. If Yes, then what I will do?
You can't just use the grails construct of ${remoteFunction...} in js directly. use ajax:
$.ajax({
type: 'POST',
url: "${createLink(action:'ajaxCallBalance', controller:'user')}",
data: { id: id },
success: function (dataCheck) {
//Do stuff
}
........
});
or use g:remoteFunction like this way
$('mydiv').onclick = <g:remoteFunction action="ajaxCallBalance" controller="user" id="${id}" />

Codeigniter with AJAX dropdown menus not working after form_validation fails and redirects/re-loads view

Once the validation runs, fails, and proceeds to redirect to the same controller index.
if (!$this->form_validation->run())
{
$this->index();
}
The form is a simple, two dropdowns, one dependent on the other, once the view is reloaded though, the second dependent dropdown stops working.
Here is the JS
$(document).ready(function()
{
$('#manufacturer_dropdown').change(function()
{
$("#sw_names > option").remove();
var id = $('#manufacturer_dropdown').val();
$.ajax({
type: "POST",
url: "software/get_software_names/"+id,
datatype : "JSON",
success: function(sw_names)
{
$.each(sw_names,function(id,software_name)
{
var opt = $('<option />');
opt.val(software_name);
opt.text(software_name);
$('#sw_names').append(opt);
});
}
});
});
});
If I manually refresh the page, the dropdowns work again. Not sure what is happening, maybe the document ready function stops checking or something. I'm no JS expert...
I can post more of the code if needed.
Edit: My JS URL was missing a /
Works now
If you are making an ajax request, you must give an ajax response
You cannot redirect the page in the middle of a request like that.
I've written something up going through all of this type of problem, as it's such a common one. Hopefully this will steer you along: http://codebyjeff.com/blog/2013/04/how-do-i-use-ajax-with-framework-x

how to use JSON for an error class

Hey all. I was fortunate enough to have Paolo help me with a piece of jquery code that would show the end user an error message if data was saved or not saved to a database. I am looking at the code and my imagination is running wild because I am wondering if I could use just that one piece of code and import the selector type into it and then include that whole json script into my document. This would save me from having to include the json script into 10 different documents. Hope I'm making sense here.
$('#add_customer_form').submit(function() { // handle form submit
The "add_customer_form" id is what I would like to change on a per page basis. If I could successfully do this, then I could make a class of some sort that would just use the rest of this json script and include it where I needed it. I'm sure someone has already thought of this so I was wondering if someone could give me some pointers.
Thanks!
Well, I hit a wall so to speak. The code below is the code that is already in my form. It is using a datastring datatype but I need json. What should I do? I want to replace the stupid alert box with the nice 100% wide green div where my server says all is ok.
$.ajax({
type: "POST",
url: "body.php?action=admCustomer",
data: dataString,
success: function(){
$('#contact input[type=text]').val('');
alert( "Success! Data Saved");
}
});
Here is the code I used in the last question, minus the comments:
$(function() {
$('#add_customer_form').submit(function() {
var data = $(this).serialize();
var url = $(this).attr('action');
var method = $(this).attr('method');
$.ajax({
url: url,
type: method,
data: data,
dataType: 'json',
success: function(data) {
var $div = $('<div>').attr('id', 'message').html(data.message);
if(data.success == 0) {
$div.addClass('error');
} else {
$div.addClass('success');
}
$('body').append($div);
}
});
return false;
});
});
If I am right, what you are essentially asking is how you can make this piece of code work for multiple forms without having to edit the selector. This is very easy. As long as you have the above code included in every page with a form, you can change the $('#add_customer_form') part to something like $('form.json_response'). With this selector we are basically telling jQuery "any form with a class of json_response should be handled through this submit function" - The specific class I'm using is not relevant here, the point is you use a class and give it to all the forms that should have the functionality. Remember, jQuery works on sets of objects. The way I originally had it the set happened to be 1 element, but every jQuery function is meant to act upon as many elements as it matches. This way, whenever you create a form you want to handle through AJAX (and you know the server will return a JSON response with a success indicator), you can simply add whatever class you choose and the jQuery code will take over and handle it for you.
There is also a cleaner plugin that sort of does this, but the above is fine too.
Based on your question, I think what you want is a jQuery selector that will select the right form on each of your pages. If you gave them all a consistent class you could use the same code on each page:
HTML
<form id="some_form_name" class="AJAX_form"> ... </form>
Selector:
$('form.AJAX_form")

Categories