Function not executing nested with jquery events functions

i have the lines of code below but seem not to be executed when called.

i made function to manage the hide and show jquery function when the elements are triggered by the click events - called showOptDivs and below i have included the function itself. the showOptDivs function executes without a problem at all the problem is the section when i included the function displayings, it seems not executing all … can someone help me know what could be the problem please? as it took me two hours an i could figure out… could it be the nesting of the jquery click events? but the rest of code work except that only? am confused… i am working this for a project. the reason i made the function is so i can simplify in case the structure of the divs are same but need to be replicated… so i thought instead of writing for each div elements i could simplify by using a function, but it is turning to a dead end… help help plz

function displayings(linking) {
    var display = ".displays";
    var dis = "." + linking;
    $(display).has(dis).show();

    $(display).not(dis).hide();

}

function showOptDivs(thelink) {
    // this function takes the name of the link clicked, and confirms it class to view on the page, while hiding the ones not
    var linkcheck = $("#all-options-links a").has(thelink);
    $(".displays").hide();
    //$(thelink).css("background-color":"whitesmoke","color":"black");
    if (linkcheck) {
        var textline = ".trigger";
        var id = $(thelink).attr("id");
        var combine = textline + "-" + id; // this creates a class name of the selected content menu item to match
        $(combine).show(); // show the created class
        var shown = $(combine).show(); // assign the event of showing the selected item to the variable

        // check if the event is successful then hide all trigger which dont have same class though sharing .trigger class 
        if (shown) {
            $(textline).not(combine).hide(); // hide all class which are not selected
            $(combine).addClass(textline); // add the stryle being held with .trigger from css file
            var firstdiv = combine + " div"; // this is to get the child div of the shown div class
            var getdivclassname = $(firstdiv).first().attr("class"); // getting the name of the first div or child of the chosen or shoen div class
            var firstdivname = "." + getdivclassname + " div"; // get the di which is descendant of the chosen class
            var divlinksclass = $(firstdivname).attr("class"); // getting the class of all the links in the selected class of the first div
            var linkforid = "." + divlinksclass; // turning the class name into a class element by adding . 
            var linksholderdiv = "." + linkforid + " a";


            // this i to get rrhe links of each menu item display once displayed, to prompt automtic hiding and showing of the elements 
            $(linksholderdiv).click(function() {
                var clickedlinkid = $(this).attr("id"); // get the link id of the clicked item thenhide and show other elements

                var clickedlinkclass = $(this).attr("class");
                var turnedintoclass = "." + clickedlinkid; // the class for the displaying

                if (displayings(clickedlinkid)) {
                    alert("executed");
                }
                //displayings(clickedlinkid);	
                else {
                    alert("not executed");
                }
            });
        }
    } // end of if statement 
} // end of the showOptDivs

Can you link to a codepen or similar and include the html so it’s easier to see what you’re trying to accomplish?

1 Like

So, in your code, you have this block:

if (displayings(clickedlinkid)) {
   alert("executed");
} //...

So that function runs, and never shows “executed”. Is your question WHY it doesn’t show “executed”? That’s because, in order for that to show, the if(...) expression would have to return a true value. As it returns no value, that if(...) parses that null return as falsy, and never actually does anything.

If you want to use your function like that, have the function return SOMETHING to indicate that it did something.

thank you so much, i fixed it…

got another problem though i really seek your advise and help on the code below.

as i have made a form and am using ajax to submit data collected from the form by jquery into the database, i decided to collect form elements values then create an object with the values, so that i can turn the created object by stringify() function so i can pss the object converted string as a text using the ajax function, and the use php json decode to turn back the string into object in php and then work with it from there to be submitted into database using php… it seems the values are collected without and problem when the submit button is created, the issues comes at creating the object and turning it into a string, can you advise…

below is my code:

$(document).ready(function(){
/// the beginning of the processing of forms for contents submissions

			var referenceAnnouncement  = "#announcement-reference";
			var announcementVisibility = "#announcementVisibility";
			var announcement_description = "#announcement_description";
			var sw_announcement_description = "#sw_announcement_description";
			//var postedby = "#postedby";
			var announcementPriority = "#announcementPriority";
			var submitAnnouncement = "#submitAnnouncement";
			var announcementObj = "#announcementObj";
		/*	
			$(announcementVisibility).change(function{
			var announcementVisibilityValue = $(this).val();// fetch the value of selected report type option vale
			if (announcementVisibilityValue == 1) {
			}	
			else if (announcementVisibilityValue == 2) {// hide the sections of form with the other types of reports
				
			}// end of the if block to check the type of the report 		
	});// end of the report type click event */
	
	
			
		$(submitAnnouncement).click(function() {
		
			var referenceValue = $("#announcement-reference").val();	
			var announcementnameValue = $("#announcement_title").val();
			var sw_announcement_descriptionyValue  = $("#sw_announcement_title").val();
			var categoryValue = $("#announcement_category").val();
			var announcementPriorityValue  = $(announcementPriority).val();
			var announcementVisibilityValue  = $(announcementVisibility).val();
			var announcement_descriptionValue  = $(announcement_description).val();
			var sw_announcement_descriptionValue  = $(sw_announcement_description).val();
			//var announcementpostedby  = $(postedby).val();
			//$(announcementObj).val();
			
			var announcements = {
			name: announcementnameValue,
			jina: sw_announcement_nameValue,
			category: categoryValue,
			kipengele: categoryValue,
			description: announcement_descriptionValue,
			sw_description: sw_announcement_descriptionyValue,
			reference: referenceValue
			};
			
			var announcementObjectString  = JSON.stringify(announcements);
			//$(announcementObj).val(announcementObjectString);	
			alert(announcementObjectString);
			

	/*
		var getData = new FormData();
		getData.append("investment":  getInvestment);
		serverService (get,"POST","php/includes/serverService/submitSubsidiaryA.php", respectedItemOpts);	
		
			//alert(announcementObject);*/
		});

});

It may just be that this line is the problem:

jina: sw_announcement_nameValue,

You have no variable named `sw_announcement_nameValue, so it may be dying on you. I’d suggest opening the console (on most browsers, the F12 key, or ‘Developer tools’). There may be errors showing up there.

Now, purely from a “I really like to avoid confusion” perspective, I would like to offer a suggestion. Some of your variable names and some of your HTML ids are very confusing. There are three different conventions we often use, and you’re using all three:

  • camel case: When the variable or id name is multi-word, the second and all subsequent words are capitalised: announcementNameValue or announcementPriorityValue for example.
  • underscore: Another option in both variables and ids, we can use underscores between words: #sw_announcement_title or announcement_description_value.
  • hyphen: Only within HTML ids, we can hyphenate: #announcement-reference

You not only mix the three throughout, but within a single variable name! You’ve got names like announcement_descriptionValue or sw_announcement_descirptionyValue with underscores and caps randomly. Not only confusing for others, but easy to lose track of yourself.

Personally, I might suggest you create an announcement Object, containing all the jQuery-wrapped DOM nodes:

  var announcement = {
    reference: $("#announcement-reference"),
    title: $("#announcement_title"),
    category: $("#announcement_category"),
    visibility: $("#announcementVisibility"),
    description: $("#announcement-description"),
    swDescription: $("#sw_announcement_description"),
    priority: $("#announcementPriority"),
    submit: $("#submitAnnouncement"),
    
  }

Doing this, I can access any property I want, simply get announcement.name.val() and there it is. So, to create your JSON-able object, you could create a function like this:

var createAnnouncementObj = function(){
  // there's very little processing, but if we did need to do any 
  //   lookups or math conversions, do so before we create the
  //   returned object.
  return {
    name: announcementObj.name.val(),
    jina: announcementObj.name.val(),
    category: announcementObj.category.val(),
    kipengele: announcementObj.category.val(),
    description: announcementObj.description.val(),
    sw_description: announcementObj.swDescription.val(),
    reference: announcementObj.reference.val()
  }
}

…creating a unified and clean way to create that object:

announce.submit.on("click" function() {
  // First, we want to create that announcement object
  var announcements = createAnnouncementObj();
  // and convert it into a string to be sent as a POST body
  var announcementObjectString  = JSON.stringify(announcements);

  // At this point, we have an announcement object converted to a string.
  //  we can save this to localStorage, or we can send it to the back end.
  console.info("My announcement: ",announcementObjectString);
}

Again, not rules – more guidelines.

1 Like

just took time now to go throug your sugeestion, let me try this approach and see hwo it works… will get back to you, thanks so much brother…

Hello snowmonkey,

thank youu so much for the guidelines, i thank you for taking time to type the guidelines… not only have you helped me know how to code better, but even know what to do for future coding works… God bless you and give you more. thank you so much.

hello i have managed to sort the rest of problem i had one thing i dont understand is the object are stringed well with json.stringify(0 but it seems when i pass it through php file, but the response the come is this Notice : Undefined index: info in /opt/lampp/htdocs/nicol/php/includes/serverService/submitInvestment.php on line 10
not info

and copy of the php file i used to test if the object had been passed it as follows:

<?php if (isset($_GET["info"])) { $investmentJSONObj = $_GET["info"]["visibility"]; $investmentObj = json_decode($investmentJSONObj, true); // $visibility = $investmentJSONObj->visibility; echo 'info'. $investmentObj; } else { print_r($_GET["info"]); echo 'not info'; } // //echo $visibility; ?>

could you help? i tried to google and i can see it to use same ways which i have already used but not working, tried using php empty( ) function on the passed post array but it seems it is empty as if no content is being passed… and same ajax function has just worked fine on other programs… can you advice…

So it’s getting from the front-end to the PHP, and the PHP is throwing the error?

Look at that error – it’s saying that, in the $_GET collection of parameters, there is no “info” parameter. Are you passing this as a GET request, or a POST?

i am passing it as post, was trying for get as well…

below is my ajax code
var carryData = new FormData().append(‘info’ ,‘90’ );
serverService(carryData, “POST”,“php/includes/serverService/submitInvestment.php”, “#viewInvestmentResponse”);

and here is how i try to catch it in php file

$investmentJSONObj = “”;
if (isset($_POST[""]) == true) {
$investmentJSONObj = $_POST[""];
// $investmentObj = json_decode($investmentJSONObj, true);
// $visibility = $investmentJSONObj->visibility;
echo ‘info’.$investmentJSONObj;
}
else {
echo ‘not info’;
}

please take note i have used same ajax fuunction and same way to collect the passed ajax data without problem. when i was testing the file passed , in collecting it in the php file. i notice the post array carrying the passed data get passed as empty too, as the name of the post array comes but no value… i have spent hours without success, what could be a solution to this plz help me…

also in another note, i thought perhaps the json stringified would be a problem, i tried assigning a fixed value when sending, as you will see i tried passing 90, to see if i could catch in the php file, but it still brought same error, so i figured it is not the stringified string of json, it is the ajax itself…

so i tried using jquery $.post and $.get, still brought same errors…

php is the one throwing the errors…

try logging $_POST and $_GET in PHP, simply to see if it’s getting any values there.

i did try logging too… it brought empty array

it like the data value being passed is not collected at all when being sent

Which makes me wonder about what is being sent. Can you console.log() the stringified data?

yes i can console the stringified data without any problem. the thing i dont understand is that i used same ajax function in another function and it worked without any problem. even in same click trigger event which calls the ajax function, instead of passing a stringified data, i decided to pass a normal fixed string directly on the function parameter but it brought same error… and the server response is working without a problem, only the php seems to have an empty $_post array passed without its content… is there a way to sort it… am new in programming

Notice : Undefined index: is the error i get

Yes it is. Because the data being passed either ISN’T being passed, or isn’t being parsed.

Out of curiousity, what happens if you var_dump($REQUEST), see what is coming from the front end entirely?

please note: print_r($_POST); returns NULL, and var_dump($REQUEST) returns nothings at all…