jQuery Form Validate not posting when using file upload - javascript

I've been using jQuery Validate plugin without problems for a while now, but not that I'm trying to use it with a file upload it does not work.
Im getting no post, and the page just reloads too quickly for me to see the "illegal" error that comes up.
The jQuery is as follows:
_validateModalForm = function(formID, modalShow){
var mesContainer = "#modal-message";
$("#" + formID).validate({
invalidHandler: function () { //display error alert on form submit
EMPGlobal.showAlert(mesContainer, '', 'danger', 'There was an error, please check the form, correct, and try again.' , '', '', '', 'warning');
},
submitHandler: function (form){
var formData = form;
formData = new FormData(formData);
console.log(formData);
$.ajax({
url: 'includes/pages/leads.php?',
//data: $(form).serialize(),
data: formData,
mimeType: "multipart/form-data",
type: "POST",
success: function (result) {
$.each(result, function(item, value){
if( (item == 'Success') || (item == 'Warning') ){
if(item == 'Success'){
var alertType = 'success';
} else {
var alertType = 'danger';
}
modalShow.modal('toggle');
EMPGlobal.showAlert('', '', 'success', value, '', '', '', alertType);
$('#lead-report-range').change(); //Reset the boxes
}
});
},
error: function (jqXHR, textStatus, errorThrown) {
returnMes = $.parseJSON(jqXHR.responseText);
message = 'A ' + jqXHR.status + ' ' + errorThrown + ' error occurred. <br /> <i>Message Details: ' + returnMes + '</i>';
EMPGlobal.showAlert(mesContainer, '', 'danger', message, '', '', '', 'warning', jqXHR.status);
},
});
return false;
}
});
$("#" + formID + " input[required='required']").each(function(){
$(this).rules( "add", {
required: true,
minlength: 2
});
});
};
It validates correctly, but just wont post over Ajax.
Any help on this one would be appreciated. I'm sure its something simple that I am missing.
Update
The error is as follows:
Uncaught TypeError: Illegal invocation
n.param.e # jquery-1.11.0.min.js:4
Wc # jquery-1.11.0.min.js:4
n.param # jquery-1.11.0.min.js:4
n.extend.ajax # jquery-1.11.0.min.js:4
$.validate.submitHandler # leads.js:157
d # VM16566:4(anonymous function) # VM16566:4
n.event.dispatch # jquery-1.11.0.min.js:3
n.event.add.r.handle # jquery-1.11.0.min.js:3

With the help of charlietfl managed to get this working.
_validateModalForm = function(formID, modalShow){
var mesContainer = "#modal-message";
$("#" + formID).validate({
invalidHandler: function () { //display error alert on form submit
EMPGlobal.showAlert(mesContainer, '', 'danger', 'There was an error, please check the form, correct, and try again.' , '', '', '', 'warning');
},
submitHandler: function (form){
var formData = new FormData($(form)[0]);
$.ajax({
url: 'includes/pages/leads.php?',
//data: $(form).serialize(),
data: formData,
type: "POST",
dataType: "json",
cache: false,
contentType: false,
processData: false,
success: function (result) {
$.each(result, function(item, value){
if( (item == 'Success') || (item == 'Warning') ){
if(item == 'Success'){
var alertType = 'success';
} else {
var alertType = 'danger';
}
modalShow.modal('toggle');
EMPGlobal.showAlert('', '', 'success', value, '', '', '', alertType);
$('#lead-report-range').change(); //Reset the boxes
}
});
},
error: function (jqXHR, textStatus, errorThrown) {
returnMes = $.parseJSON(jqXHR.responseText);
message = 'A ' + jqXHR.status + ' ' + errorThrown + ' error occured. <br /> <i>Message Details: ' + returnMes + '</i>';
EMPGlobal.showAlert(mesContainer, '', 'danger', message, '', '', '', 'warning', jqXHR.status);
},
});
return false;
}
});
};

Related

Laravel Hiding Validation Errors Message with Ajax when is true

i have implement the validation errors message with ajax successfully, but when the previous input form is true, the previous error in that input form is not hiding. Anyone can help me to hide the previous error if input form is true?
This is my javascript code :
$.ajax({
url: `${window.url}/income`,
type: "POST",
data: {
_token: CSRF_TOKEN,
detail: arrValues,
data_contact_id,
total,
description,
invoice,
transaction_date,
to_account_id,
},
dataType: "JSON",
success: function (response) {
console.log(response);
if (response.status) {
Swal.fire({
icon: "success",
type: "success",
title: response.message,
showConfirmButton: true,
}).then((result) => {
window.location.href = `${window.url}/income`;
});
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
let fields = [
"data_contact_id",
"invoice",
"transaction_date",
"to_account_id",
"description",
];
fields.map((field) => {
$(`#${field}`).removeClass("is-invalid");
$(`.${field}-error`).html(``);
});
let errors = jqXHR.responseJSON.errors;
$.each(errors, function (key, value) {
$(`#${key}`).addClass("is-invalid");
$(`.${key}-error`).append(`
<span class="text-danger" style="font-size: 0.8rem">
${value.map((v) => "<strong>" + v + "</strong><br>")}
</span>
`);
console.log("Field : ", key);
});
Swal.fire({
icon: "error",
type: "error",
title: "Error!",
showConfirmButton: true,
});
},
});
In my controller i have return validation error json from Validator::make()
if ($validator->fails()) {
return response()->json(['errors' => $validator->errors()->all()]);
}
$.ajax({
beforeSend: function(){
$(".key_of_form").removeClass("is-invalid");
$(".error_of_key").empty();
},
complete: function(){
// Handle the complete event
}
error : function(){
// Handle the error event
}
// ......
});
$(`#${key}`) add class key_of_form
$(`.${key}-error`) add class error_of_key
before submit of form or beforeSend of ajax you need reset error messages same as :
$(".key_of_form").removeClass("is-invalid");
$(".error_of_key").empty();

How can I post message in Yammer Group with link user?

Yammer REST api json. My code send message in group succesfull. But I need to send msg with "cc", link some user, like this:
function yamPostRequest(val) {
var msg_value = document.getElementById('msg_body').value;
var groupID = document.getElementById('group_id').value;
if (msg_value == "") {
alert("Message body cannot be empty!");
return false;
}
if (groupID == "") {
var conf = confirm("Group ID is empty, message will be posted to All Company");
if (conf == false) {
return false;
}
}
yam.platform.request({
url: "https://api.yammer.com/api/v1/messages.json",
method: "POST",
data: {
"body": msg_value,
//"title" : msg_title,
"group_id": groupID,
},
success: function(msg) {
alert("Post was Successful!");
},
error: function(msg) {
alert("Post was Unsuccessful");
}
})
}
I found it.
function PostYammerWithNotification(group_id, message, userCC) {
var yammerData;
yammerData = {
group_id: group_id,
body: message
};
yammerData.cc = "[[user:" + userCC + "]]";
yam.platform.request({
url: "https://api.yammer.com/api/v1/messages.json",
method: "POST",
data: yammerData,
success: function(msg) {
alert("Post was Successful!");
},
error: function(msg) {
alert("Post was Unsuccessful");
}
});
}
You need to use user ID:
PostYammerWithNotification(/*Group ID*/,"test msg",/*User ID*/)
Found it here

javascript works on localhost but fails on hosting server

When i click on add-to-basket button i see an error which appears in my browser console saying :
Here is my basket.js file :
$(document).ready(function() {
initBinds();
function initBinds() {
if ($('.remove_basket').length > 0) {
$('.remove_basket').bind('click', removeFromBasket);
}
if ($('.update_basket').length > 0) {
$('.update_basket').bind('click', updateBasket);
}
if ($('.fld_qty').length > 0) {
$('.fld_qty').bind('keypress', function(e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code == 13) {
updateBasket();
}
});
}
}
function removeFromBasket() {
var item = $(this).attr('rel');
$.ajax({
type: 'POST',
url: '/home/u919084925/public_html/mod/basket_remove.php',
dataType: 'html',
data: ({ id: item }),
success: function() {
refreshBigBasket();
refreshSmallBasket();
},
error: function() {
alert('An error has occurred');
}
});
}
function refreshSmallBasket() {
$.ajax({
url: '/home/u919084925/public_html/mod/basket_small_refresh.php',
dataType: 'json',
success: function(data) {
$.each(data, function(k, v) {
$("#basket_left ." + k + " span").text(v);
});
},
error: function(data) {
alert("An error has occurred");
}
});
}
function refreshBigBasket() {
$.ajax({
url: '/home/u919084925/public_html/mod/basket_view.php',
dataType: 'html',
success: function(data) {
$('#big_basket').html(data);
initBinds();
},
error: function(data) {
alert('An error has occurred');
}
});
}
if ($(".add_to_basket").length > 0) {
$(".add_to_basket").click(function() {
var trigger = $(this);
var param = trigger.attr("rel");
var item = param.split("_");
$.ajax({
type: 'POST',
url: '/home/u919084925/public_html/mod/basket.php',
dataType: 'json',
data: ({ id : item[0], job : item[1] }),
success: function(data) {
var new_id = item[0] + '_' + data.job;
if (data.job != item[1]) {
if (data.job == 0) {
trigger.attr("rel", new_id);
trigger.text("Remove from basket");
trigger.addClass("red");
} else {
trigger.attr("rel", new_id);
trigger.text("Add to basket");
trigger.removeClass("red");
}
refreshSmallBasket();
}
},
error: function(data) {
alert("An error has occurred");
}
});
return false;
});
}
function updateBasket() {
$('#frm_basket :input').each(function() {
var sid = $(this).attr('id').split('-');
var val = $(this).val();
$.ajax({
type: 'POST',
url: '/home/u919084925/public_html/mod/basket_qty.php',
data: ({ id: sid[1], qty: val }),
success: function() {
refreshSmallBasket();
refreshBigBasket();
},
error: function() {
alert('An error has occurred');
}
});
});
}
// proceed to paypal
if ($('.paypal').length > 0) {
$('.paypal').click(function() {
var token = $(this).attr('id');
var image = "<div style=\"text-align:center\">";
image = image + "<img src=\"/images/loadinfo.net.gif\"";
image = image + " alt=\"Proceeding to PayPal\" />";
image = image + "<br />Please wait while we are redirecting you to PayPal...";
image = image + "</div><div id=\"frm_pp\"></div>";
$('#big_basket').fadeOut(200, function() {
$(this).html(image).fadeIn(200, function() {
send2PP(token);
});
});
});
}
function send2PP(token) {
$.ajax({
type: 'POST',
url: '/mod/paypal.php',
data: ({ token : token }),
dataType: 'html',
success: function(data) {
$('#frm_pp').html(data);
// submit form automatically
$('#frm_paypal').submit();
},
error: function() {
alert('An error has occurred');
}
});
});
I tried to resolve it but couldn't find a proper solution.
Help me with this, I cannot understand the cause of this error.
This is mainly due to Rules of Origins (CORS), for some reason the javascript(browser) sees the request as not residing in the same server. And the reason for that, I believe, is because /home/u919084925/public_html/mod/basket.php is not seen as a valid url on the server, it should start with http://{hostname}/{path}.
It looks like your ajax url is totally wrong and the browser interpret that is cross origin ajax request. Please simply check in browser's address bar if your ajax provided urls are valid.

Error passing json data through ajax method into DataTable

Im getting an error in my IDE on the console of Google Chrome that states:
Uncaught TypeError: Cannot read property 'length' of undefined. This error is thrown when dataTables takes the raw json data and attempts to inject it into the table.
// Got the data - add it to the table
for ( i=0 ; i<aData.length ; i++ ) {
_fnAddData( settings, aData[i] );
}
<script>
$(document).ready(function(){
$('#clickMe').click(function(){
$.ajaxPrefilter(function(options, originalOptions, jqHXR ){
options.async = true;
});
$.ajax({
//type: 'GET',
url: 'URL',
dataType:"json",
data: "getAddressResults", //name of json expression
success: function(data){
var jsTable = $('#data').dataTable();
jsTable.fnClearTable();
$.each(data, function(key, value){
var i = this.length;
alert("There are : " + i + " entries."); //shows how many objects are in my json data
jsTable.dataTable().fnAddData([
value[key].childName,
value[key].childNum,
value[key].lineNum,
value[key].parentName,
value[key].parentNum
]);
});
if(data){
var txt = "";
if(res > 0){
for (var i=0;i<data.length;i++){
if (data[i].parentNum && data[i].childNum){
txt += "<tr><td>"+data[i].parentNum+"</td><td>"+data[i].childNum+"</td></tr>"
}
}
if(txt !=""){
$("#data").append(txt).removeClass("hidden");
}
}
}
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus + ': ' + errorThrown);
}
});
return false;
});
$('#data').DataTable({
columns:[
{ title: "childName" },
{ title: "childNum" },
{ title: "lineNum" },
{ title: "parentName" },
{ title: "parentNum" }
]
});
Remove that <script> tag, you can't just put an html tag like that in between of a javascript.

Add Javascript function return value to output

I have the following code:
var Faculty180API = {
token: '1a88be52b9e9dd649998c3c1979b6b5c79cc160e',
base_url: 'https://www.faculty180.com/api.php',
account: 'DemoLinks',
last_results: null,
fetch: function(path, params, callback) {
$.ajax((this.base_url + this.make_path(path)), {
data: this.make_params(params),
crossDomain: true,
xhrFields: { withCredentials: true },
success: callback,
dataType: 'json',
error: function(xhr) {
if(xhr.status == 200) {
$('#results').text(xhr.responseText);
}
else {
$('#URL').text(Faculty180API.base_url . HERE);
$('#results').text(xhr.status + ' - ' + xhr.statusText);
}
}
});
},
make_params: function(params){
params['token'] = this.token;
return $.param(params);
},
}
In the line that I have written HERE, I want to add what Function(params) returns to the output. How can I do this?
Haven't tested this, but I'm thinking you can just call it like this:
$('#URL').text(Faculty180API.base_url + Faculty180API.make_params( yourParams ) );
Also note that I changed your . (after base_url) to a +. Dot is string concatenation in PHP; in Javascript it's +

Categories

Resources