jQuery AJAX call from multiple input fields within the 1 script - javascript

I'm working on my first HTML form that performs an AJAX HTTP POST using jQuery. When a user makes a change to an input text field and tabs out of the field it triggers the AJAX script which in turn calls a PHP script which performs a database update.
I've got this working successfully for my first input field - I would now like to extend this to a 2nd, 3rd etc input fields but want to try and avoid having multiple scripts that perform very similar functions. I'm new to jQuery and AJAX so learning the syntax as I go.
Here's my input fields:
Manager
Phone
Here's my Javascript that is working on the storeManager input field:
<script type="text/javascript">
$(document).ready(function() {
$("#storeManager").change(function(){
var storeManager = $("#storeManager").val();
$.post('editProject.php', { storeManager: storeManager, id: '1E1DDA14-D2C6-4FC8-BA5F-DBCCC7ABAF7F' }, function(data) {
$("#managerRow").addClass("success");
}).fail(function () {
// no data available in this context
$("#managerRow").addClass("danger");
$("#ajaxAlert").addClass("alert alert-danger");
});
});
});
</script>
I essentially need to branch and pass an additional POST parameter to the editProject.php script so it knows which database field to update, and then conditionally add a class to the appropriate row.
Everything I've tried breaks the script when I try and get it to branch or pass a parameter based on the input field that is being edited. I haven't been able to find any examples that show the correct syntax to have the one script that is called by different input fields - I'm presuming this is possible instead of having multiple versions of the same script acting on different fields.

This works for multiple fields. Just call the same function from different input fields. I just broke your code into two parts.
1. onChange function of each individual field, and
2. function call by passing the field parameters.
<script type="text/javascript">
$(document).ready(function() {
$("#storeManager").change(function(){ yourFunction(this) }):
$("#worker").change(function(){ yourFunction(this) }):
$("#someX").change(function(){ yourFunction(this) }):
yourFunction(field)
{
var value = $(field).val();
var inputId=field.id;
$.post('editProject.php', { inputValue: value, id: inputId }, function(data) {
$('#'+inputId+'Row').addClass("success"); // (this looks like: *#storeManagerRow* ) you can change your Row id's accordingly to make your work easier. Eg: for **#storeManager** make this id as **storeManagerRow**
}).fail(function () {
// no data available in this context
$('#'+inputId+'Row').addClass("danger");
$("#ajaxAlert").addClass("alert alert-danger");
});
});
</script>

You just try to post a value. for example type. Which should contain some value for identify the ajax call.
If it is for login, then add type = 'login'. Then check the value of $_POST['type'] and write php according to it
sample.php
if(isset($_POST['type']))
{
if($_POST['type'] == 'login')
{
//your code goes here
}
}

you can use this kind of code :
$("#storeManager, #Manager, #Phone").change(function(){

You could do something like this using :input or a class that they all have
$(":input").on("change", function(){
var text = $(this).val();
var idOfInput = $(this).attr("id");
//your post to php function using the above variables
});
From this you could post the id of the input to your php script using the idOfInput variable which you could then on the php side use a case switch to do a different query depending on which id is sent to the php
Here is a jsfiddle showing how it works

Related

adding a class after email is validated using jquery

I'm trying to use jQuery for email validation in a form field
$(document).ready(function() {
var email = new RegExp("[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$");
var value = $("#email_address").val();
$("#email_address").on("keypress", function() {
if(email.test(value)) {
$("#email_address").parent().addClass("has-success");
}
});
});
However, the has-success class doesn't get added. I've tried each line of code individually in the console and they all seem to be doing/pointing to the right thing. It's when it's all put together that it doesn't seem to work.
You load the value on jQuery's DOM ready and never load it again.
You need to test the current value, not the one that's there when the DOM is ready, roughly:
$("#email_address").on("keypress", function() {
if(email.test($(this).val())) {
$("#email_address").parent().addClass("has-success");
}
});
Unrelated, but personally I'd wrap up the email test in a function so instead of saying email.test(xxx) you could read it more naturally like validEmail(xxx) etc.

Trying to use an id from the same page that my .click function was triggered on, in an ajax function

newbie to coldfusion/jquery/programming general here. So the overview of my problem is this: I have a ticket id that corresponds with a specific row in my database. When I click a button, I would like one of the columns in that row to change values to "In Testing". My issue is that I do not know how to pull that ticket id number into my jquery function, or if this is even possible. My code:
<script src="/TicketFaster/js/jquery-1.11.3.js"></script>
<script src="/TicketFaster/js/scripts.js"></script>
<cfset ticketid="#ticketid#">
<button id="in_testing" type="button">In Testing</button>
my js:
$(document).ready(function() {
$("#in_testing").click(function() {
var x = (#ticketid#);
$.ajax({
url: 'ticketcomponent.cfc?method=in_testing',
type: 'POST',
data: {
test: x
}
});
});
});
The big problem is that these pages are being generated dynamically, so each one will have a different ticket id. Therefore, I need to have the ticket id variable be imported rather than just hard coded in to the jquery function. So is this possible? I did not include the query because it works fine when I use it in other places, just getting the data delivered is the tough part. I appreciate any help you can give me :)
Edit: I was requested to post what I'm trying right now.
The original coldfusion is the same so I'm not going to post that again. Here is the js I'm using:
$(document).ready(function() {
$("#in_testing").click(function() {
var x = (<cfoutput>#ticketid#</cfoutput>);
alert(x);
});
});
(I also tried without the cfoutput tags)
As you can see, I'm just trying to do a simple alert to check if my variable has been correctly set. Once I get that to work, then the ajax should follow fairly quickly because I have some experience in that.
What is your specific issue?, can you share a jsfiddle?
for dynamic events replace
$("#in_testing").click(function() {});
for
$(document).on('click','#in_testing', function() {});
This value
var x = (#ticketid#);
in jquery is some like that
var x = $('#ticketid').val(); // for value or $('#ticketid') for object
you just have to take account id created dynamically

submitting a form via ajax upon stop event of jquery

UPDATE
Added this error, just says "Error caught"
<script type="text/javascript">
window.onerror = function() {
alert("Error caught");
};
xxx();
</script>
This is not working, I don't understand why.
My php script inserts data properly if called by itself without an if{method=post} statement
I tried with and without an if method = post argument on the php side to get the ajax below to work but I can't tell if the script is being called at all.
My aim is to submit the data without the user knowing, it's a coordinate / dimension update for a variable design interface.
This is my ajax insert which is supposed to work when a function is invoked after the stop is triggered eg. after an object is done moving which the function is invoked properly as I have set up sequential alerts to pop up after certain lines.
$("#form").submit(function(event){
event.preventDefault();
var $form = $( this ),
url = $form.attr( 'action' );
var posting = $.post( url, {
id: $('#id').val(),
name: $('#name').val(),
wname: $('#wname').val(),
xcor: $('#xcor').val(xcor),
ycor: $('#ycor').val(ycor),
xwid: $('#xwid').val(xwid),
yhei: $('#yhei').val(yhei),
photo: $('#photo').val(),
targeturl: $('#targeturl').val()
});
posting.done(function( data ){
alert('success');
});
});
This is wrong
xcor: $('#xcor').val(xcor),
ycor: $('#ycor').val(ycor),
xwid: $('#xwid').val(xwid),
yhei: $('#yhei').val(yhei),
Those object are holding jQuery objects, not a value.
Looks like you want to set the value and use the new value. This makes me cringe, but it would do the job
xcor: $('#xcor').val(xcor).val(),
ycor: $('#ycor').val(ycor).val(),
xwid: $('#xwid').val(xwid).val(),
yhei: $('#yhei').val(yhei).val(),
You would be better off updating them before the call and just using the variable when setting the object. Or just use jQuery serialize() and don't deal with grabbing the elements.

Getting all values being sent to the server at once

I have a form, bunch of inputs and submit button. Some of the inputs are added and deleted dynamically. And some of them may be (or may not) disabled but I still need to get their values of the server.
So I have to add a handler to the button and collect the values of the disabled inputs manually and add them up to other, enabled. inputs. But I'd like not to go that way as it seems too complex (since some of the inputs are added / removed dynamically).
I can also add hidden inputs for each inputs which can be disabled but still it's a bit complex.
What I want is similar to 1. But instead of manually enumerating the enabled inputs by jquery selectors, I want to just get all values are being sent to the server at once by some jquery function maybe or by any other way. And then manually (by selectors) add up the values from the disabled inputs to them. Is this possible?
You could use the jQuery .serialize() for that.
The general structure of the function would look something like this
var mydata = $("#myform").serialize();
$.ajax({
type: "POST",
url: "ajaxurl",
data: mydata,
dataType: "json",
success: function(data) {
...
}
});
So I just figured you had a problem of how to get the disabled fields as well. You could use the function suggested in this thread:
Disabled fields not picked up by serializeArray
Just to make the answer complete, I will copy the plugin from there.
The usage is like this:
var data = $('form').serializeAllArray();
And here's the plugin itself:
(function ($) {
$.fn.serializeAllArray = function () {
var obj = {};
$('input',this).each(function () {
obj[this.name] = $(this).val();
});
return $.param(obj);
}
})(jQuery);
You could use a strategy like the following in your submit handler:
Select all disabled elements .. (don't lose the reference to these)
Enable all disabled elements
Serialize the form .. to get all the data
Disable the elements back
Submit your form.

MVC dropdownlist onchange call jquery

I have a SelectList representing a delivery type for an order.
The delivery type reference data has the usual code/description, but also an additional boolean property which indicates if further information needs to be entered for the type selected.
So for Emergency deliveries additional data is required. The additional data entry fields would be set visible if Emergency was selected, otherwise hidden
My ViewModel contains <List>ReferenceDeliveryTypes which contains the 3 properties.
I have created a SelectListItems from the ViewModel data
#Html.DropDownListFor(model => model.DeliveryTypeCode,
new SelectList(Model.ReferenceDeliveryTypes as System.Collections.IEnumerable,
"DeliveryTypeCode", "DeliveryTypeDescription"), new { id = "ddlDeliveryType" })
How can I call a jQuery function on change of the delivery type, pass the selected code and check the Model.ReferenceDeliveryTypes for that code to see if the additional data property is true/false to show/hide the additional fields div?
I have managed to get the jQuery function called to pass the value.
$(function () {
$('#ddlDeliveryType').change(function () {
var value = $(this).val();
alert(value);
});
});
I don't know of any way you can do this using a select list but I suggest the following options:
Simple but a hack - add a string to the end of DeliveryTypeDescription, for example (emergency delivery) and check for that in your change function
Another hack - multiply DeliveryTypeCode by 10 and add 1 on if it's an emergency delivery (and then use mod 10 in your change function)
Use an Ajax lookup function
Load a JavaScript lookup table with the codes which require an emergency delivery
Use a hidden field in your form which contains a string list of the emergency codes with a suitable separator
Good luck
UPDATE
For the hidden field option if you use something like 123|456|789| and then use indexOf having appended a | to the selected ID.
I converted the Model.ReferenceDeliveryTypes to a JSON list which allowed me to access it from the jQuery.
Possibly not the best way, but it allows me to do everything on the client rather than making an AJAX call back. I can now show/hide the inside the if block.
Thought it worth documenting what I did as I've not come across the #Html.Raw(Json.Encode before and it might prove useful for someone who wants to access model data from within jQuery.
Any additional comments welcome.
<script type="text/javascript">
var ReferenceDeliveryTypeJsonList=#Html.Raw(Json.Encode(Model.ReferenceDeliveryTypes))
</script>
#Html.DropDownListFor(model => model.DeliveryTypeCode,
new SelectList(Model.ReferenceDeliveryTypes.ReferenceDeliveryType as System.Collections.IEnumerable,
"DeliveryTypeCode", "DeliveryTypeDescription"), new { id = "ddlDeliveryType" })
$(function () {
$('#ddlDeliveryType').change(function () {
var selectedDT= $(this).val();
$.each(ReferenceDeliveryTypeJsonList, function (index, item) {
if (selectedDT === item.DeliveryTypeCode) {
alert("match " + selectedDT);
}
});
});
});

Categories