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")
Related
I have an issue which I don't quite know how to approach.
I need to extend the Sitecore Insert link functionality: when I insert a link to a Sitecore Item, a certain icon, based on some logic (I've already created the logic for another user story(*)), needs to appear in the front of the link after "Insert" button is pressed, and of course, finally on the UI.
I was thinking on the following approach: after the item is inserted, the item's ID is sent to the backend via an Ajax call and the response is a mark-up with the values returned by the service I told you above at (*).
The issue is that I don't know where to start on or if my idea is ok.
Any help is welcome.
I found the answer:
In the RichText Commands.js file, I have added the following script which sends the item Sitecore ID to the API:
function scInsertSitecoreLink(sender, returnValue) {
if (!returnValue) {
return;
}
var url = returnValue.url;
var itemId = url.substring(url.indexOf("=") + 1, url.lastIndexOf("&"));
var $ = jQuery.noConflict();
$.ajax({
async: true,
type: "GET",
url: '/sitecore/api/Test/ThisIsTheTestApiCall',
data: JSON.stringify(itemId),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result);
}
});
[...]
}
First I have added var $ = jQuery.noConflict(); before the ajax call;
More info here: https://api.jquery.com/jquery.noconflict/
Then I've checked if there are any changes over the routes: RegisterHttpRoutes;
Profit.
You might be better to modify the renderField pipeline, because if you ever need to change these icons later, you're going to have to process every single link on your site.
To do that, you'll want to create a processor and have it run before Sitecore.Pipelines.RenderField.ExpandLinks, Sitecore.Kernel in the renderField pipeline so that you can use the dynamic links (which contain IDs) to figure out what icons you need. From there you can use HtmlAgilityPack.HtmlDocument to find and update the markup when the link is rendered.
Due to the nature of my current project, I often find myself having to create HTML <form> elements which must support dynamic add/remove functionality of items for posting collections to the server.
My issue is that I find myself constrained by the name attribute of the form elements because I have to keep track of indices, ex.: Room[1].Tourists[0].Name. This is giving me hard times when I would like, for example, to remove an existing input element from the beginning.
I am currently building these dynamic forms with react.js which is enabling great flexibility, but I was wondering if there was some way that I could collect form data on submit event and just serialize it to match the expected model in the controller's action and post it?
Okay so you just want to solution about this i think you were stuck somewhere in your code that's why i am asking about the sample code no worry back to this try this:
<script type="text/javascript">
$(document).ready(function () {
$("#btn_submit").on('click', function () {
$.ajax({
type: "POST",
url: "Give URL here",
async: false,
data: $("#FormID").serialize(),
success: function (result) {
//Do what you want
},
error: function (response) {
//Do what you want
}
});
});
});
</script>
I've seen several questions here with the similar subject but I can't find anything which is relevant to my situation. I am trying to build jQuery code that is able to build a list of items to save it in an inventory database and I am using .post() those to a additems.php that will add them to that database (after sensitization), as well as the current path name so the .php can send the user back to the same page.
The behavior I am getting is nothing whatsoever with no console error (except the 'this works' alert when I leave that in.) The behavior I am looking for is, the page should redirect to additems.php as an html form action would, execute the code there and redirect back to this page.
Here is my piece of code:
$(document).ready(function(){
$("#button").click(function(){
alert("this works");
var itemsarray = ['itemname'];
var itemattributesarray = ['itemattribute'];
var quantitiesarray = ['1'];
$.post('additems.php', {
items:{items: itemsarray},
itemattributes:{itemattributes: itemattributesarray},
quantities:{quantities: quantitiesarray},
returnpath: window.pathname
});
});
});
Thank you for your time and any suggestions. I've never used this site so please let me know how I can improve my question as well, if you have the time.
An alternative way is,
$.ajax({
'url':'additems.php',
'method' : 'POST',
'data':{
'items':itemsarray,
'itemattributes':itemattributesarray,
'quantities' : quantitiesarray
},
success: function(data){
//here you will get ajax response
console.log(data);
}
});
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
I need to fire asp.net (link button or Button) click event(server side code) using Jquery, the buttons are in an update panel. Kindly help.
Michael's solution is good.
But I think it is safer to call GetPostBackEventReference.
The internal structure of ASP.NET Page may be changed in the future.
Here's the sample Code.
<%= Page.ClientScript.GetPostBackEventReference(lnkButton, "") %>
How about:
__doPostBack("<%= lnkMyButton.UniqueID %>", "");
What you need to do is to define your server side code as [WebMethod] once you do that your classname will be available to client side code for calling.
Then you would go about calling that method using something like this:
jQuery.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{}',
dataType: 'json',
url: 'MyPage.aspx/SomePageMethod',
success: function(result){
alert(result);
}
});
I am more of a C# person, but I would imagine if you read this page you are easily able to make it in VB: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Below is how I triggered a click event with a LinkButton within an Update Panel. I couldn't get the ID until run time due to the way I was creating buttons, that is, it kept appending a _0, _1, etc to the end of the button name. For example on the server I would create 2 buttons with ID's say of 111555 & 222666. It would rename the buttons with ID's like:
contentMain_gridviewMessages_111555_0
contentMain_gridviewMessages_222666_1
So the first thing I did was create a unique attribute I could search upon, in my case the message id:
var msgLink = ('a[messageId="' + messageId + '"]');
After that I used a little bit of jQuery to get the auto generated ID:
var id = $(msgLink).attr("ID");
When I got the ID good ole fashion javascript did the rest:
document.getElementById(id).click();
Hope this helps someone out.