Is it possible to hook a function to an html attribute?
For example:
HTML:
<form method="post" action="ajax.php" id="login-form" data-function="doSomething">
//...
</form>
JS:
function doSomething() {
alert('hello!');
}
$(document).on('submit', 'form', function(event){
event.preventDefault();
var form = $(this);
$.ajax({
url: form.attr('action'),
type: "POST",
data: form.serialize(),
success: function(result){
form.attr('data-function'); //<-- call the function defined in data-function here
}
});
});
Thanks in advance!
you can do this if you store the function in an object
const obj = {
doSomething() {
alert('hello!');
}
}
then you can call doSomething with
obj['doSomething']()
Related
Im am using Microsoft Edge in the scenario.
I as able to successfully do a single function with a ajax syntax with this code:
<script>
document.getElementById("inputEventID").onchange = function () { myFunction() };
function myFunction() {
$.ajax({
type: 'post',
url: 'webFetchMax.php',
data: {
eventID: form.eventID.value
},
success: function (response) {
$('#divSlots').html(response);
}
});
}
</script>
However when I insert addition functions with their on ajax inside the function I am receiving $ is not defined error function monitorOccupy() as shown below:
<script>
document.getElementById("inputEventID").onchange = function () { myFunction() };
monitorOccupy();
monitorAvail();
function monitorOccupy() {
$.ajax({
type: 'post',
url: 'webFetchMax.php',
data: {
eventID: form.eventID.value
},
success: function (response) {
$('#oSlots').html(response);
},
complete: function() {
setTimeout(monitorOccupy,1000);
}
});
}
function monitorAvail() {
}
function myFunction() {
$.ajax({
type: 'post',
url: 'webFetchMax.php',
data: {
eventID: form.eventID.value
},
success: function (response) {
$('#divSlots').html(response);
}
});
}
</script>
I have no idea my is this error is showing up on my console.
Call these functions as below
$(document).ready(function(){
monitorOccupy();
MonitorAvail();
});
Before posting this question the only jQuery file in my html file was jquery.min.js
<script scr="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
After inserting another jquery.min.js file my problem is solved. This is what it looks now:
<script scr="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
I'm trying to create a notification feature and I wanted the ajax to be able to run a query via the controller on button click
THIS IS MY SCRIPT
$('#noti_Button').click(function (e) {
e.preventDefault();
$.ajax({
url: '<?php echo site_url("profile/read_notif")?>'
});
});
THE CONTROLLER
public function read_notif(){
$this->profile_model->read_notifs($data['id']);
return;
}
AND THE MODEL
function read_notifs($id)
{
$read = array(
'read' => '1'
);
$this->db->where('recipient', $id);
$this->db->update('tbl_notifications', $read);
return;
}
I tried this and the data in the database doesn't update.
IN MY HTML IT IS JUST A SIMPLE BUTTON
Script
$('#noti_Button').click(function (e) {
e.preventDefault();
$.ajax({
url: '<?php echo site_url("profile/read_notif")?>',
success:function(data)
{
alert(data);
}
});
});
Controller
public function read_notif(){
$this->profile_model->read_notifs($data['id']);
echo $this->db->last_query();
}
It is the sample calling the ajax in ruby on rails . In this code we are calling the controller for getting the values.
$('#Button').on('change', function(event) {
var selected_resource_id = $(this).val();
$.ajax({
type: 'GET',
url: "<%= Home_index_path %>",
data: { id: selected_resource_id },
success: function (data) {
alert("Ajax success");
}
});
});
use error: to check if there's any error in submitting your form.
$('#button').click(function (e) {
e.preventDefault();
$.ajax({
url: '<?php echo site_url("profile/read_notif")?>',
success:function(data)
{
alert(data);
}
});
});
I have the following input HTML tag
<input type="submit" id="submitForm" value="Submit" class="btn btn-primary start" autocomplete="off" onclick="submitForm();" />
When I click on the submit button, it goes to the related JavaScript file and executes the function submitForm();
I would like to change the text of the submit form to "Please wait..." until the function is completed.
Is there a way this can be done?
This is how the submitForm() function looks like:
function submitForm() {
$("#submitForm").val("Please wait...");
if (formValidation() === true) {
submitFormInfo().done(function () {
$("#submitForm").val("Submit");
});
}
}
function submitFormInfo() {
return $.ajax({
cache: false,
url: "URLHERE"
error: function (xhr) {
},
success: function (result) {
},
async: false,
processData: false
});
}
Are you having asynchronus operation in submitform() ?
if yes then you can use following line
$("#submitForm").val("Please Wait");
You can use jquery please see:-
https://jsfiddle.net/swawrm1g/3/
I have removed:-
onclick="submitForm();"
and added:-
$('#submitForm').click(function(){
$(this).val('Please Wait...');
submitForm()
});
function submitForm() {
alert('Form submitted');
};
Simple javascript is enough to do this..
<script>
function submitForm(){
document.getElementById('submitForm').value="Please wait..";
}
</script>
<input type="submit" id="submitForm" onclick="submitForm()" value="Submit">
Use the beforeSend option on your ajax call, so in your submitForm() function, you can do something like this:
function submitForm() {
var submitForm = $("#submitForm");
if (formValidation() === true) {
$.ajax({
cache: false,
url: "URLHERE",
async: false,
type: 'post',
data: { somedata: 'here' },
beforeSend: function (){
submitForm.val("Please wait...").attr("disabled", "disabled");
},
success: function (data){
// do something
},
error: function (){
// do something
},
complete: function () {
// regardless of the response status (success/error)
// the codes below will be executed.
submitForm.val("Submit").removeAttr("disabled");
}
});
}
}
$('form.comment_form').submit(function(e) {
e.preventDefault();
var $form = $(this);
$.ajax({
url : 'inc/process-form.php',
type: 'POST',
cache: true,
data:({
comment : $form.find('input[name="comment"]').val(),
pid : $form.find('input[name="pid"]').val(),
post_author : $form.find('input[name="post_author"]').val(),
date_comment : $form.find('input[name="date_comment"]').val()
}),
success : function(results) {
$('.show-results').html(results).slideToggle().delay(2000).slideToggle();
$form[0].reset();
$('#all-post').load('home.php #all-post li');
}
});
return false;
});
The code above is my "jQuery+AJAX" for comment form. When I am submitting the comment form, it works fine but when I am submitting it again within a second, it reloads the page.
You can use unbind method to stop submitting the form again.
Here is the code as a sample :
var $form = $('form');
$form.bind('submit', function(e){
e.preventDefault();
...
$.ajax({
...
success: function(){
...
$form.unbind('submit').trigger('submit');
}
});
});
or you can use the it in other way
by using $(document).on("submit", "form", function() { });
sample code :
$(document).ready(function () {
$(document).on("submit", "form", function() {
$('#content').fadeOut(100, function () {
$(this).html('
<img src="//mywebsite.com/spinner.gif"/>
<div style="display:inline;color:#1FAEFF">Loading...</div>
').fadeIn(100);
});
$.get('submit.server', $(this).serialize(), function (data) {
$('#content').html(data);
});
return false;
});
});
I have a view with a few checkboxes that can be selected or unselected. I'd like to always register any change in a checkbox, without the use of a submit button (the user could forget to do it, and it would waste time).
So, is there a way to handle this inside the view? Up to now, I've only used the controller to do that job.
So, a piece of code :
#ModelType MvcApplication.OpportuniteDetails
#Code
ViewData("Title")="Details"
#End Code
<script type="text/javascript">
$(function () {
$(':checkbox').change(function() {
$.ajax({
url: '#Url.Action("update")',
type: 'POST',
data: { isChecked: $(this).is(':checked') },
success: function (result) { }
});
});
});
</script>
[... Some code here...]
#Html.Raw("Mail sent?") #Html.CheckBox(Model.Opportunite.Mail)
<input type="checkbox" name="mail" id="mail" onclick="test()" />
You could use AJAX:
$(function() {
$(':checkbox').change(function() {
var form = $(this).closest('form');
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function(result) {
}
});
});
});
In this example we subscribe to the change event of each checkbox. When this event is trigerred we look for the containing form and send its contents to the server using an AJAX request.
And if you only wanted to submit the current checkbox state to the server and not the entire form:
$(function() {
$(':checkbox').change(function() {
$.ajax({
url: '#Url.Action("SomeAction")',
type: 'POST',
data: { isChecked: $(this).is(':checked') },
success: function(result) {
}
});
});
});
where you could have a controller action which will do the necessary processing:
[HttpPost]
public ActionResult SomeAction(bool isChecked)
{
...
}
If you don't need or want AJAX and just want to submit the form, this
$(':checkbox').change(function() {
var form = $(this).closest('form');
form.get( 0 ).submit();
});
would do it.