Cakephp (2.x) Model Validation using "onclick" in Jquery not working - javascript

I'm working on a code already wrote... in CakePHP.
And, I've add some model validations.
But, in Jquery, this code works fine (model validation and HTML5 messages):
$('#itemAdd').on('submit', function(e) {
var $itemAdd = $("#itemAdd");
e.preventDefault();
var $this = $(this);
$this.serialize();
$.ajax({
...
}).done(function (data) {
if (data == true) {
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
});
location.reload();
}
}).fail(function () {
alert("Error");
});
});
But, when it's using 'click', the ajax method works but the validation NOT... :( :
$("#next-item").on('click', function(e) {
e.preventDefault();
var $itemAdd = $("#itemAdd");
var data = $itemAdd.serializeArray();
var $this = $(this);
$.ajax({
...
}).done(function (data) {
alert(data);
alert('go !');
var $addItem = $("#addItem");
$addItem.removeData('modal-header');
$addItem.removeData('modal-body');
$("#addItem .modal-content").load('<?php echo FULL_BASE_URL; ?>/stock/stocks/modal_item_add/<?php echo $batch_id; ?>', function () {
$('#addItem').modal('show');
});
}).fail(function (jqXHR, textStatus, errorThrown) {
alert("An error : " + textStatus + ", " + errorThrown );
});
return false;
});
The validation based on the Model doesn't work. But, in the Php method ,launched with Jquery Ajax, show me (it's ok) the validations errors with :
$this->Item->invalidFields();
There's a problem cause when I use $("#next-item") I want the jQuery modal not hide.
And using "submit" instead of "click" close the modal.
Can anybody has an idea ?
Thanks.
F.

Related

Ajax form is not going through when using Mozilla

When I'm on the form it says that it has been submitted, but it don't receive it in my email. It works fine with Chrome and MS Edge. Any help would greatly be appreciated.
I have uploaded the newest version of Java, but when I reference the new version in the .html file, it comes up with a blank web page.
or so it is not happy with the new version. I thought that might be the problem with Mozilla, but I'm not sure.
JS file:
jQuery(document).ready(function() {
//Captcha
$('.captcha-button').click(function() {
$( ".not-a-robot-text" ).fadeOut( 500 );
$( ".not-a-robot-icon i" ).delay( 499 ).fadeIn( 500 );
$( ".captcha-button" ).delay( 1500 ).fadeOut( 0 );
$( ".button-parent" ).html( '<button style="display:none" class="submit-form button border-radius l=12 text-white background-orange" type="submit">Submit Button</button>' );
$( ".submit-form.button" ).delay( 1500 ).fadeIn( 0 );
});
$('.ajax-form').each(function(index, element) {
$(this).submit(function(e) {
//Stop form submission & check the validation
e.preventDefault();
window.error = false;
//text, textarea
$(element).find('.required').each(function() {
// Variable declaration
var required = $(element).find(this);
var required_val = $(element).find(this).val();
// Form field validation
if (required_val.length == 0) {
window.error = true;
$(this).parent().find('.form-error').fadeIn(500);
$(element).find('.mail-success').fadeOut(500);
} else {
$(this).parent().find('.form-error').fadeOut(500);
$(element).find('.mail-fail').fadeOut(500);
}
});
//email
$(element).find('.email').each(function() {
// Variable declaration
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
var email = $(this).val();
// Form field validation
if (!filter.test(email)) {
window.error = true;
$(this).parent().find('.form-error').fadeIn(500);
$(element).find('.mail-success').fadeOut(500);
} else {
$(this).parent().find('.form-error').fadeOut(500);
$(element).find('.mail-fail').fadeOut(500);
}
});
// If there is no validation error, next to process the mail function
if (window.error == false) {
var formObj = $(this);
var formURL = formObj.attr("action");
var formData = new FormData(this);
$.ajax ({
url: 'resp-csa2.php',
type: 'POST',
data: formData,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(data, textStatus, jqXHR)
{
//If the email is sent successfully, reset form
$(element).each(function() {
this.reset();
});
//Display the success message
$(element).find('.mail-success').fadeIn(500);
},
error: function(jqXHR, textStatus, errorThrown)
{
//Display the error message
$(element).find('.mail-success').fadeOut(500);
$(element).find('.mail-fail').fadeIn(500);
}
});
e.preventDefault(); //Prevent Default action.
e.unbind();
}
});
});
});

jQuery How to make a variable that shows just the value of a form array

So right now I have a form that is saved in AJAX when submitted.
$(document).ready(function () {
$("#dispatchForm").on("submit", function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr("action") || window.location.pathname,
type: "POST",
data: $(this).serialize(),
success: function (data) {
$("#form_output").html(data);
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
I then have it where the result is shown in a variable and put into a textbox on the page when the submit button is clicked, via this code.
$(function () {
$("#dispatchSumbit").on("click", function () {
var text = $("#textarea");
var local = $("#dispatchForm").serialize();
text.val(text.val() + time +" - Dispatched to \n" + local);
});
});
However it shows the whole array which is like this:
I want it to just say "[Time] - Dispatched to Test"
Thanks for the help in advance!
$("#dispatchForm").serialize() is for creating a name=value&name=value&... string for all the inputs in the form, which can be used as the data in an AJAX request. If you just want a single value, use
var local = $("#dispatchForm [name=dispatchLocal]").val();

AJAX call doesn't work after submitting a form

This is my code at www.domain-a.de/external.search.js. I call it from www.domain-b.de/test.php:
(function ($) {
// make the ajax request
$.getJSON('http://www.domain-a.de/external-search.js?jsoncallback=?', function(data) {
// append the form to the container
$('#embedded_search').append(data);
$('#embedded_search form').attr('action','');
myUrl = 'http://www.domain-a.de/get-form-values?jsoncallback=?'
var frm = $('#embedded_search form');
// click on submit button
frm.submit(function (ev) {
$.getJSON( myUrl )
.done(function( json ) {
console.log( "JSON Data: " + json );
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
});
});
})(jQuery);
After running this code I don't get any message in console. What is wrong with that code?
frm.submit(function (ev) {
ev.preventDefault();
.....rest of code.
Your code is not calling the submit handler on the item, it is simply binding it. You should do the frm.submit(function binding outside of your $.getJSON callback; then inside the callback add
frm.submit()
Which triggers the event.
Also, when the submit happens, your actions will take place but then the form will submit to the back end as normal, causing a page reload.
After the line
frm.submit(function (ev) {
Add
ev.preventDefault();
So your overall code should be
(function ($) {
var frm = $('#embedded_search form');
var myUrl = 'http://www.domain-a.de/get-form-values?jsoncallback=?'
frm.submit(function (ev) {
ev.preventDefault();
$.getJSON( myUrl )
.done(function( json ) {
console.log( "JSON Data: " + json );
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
});
// make the ajax request
$.getJSON('http://www.domain-a.de/external-search.js?jsoncallback=?', function(data) {
// append the form to the container
$('#embedded_search').append(data);
$('#embedded_search form').attr('action','');
// click on submit button
frm.submit();
});
})(jQuery);

Jquery ajax() not working as expected

I have a function getActivityHP() which I am calling as soon as my page loads. This function makes an ajax calls to another test3.php page with certain data which will contain default values initially. However as soon as I add my ajax code the function stops working as if there is an error. Simple alert also doesn't work!
<script>
$(document).ready( function(){
alert("Welcome");// not working
getActivityHP();
}
function getActivityHP() {
$("#loading").show();
alert("Hello"); // not working
var search = $("#search").val();
var deployedon = $("#deployedon").val();
var platform = $("#platform").val();
var country = $("#country").val();
var carrier = $("#carrier").val();
$.ajax({
type: "POST",
url: "test3.php",
data: {
"action" : "activity",
"deployedon" : deployedon,
"platform" : platform,
"country" : country,
"carrier" : carrier
},
success: function(msg) {
$("#loading").hide();
$("#activity").html(msg);
}
error: function() {
alert("An error occurred while processing file.");
}
});
}
</script>
In my test3.php I am doing:-
$action=$_POST['action'];
$deployedon=$_POST['deployedon'];
$platform=$_POST['platform'];
$carrier=$_POST['carrier'];
$country=$_POST['country'];
and then I am using echo to print these in my html!
There is syntax error. You are missing ) at the end of -
$(document).ready( function(){
alert("Welcome");
getActivityHP();
});
And missing , at the end of success -
success: function(msg) {
$("#loading").hide();
$("#activity").html(msg);
},
Update your code and try to run.
You missed a comma right here:
success: function(msg) {
$("#loading").hide();
$("#activity").html(msg);
}, // <--- This comma
error: function() {
alert("An error occurred while processing file.");

Only send post/get if form values has changed

I want to prevent multiple ajax calls (user holds enter key down or multi presses submit or other)
I'm thinking, the best way is to use a var with the previous form post values and compare them at each click/submit.. Is it the same? : Then do nothing
But I don't know how to go about it
Here is my javascript/jquery:
$('form').submit(function() {
$theform = $(this);
$.ajax({
url: 'validate.php',
type: 'POST',
cache: false,
timeout: 5000,
data: $theform.serialize(),
success: function(data) {
if (data=='' || !data || data=='-' || data=='ok') {
// something went wrong (ajax/response) or everything is ok, submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
} else {
// ajax/response is ok, but user input did not validate, so don't submit
console.log('test');
$('#jserrors').html('<p class="error">' + data + '</p>');
}
},
error: function(e) {
// something went wrong (ajax), submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
}
});
return false;
});
Not very creative with naming vars here:
var serial_token = '';
$('form').submit(function() {
$theform = $(this);
if ($(this).serialize() === serial_token) {
console.log('multiple ajax call detected');
return false;
}
else {
serial_token = $(this).serialize();
}
$.ajax({
url: 'validate.php',
type: 'POST',
cache: false,
timeout: 5000,
data: $theform.serialize(),
success: function(data) {
if (data=='' || !data || data=='-' || data=='ok') {
// something went wrong (ajax/response) or everything is ok, submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
} else {
// ajax/response is ok, but user input did not validate, so don't submit
console.log('test');
$('#jserrors').html('<p class="error">' + data + '</p>');
}
},
error: function(e) {
// something went wrong (ajax), submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
}
});
return false;
});
You could combine this with a timeout/interval function which aborts the submit, but the code above should just compare the data in the form
If you have some kind of submit button, just add a class 'disabled' to it when you start the ajax call, and check if it is present before trying to make the call. Remove the class when the server gives a response. Something like:
...
$theform = $(this);
$button = $theform.find('input[type=submit]');
if ($button.hasClass('disabled')) {
return false;
}
$button.addClass('disabled');
$.ajax({
....
},
complete: function () {
$button.removeClass('disabled');
}
});
...

Categories