get script Jquery issues - javascript

im having troubles with getting script from another file in jquery.
i've tried with $.getScript and $.ajax();
how can i include one script like require.js in jquery?
util.js
function getSessionInformation () {
$.ajax({
url: '../controller/controller.php',
type: 'POST',
dataType:'JSON',
data: {
action: 'getInfoCompany'
},
})
.done(function(data) {
try{
return data;
}catch(e){
console.log(e);
}
})
.fail(function() {
console.log("error");
});
}
file.js
$(document).ready(function() {
_getAllUsers();
});
function _getAllUsers()
{
jQuery.ajax({
url: "util.js",
dataType: "script",
cache: true
}).done(function() {
alert("im in");
jQuery.cookie("cookie_name", "value", { expires: 7 });
});
}

Try again, the getScript method is the right tool for this:
function _getAllUsers()
{
jQuery.getScript("util.js", function() {
alert("im in");
jQuery.cookie("cookie_name", "value", { expires: 7 });
});
}
Update:
The reason that you get a HTTP 404 error is that the URL that you are using will look for the script in the same folder as the page. You need a ../ to get out of the view folder and a js to get into the script folder:
jQuery.getScript("../js/util.js", function() {

Related

Sync issue with iframe in Chrome and Edge

the following script is used to load in a IFRAME a web application.
function openCashier(destination) {
postIsAnonymous(function (data) {
if (data.IsAnonymous) {
window.parent.location.replace('<%= ResolveUrl("~/Popup/login") %>');
} else {
stateReset('showUserBtn');
WCore.OpenTab('cashier');
$("#cashierPopup").addClass(destination);
$("#cashierFrame").attr('src', '<%= ResolveUrl(Routing.GetUrl("Root-TPAutologin")) %>?Destinazione=' + destination);
}
});
}
In Firefox everything works fine, while in Edge and Chrome I get error 404. If I try to load the contents of the IFRAME in a separate browser session everything works.
I tried to edit the javascript as follows, fearing an asynchronism problem:
function openCashier(destination) {
setTimeout(function () {
postIsAnonymous(function (data) {
if (data.IsAnonymous) {
window.parent.location.replace('<%= ResolveUrl("~/Popup/login") %>');
} else {
stateReset('showUserBtn');
WCore.OpenTab('cashier');
$("#cashierPopup").addClass(destination);
$("#cashierFrame").attr('src', '<%= ResolveUrl(Routing.GetUrl("Root-TPAutologin")) %>?Destinazione=' + destination);
}
});
}, 1000 * 20);
}
With this trick the problem is solved with very bad performances.
PostIsAnonymous code is the following :
function postIsAnonymous(successFunc) {
$.ajax({
type: "POST",
url: '?checkIsAnonymous=1',
cache: false,
contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
processData: false,
success: successFunc
});
}
Do you have any suggestions to give me to solve the problem in a more
elegant way? Thank you
I solved the problem with the following code.
function openCashier(destination) {
var dest = destination;
sessionManager.isAnonymous()
.then((data) => {
if (data.IsAnonymous) {
window.parent.location.replace('<%= ResolveUrl("~/Popup/login") %>');
}
else {
stateReset('showUserBtn');
WCore.OpenTab('cashier');
$("#cashierPopup").addClass(dest);
$("#cashierFrame").attr('src', '<%= ResolveUrl(Routing.GetUrl("Root-TPAutologin")) %>?Destinazione=' + dest);
}
})
.catch((err) => {
console.error(err);
});
}
var sessionManager = {
isAnonymous: () => {
return new Promise((resolve, reject) => {
$.ajax({
type: "POST",
url: '?checkIsAnonymous=1',
cache: false,
contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
processData: false,
success: function (data) {
resolve(data);
},
error: function (data) {
reject(data);
}
});
})
}
}

How to run JavaScript code on Success of Form submit?

I have an Asp.Net MVC web application. I want to run some code on the successful response of the API method which is called on form submit.
I have the below Code.
#using (Html.BeginForm("APIMethod", "Configuration", FormMethod.Post, new { #class = "form-horizontal", id = "formID" }))
{
}
$('#formID').submit(function (e) {
$.validator.unobtrusive.parse("form");
e.preventDefault();
if ($(this).valid()) {
FunctionToBeCalled(); //JS function
}
}
But FunctionToBeCalled() function gets called before the APIMethod(), but I want to run the FunctionToBeCalled() function after the response of APIMethod().
So I made the below changes by referring this link. But now the APIMethod is getting called twice.
$('#formID').submit(function (e) {
$.validator.unobtrusive.parse("form");
e.preventDefault();
if ($(this).valid()) {
//Some custom javasctipt valiadations
$.ajax({
url: $('#formID').attr('action'),
type: 'POST',
data: $('#formID').serialize(),
success: function () {
console.log('form submitted.');
FunctionToBeCalled(); //JS function
}
});
}
}
function FunctionToBeCalled(){alert('hello');}
So I am not able to solve the issue.
If you want to execute some work on success, fail, etc. situation of form submission, then you would need to use Ajax call in your view. As you use ASP.NET MVC, you can try the following approach.
View:
$('form').submit(function (event) {
event.preventDefault();
var formdata = $('#demoForm').serialize();
//If you are uploading files, then you need to use "FormData" instead of "serialize()" method.
//var formdata = new FormData($('#demoForm').get(0));
$.ajax({
type: "POST",
url: "/DemoController/Save",
cache: false,
dataType: "json",
data: formdata,
/* If you are uploading files, then processData and contentType must be set to
false in order for FormData to work (otherwise comment out both of them) */
processData: false, //For posting uploaded files
contentType: false, //For posting uploaded files
//
//Callback Functions (for more information http://api.jquery.com/jquery.ajax/)
beforeSend: function () {
//e.g. show "Loading" indicator
},
error: function (response) {
$("#error_message").html(data);
},
success: function (data, textStatus, XMLHttpRequest) {
$('#result').html(data); //e.g. display message in a div
},
complete: function () {
//e.g. hide "Loading" indicator
},
});
});
Controller:
public JsonResult Save(DemoViewModel model)
{
//...code omitted for brevity
return Json(new { success = true, data = model, message = "Data saved successfully."
}
Update: If SubmitButton calls a JavaScript method or uses AJAX call, the validation should be made in this method instead of button click as shown below. Otherwise, the request is still sent to the Controller without validation.
function save(event) {
//Validate the form before sending the request to the Controller
if (!$("#formID").valid()) {
return false;
}
...
}
Update your function as follows.
$('#formID').submit(function (e) {
e.preventDefault();
try{
$.validator.unobtrusive.parse("form");
if ($(this).valid()) {
$.ajax({
url: $('#formID').attr('action'),
type: 'POST',
data: $('#formID').serialize(),
success: function () {
console.log('form submitted.');
FunctionToBeCalled(); //JS function
}
});
}
}
catch(e){
console.log(e);
}
});
Check the browser console for fetching error. The above code will prevent of submitting the form.
I think line $.validator.unobtrusive.parse("form") were throwing error.
For that use you need to add the following jQuery libraries.
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.11/jquery.validate.unobtrusive.min.js"></script>
I think you should remove razor form tag if you want to post your form using ajax call and add post api URL directly to ajax request instead of getting it from your razor form tag using id:
Here is the revised version of your code :
<form method="post" id="formID">
<!-- Your form fields here -->
<button id="submit">Submit</button>
</form>
Submit your form on button click like:
$('#submit').on('click', function (evt) {
evt.preventDefault();
$.ajax({
url: "/Configuration/APIMethod",
type: 'POST',
dataType : 'json',
data: $('#formID').serialize(),
success: function () {
console.log('form submitted.');
FunctionToBeCalled(); //JS function
}
});
});
function FunctionToBeCalled(){alert('hello');}
You need to use Ajax.BeginForm, this article should help [https://www.c-sharpcorner.com/article/asp-net-mvc-5-ajax-beginform-ajaxoptions-onsuccess-onfailure/ ]
The major thing here is that I didn't use a submit button, I used a link instead and handled the rest in the js file. This way, the form would nver be submitted if the js file is not on the page, and with this js file, it initiates a form submission by itself rather than th form submitting when the submit button is clicked
You can adapt this to your solution as see how it respond. I have somthing like this in production and it works fine.
(function() {
$(function() {
var _$pageSection = $('#ProccessProductId');
var _$formname = _$pageSection.find('form[name=productForm]');
_$formname.find('.buy-product').on('click', function(e) {
e.preventDefault();
if (!_$formname.valid()) {
return;
}
var formData = _$formname.serializeFormToObject();
//set busy animation
$.ajax({
url: 'https://..../', //_$formname.attr('action')
type: 'POST',
data: formData,
success: function(content) {
AnotherProcess(content.Id)
},
error: function(e) {
//notify user of error
}
}).always(function() {
// clear busy animation
});
});
function AnotherProcess(id) {
//Perform your operation
}
}
}
<div class="row" id="ProccessProductId">
#using (Html.BeginForm("APIMethod", "Configuration", FormMethod.Post, new { #class = "form-horizontal", name="productForm" id = "formID" })) {
<li class="buy-product">Save & Proceed</li>
}
</div>

jquery date picker is not work when i put datepicker on ready after ajax call

I want to know that my jquery-ui datepicker is not working in document.ready after an ajax function call. when I put on ajax complete its work successfully please help what should I do. what's the reason for not working
$("#ScheduledArrivalDate").datepicker({
beforeShow: function () {
setTimeout(function () {
$('.ui-datepicker').css('z-index', 2000);
}, 0);
}
});
function getPage(page) {
$.ajax({
type: "POST",
url: page,
data: $("#frm").serialize(),
xhrFields: {
withCredentials: true
},
success: function (html) {
$('#List').empty();
$('#List').append($.parseHTML(html));
},
error: function () {
alert("error");
},
complete: function () {
alert("complete");
}
});
}
$.document.ready() only initiates after a page is loaded without ajax. When you replace/append html in an ajax call and you have a datefield in the new inserted html, you need to initialise it again (at least for the new inserted html block).
You could do this by calling $.datepicker in your success or complete function, like you already did, or by adding $.document.ajaxEnd() to your javascript file, what is initialized after every end of an ajax event (also on error).
Be aware not do double initiate the datepicker, especially when using ajaxEnd. This could lead to unexpected behaviour.
the code inside $(document).ready() will run only after page loads. While you are dynamically adding datepicker if I am not wrong. So do one thig. Take options in a variable like below:
var options = {
beforeShow: function () {
setTimeout(function () {
$('.ui-datepicker').css('z-index', 2000);
}, 0);
}
}
then:
$(document).ready(function(){
$("#ScheduledArrivalDate").datepicker(options);
});
and in ajax call:
function getPage(page) {
$.ajax({
type: "POST",
url: page,
data: $("#frm").serialize(),
xhrFields: {
withCredentials: true
},
success: function (html) {
$('#List').empty();
$('#List').append($.parseHTML(html));
$('#IdOfnewlyAddedDatePicker').datepicker(options);
},
error: function () {
alert("error");
},
complete: function () {
alert("complete");
}
});
}
Let me know if this not work or you are injecting html other than this.

AJAX/ json returning null open cart

Hi Im attempting a simple ajax request but I keep getting a null value for json.
Here is my javascript...
<script>
$(document).ready( function() {
$('#donate-box-submit').on('click', function() {
var donate_code = $('#charity-campaign-code').val();
var donate_amount = $('#charity-campaign-amount').val();
$.ajax({
url: 'index.php?route=donate/donatenow',
type: 'post',
data: {
donate_code: donate_code,
donate_amount: donate_amount
},
dataType: 'json',
beforeSend: function() {
},
complete: function() {
},
success: function(json) {
console.log(json);
alert(json['test']);
},
error: function() {
}
});
});
});
</script>
and my php...
public function donatenow() {
$json = array(
'test' => 'Output this text'
);
$this->response->setOutput(json_encode($json));
}
I have also tried echo json_encode($json); just to rule out any issues with that OpenCart function, but the same issue is still there.
The problem is the route you are using to call the method. Not sure on exactly what class you are using as the controller, but there should be three parts to the route: route=aaa/bbb/donatenow where as you've got aaa/donatenow

Why won't the return value print from the jQuery $.post function?

First, let's start with the code.
chrome.tabs.getSelected(null, function(tab) {
tabURL = tab.url;
$.post("http://s.mxtm.me/yourls-api.php",
{ signature: "XXXXXXXXXX",
action: "shorturl",
url: tabURL,
format: "simple"
},
function(data) {
$("body").append(data);
});
I'm working on a little Chrome extension as a client for YOURLS, and I'm using the jQuery $.post function to interact with the YOURLS API.
Under function(data) { I'm attempting to print the return from my POST. I've tried appending, I've tried alerting, I've tried document.writing, but nothing works. Does anyone have any idea of what is wrong?
That usually means that the ajax call is failing, add an error callback to see what's wrong:
$.post(
"http://s.mxtm.me/yourls-api.php",
{ signature: "XXXXXXXXXX", action: "shorturl", url: tabURL, format: "simple" },
function(data) { $("body").append(data); }
).error(function(xhr,error,ex) { alert("error"); });

Categories

Resources