Add if and else in javascript function based on other jquery function - javascript

I have a jQuery function that will be run when user click a submit button of form is submitted
FUNCTION #1
jQuery(function($){
$('#filter').submit(function() {
var filter = $('#filter');
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
type:filter.attr('method'), // POST
beforeSend:function(xhr){
filter.find('button').text('Filtering...'); // changing the button label
},
success:function(data){
filter.find('button').text('Filter'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
});
});
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
I have other script with javascript that run when user click on link with id "link-id".
FUNCTION #2
$div1 = $(".div1");
$div2 = $(".div2");
$div1.hide()
$div2.hide()
function showDiv(){
if(document.getElementById('chk1').checked){
$div1.show()
} else {
$div1.hide()
}
if(document.getElementById('chk2').checked){
$div2.show()
} else {
$div2.hide()
}
}
$('#link-id').on('click', showDiv)
<a id="link-id" class="btn btn-primary" href="javascript: void(0)">Go ahead</a>
I'd like to add and if and else in the FUNCTION #2 that:
if jQuery 'FUNCTION #1' is not submitted (run), javascript 'FUNCTION #2' do something (current code);
if user has already click one time on button to run 'FUNCTION #1', the 'FUNCTION #2' shall do other thing.
I'm not expert with javascript code.
Is there a way to made this check?

If I'm understanding you correctly the two functions are called from different event which means at different times.
If the scripts are linked (by integrating both in the html) or in one:
Then you could add a global variable that changes in function 1 and is being checked in function 2.
Declaration:
let functionOneWasExectuted = false;
In function 1:
functionOneWasExectuted = true;
In function 2:
if (functionOneWasExectuted) {
// code function 1 has been executed before
} else {
// code function 1 has not been executed before
}
If the 2 scripts are not linked in any way let me know and I'll post a different solution :)

Related

how to open view result from action call from javascript

i'm developing using ASP.Net mvc 4. I have a delete function in my Index view. Before user proceed to delete an item, this is the steps to go through
pop-up a confirm dialog to get the 'yes' or 'no' answer using javascript.
If the user say 'yes', I call the delete action from my controller
the delete action remove the item from database
the delete action return 'RedirectToAction ("Index");'
.. suppose the view will be updated with latest update
Step 5 is my problem.. its not working
Here is my code
The delete button
<a href="#Url.Action("DeleteFile", new { id = #item.Id })"
onclick = "return confirm2delete(this);"
class="btn btn-danger btn-sm"
data-toggle="tooltip" title="Delete File">
<i class="fa fa-trash-o"></i>
</a>
The javascript
function confirm2delete(obj)
{
deleteLinkObj = $(this);
w2confirm("Are sure to delete this file ?")
.yes(function () {
$.get(obj.href, function (data) {
alert(data); // i checked ..this return the html page created from the delete action
window.open (data); // not the right approach ???
});
})
.no(function () {
alert("no");
result = false;
});
return false;
}
The delete action in my controller
public ActionResult DeleteFile(int id)
{
FileUpload f = db.FileUploads.Find(id);
try
{
FileInfo dfile = new FileInfo(f.fileUrl);
if (dfile.Exists) { dfile.Delete(); }
fileUrl = f.FileUrl.Replace("Images/Uploads", "Images/Thumbnails");
FileInfo thumbnail= new FileInfo(fileUrl);
if (thumbnail.Exists) { thumbnail.Delete(); }
db.FileUploads.Remove(f);
db.SaveChanges();
}
catch (Exception ex)
{
}
return RedirectToAction("Index"); // or may i should return something else to make it work in javascript ???
}
Hope you guys can help me. I've been searching and trying for days to come to this level and I feel its time get some help. Just a little bit more. Almost there.
Ajax calls stay in the same page, so calling return RedirectToAction("Index"); is pointless (it will not redirect). In any case it is unnecessary to return the new view. Instead you can just remove the existing elements from the DOM if the controller successfully deleted the item. You have not shown your view, but assuming you have a table where a row might be something like
<tr>
<td>the name of the file</td>
<td>the delete link</td>
</td>
Then you can use the following where the 'delete' link is
<td><button type="button" class="delete" data-id="#item.Id">Delete</button></td>
The key points are the class and the data-id attributes - modify the rest to suit your display but remove the onclick attribute (stop polluting you markup with behavior and use unobtrusive javascript - its the 21st century!)
Then the script
var url = '#Url.Action("DeleteFile")';
$('.delete').click(function() {
var id = $(this).data('id');
var row = $(this).closest('tr'); // modify if the containing element is not a <tr>
w2confirm("Are sure to delete this file ?")
.yes(function () {
$.post(url, { id: id }, function(response) { // its a POST, not a GET!
if (response) {
row.remove(); // remove the row
} else {
// Oops, something went wrong
}
}).fail(function (response) {
// Oops, something went wrong
});
})
.no(function() {
alert("no");
});
});
Note if your using jquery version 1.9+ then the else block in the $.post() functuion is not required since return Json(null); in the method below will go to the .fail() callback
Then in the controller, return json to indicate the item was successfully deleted
[HttpPost]
public ActionResult DeleteFile(int id)
{
FileUpload f = db.FileUploads.Find(id);
try
{
....
db.SaveChanges();
return Json(true); // signal success
}
catch (Exception ex)
{
return Json(null); // signal failure
}
}

How to create log-out script - Parse (JavaScript)

I'm having a problem with logging out on my website. I have looked at the documentation on the parse website but it does not really provide much detail on how to log out the user, also does not help when I am not proficient with JavaScript.
When I click my log out button, it just refreshes the page and nothing more but I would like to take it back to the sign in screen.
My current script file that I have written is shown below (for obvious reasons I have removed my parse unique ids):
$(function() {
Parse.$ = jQuery;
Parse.initialize("MY CODE HERE", "MY CODE HERE");
$('.form-logout').on('submit', function(e) {
// Prevent Default Submit Event
e.preventDefault();
//logout current user
var currentUser = Parse.User.current();
if (currentUser) {
Parse.User.logout();
window.location="Sign_In.html";
} else {
window.location="Sign_In.html";
}
});
});
The section where I create the button is located here in my html file:
<form class="form-logout" role="form">
<input type="submit" value="Logout" id="logout" class="btn btn-primary btn-lg">
</form>
Add
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://www.parsecdn.com/js/parse-1.4.2.min.js"></script>
to your page.
Then use this script:
jQuery(document).ready(function() {
Parse.$ = jQuery;
Parse.initialize("...", "...");
$('.form-logout').on('submit', function (e) {
// Prevent Default Submit Event
e.preventDefault();
console.log("Performing submit");
//logout current user
if ( Parse.User.current() ) {
Parse.User.logOut();
// check if really logged out
if (Parse.User.current())
console.log("Failed to log out!");
}
// do redirect
//window.location.replace("Sign_In.html");
// or
window.location.href = "/Sign_In.html";
});
});
create a function
const handleLogout = () => {
window.localStorage.clear();
window.location.reload(true);
window.location.replace('/');
};
then call it in this way
<Button className="button" onClick={() => handleLogout()}>
<i className="fas fa-power-off"></i>
</Button>
You can self-execute a custom callback function on the logout() object.
That is you first wrap your logout() function within an anonymous function, a syntax like:
function(){logout()}
You self execute it:
(function(){
logout()
})()
and you pass your callback as parameter!
(function(aFunctionIsToBePassedHere){
logout()
})(myCallbackFunction())
All of this become:
function logout() {
(function(myCallbackGoesHereAsVariable) {
Parse.User.logOut();
})(myFunctionToShowTheLoginScreen())
}
and then you bind the logout() function to your form.

QUnit Testing Test Case

How would a test method look in QUnit if I am testing validation functions written for a form? Say, if the form needs to check for name field not being null and my function that tests this functionality looks like
function validNameCheck(form)
{
if (document.forms["formSecond"]["nameFull"].value=="")
{
alert("Name Field cannot be empty")
return false;
}
else
return true;
}
What would be a possible QUnit test case for the above?
Lets say that the parameter you are passing to the validNameCheck function is the name element in a form that you want to check if is empty or not, I mean something like this:
var myName = document.forms["formSecond"]["nameFull"];
Then your function should look like this:
function validNameCheck(form){
if (form.value==""){
alert("Name Field cannot be empty")
return false;
}else{
return true;
}
}
Note that I'd change the hardcoded element that you were checking.
Then your QUnit test should look like this:
QUnit.test( "CheckingName", function( assert ) {
var value = false;
assert.equal( value, validNameCheck(myName), "We expect the return to be false" );
});
I would take #Gepser's solution a bit further (although it is certainly part of the solution). If you want to grab the form by it's name, then you probably want to use QUnit's fixture for resetting HTML before each test. Then you might want to mock out the alert method so that you don't get a bunch of them while you're testing.
In the QUnit HTML file:
<body>
<div id="qunit"></div>
<div id="qunit-fixture">
<!-- Anything in here gets reset before each test -->
<form name="formSecond">
<input type="text" name="nameFull">
</form>
</div>
...
</body>
Then in your QUnit tests (either in that HTML file our in their own JS file):
QUnit.begin(function() {
// mock out the alert method to test that it was called without actually getting an alert
window.alert = function() {
window.alert.called++;
};
window.alert.called = 0;
});
QUnit.testDone(function() {
// reset the alert called count after each test
window.alert.called = 0;
});
...
// From #Gepser's answer...
QUnit.test( "CheckingName", function( assert ) {
var value = false;
assert.equal( value, validNameCheck(), "We expect the return to be false" );
// add an assertion to make sure alert was called
assert.equal( 1, window.alert.called, "alert was called only once" );
});

How to submit data from new page to older page

I got a Button on HTML form (let's call it Form_A) which when clicked, opens a new window (let's call it Form_B).
When user fill in some information in Form_B form and hit submit (or just a button), I need to send some processed information back to 'Form_A' and close 'Form_B.'
How can I accomplish it?
This is best illustrated with an example. In the code of Form_A:
<div id="target"></div> <button onclick="window.open('form_b.html'); return false">Open Form B</button>
function receive_data (value)
{
$("#target").text(value);
}
In the code of Form_B:
<input type="button" onclick="window.opener.receive_data('hello'); window.close();">
You can do it using localStorage, like:
<!--FormB-->
<input type="submit" onclick="processInfo();" />
and in your javascript code:
function processInfo(){
//process your information then
//let's day you have 2 variables as a result of your process
var info1 = "My Information 1";
var info2 = "My Information 2";
localStorage.setItem("info1", info1);
localStorage.setItem("info2", info2);
}
then in your code on the next page get your variables whenever you wanted like:
function getInfo1(){
return localStorage.getItem("info1");
}
function getInfo2(){
return localStorage.getItem("info2");
}
and the other solution for ancient browsers is using window.opener, you can use it in your close function like this:
<!--FormB-->
<input type="button" onclick="closeWindow();" />
javascript code:
function closeWindow(){
//process your information then
//let's day you have 2 variables as a result of your process
var info1 = "My Information 1";
var info2 = "My Information 2";
window.opener._info1 = info1;
window.opener._info2 = info2;
window.close();
}
then you can get them in the main page like:
function getInfo1(){
return window._info1;
}
function getInfo2(){
return window._info2;
}
BTW, we usually use _ when we want to simulate private variable, whereas they are not really private.

How do I create a web link inside a javascript function and pass cell value as a parameter to servlet?

I am creating a table dynamically with JavaScript as you can see below. I want users to be able to click on the first column value and pass the value of the cell as a parameter to a J#EE servlet. Can you help me? Basically the first column should be links to a new page with a country details. How can I do that? Thank you.
Where do I put the link code?
function oneSecondFunction() {
$.get('DisplayCountries', function(responseJson) {
if (responseJson != null) {
$("#countrytable").find("tr:gt(0)").remove();
var table1 = $("#countrytable");
$.each(responseJson, function(key, value) {
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td>" +
"<td></td><td></td></tr>");
rowNew.children().eq(0).text(value['id']);
rowNew.children().eq(1).text(value['country1']);
rowNew.children().eq(2).text(value['country2']);
rowNew.children().eq(3).text(value['country3']);
rowNew.children().eq(4).text(value['country4']);
rowNew.children().eq(5).text(value['country5']);
rowNew.children().eq(6).text(value['country6']);
rowNew.children().eq(7).text(value['country7']);
rowNew.children().eq(8).text(value['country8']);
rowNew.appendTo(table1);
});
}
});
and here is the link code. I have tried several options and it doesn't work.
id
First, assign a class to the first <td> something like <td class="linkHolder">.
Then, write a click handler to send ajax request to servlet:
$('#countrytable').on('click', '.linkHolder', function() {
var link = $(this).html();
$.post('/myservlet', {url: link}, function(response) {
//handle response here
});
return false;
});
You can access the link on the servlet side with the request parameter url

Categories