LinuxQuestions.org
Review your favorite Linux distribution.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 10-02-2022, 02:15 PM   #1
pizzipie
Member
 
Registered: Jun 2005
Location: Hayden, ID
Distribution: Ubuntu 20.04
Posts: 441

Rep: Reputation: 12
Javascript <scripts> not working when called from program


Hi,
I think pictures will describe my problem best Sooo:

If I run my program file contactQueries.html like so:

http://localhost/DBases.com/Dbmysql/...ctQueries.html from firefox address line I get this result: QueryBox.png

If I run my program file dbConnect.html which makes an function call function getTblChoice(data) { which in turn makes an AJAX call to the file contactQueries.html I get this result: Qbox.png.

Thanks for any help in solving this.

Code:
function getTblChoice(data) { 

dbase=data.pop(data); // get last element, dbase, to pass to query function

	$('#dbsbox').show();
	$('#dbsbox').append($("<h4>Choose a Table</h4>"))  // Header
     			 .append("<select id='selbox' name='selbox' size='5'></select>");  // Select Box
    for (const val of data) {
    	$('#selbox').append($("<option>").prop({ value: val, text: val })); // Options
    } // for
    $('#dbsbox').append("<br><br>"); 
    
	 $("#selbox").on('click', function () {                       // pick choice
			myselection=$("#selbox option:selected").text();  
			$('#dbsbox').empty();  //.hide();
				
	 var request = $.ajax({ 
   	 url: "contactQueries.html",    // create phpmyadmin style query box   	 
   	 type:"GET",
   	 data: {"dbase":dbase, "table":myselection}
    	 //dataType: "json" doesn't need to return anything 
  }); // request
 
}); // click
				  	 	 
} // end getTblChoice()
// ============ Here is the code for contactQueries.html: ============

Code:
<!DOCTYPE html>

<html>

<head>

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
	
<title>Create phpadmin() style SQL box - using dynamic html creation </title>
<!-- Tue Sep 13 2022 16:45 -->
<!-- Sun Oct 2 2022 10:09 -->

<!-- ============== styles  ================ -->

<link rel="stylesheet " type="text/css" href="css/query.css" />
<link rel="stylesheet " type="text/css" href="css/contact.css" />

<!--  <link rel="stylesheet " type="text/css" href="css/polly.css" />  -->

<!-- ============== scripts1 ================ -->

<script  type="text/javascript" src="../../jquery/jquery-3.2.0.js"></script>
<script type="text/javascript" src="js/insertAtCaret.js"></script>
<script type="text/javascript" src="js/connect.js"></script>
<script type="text/javascript" src="js/showTable.js"></script>

</head>
	
<body>  
<!-- =============== html  ================== -->


<div class="controls">
	<button type="button" class='hov' id="bak">Go Back</button>       <!--line 70-->
	<button type="button" class='hov' id="contact">View More</button>           	
  	<button type="button" class='hov' id="qmore">Another Query</button>
 	<button type="button" class='hov' id="qsave">Save Query</button>
  	<button type="button" class='hov' id="qget">Get Query</button>	
  	<button type="button" class='hov' id="qdel">Delete Query</button>		 	 			
</div>

<div id="tblcontrol">

</div>

<div id="div1">

    <div id='list'>
        <!--This is where the list of MySql database fields goes.-->
    </div>
    
</div>

<div id='sql'>   <!-- <textarea w/default query-->  
    <textarea  id="thesql" rows='4' cols='950' >SELECT * FROM `cdata` WHERE 1;</textarea> 
      
</div>

<div id='sqlcontrols' class='hov'>
        <!--This is where the MySql Control buttons go.-->    
</div> 

<div id='namebox'>

</div>

<div id="ajaxbox">

</div>



<!-- =============== scripts2  Controls ================ -->

<script type="text/javascript">

alert("Line 77: You are In contractQueries.html ")


//  ==========  #bak   #contact  #qmore  #qsave  #qget  #qdel  #list =========

$('#bak').click(function() {window.location.href='./contactQueries.html'});    // changed ######
$('#contact').click(function() {window.location.href='./contactConnect.html'});// from contacts
$('#qsave').click(function() {	          
    var qName=window.prompt("Enter a name for the query","");
	localStorage.setItem(qName,  $('textarea').val());
});

$('#qget').click(function() {
          
	$("#list").empty();
	$("#list").append("<ui></ui>");
	$("#list").prepend("<p>Chose Your Query</p>");
 
 /*   
    for(var i in localStorage)
{
    console.log(localStorage[i]);
}
    
*/
         		
	for(var i=0; i<localStorage.length; i++) {
		var x=localStorage.key(i);
		if(x=="null") {
			localStorage.removeItem(x);
			continue;
		}
		qNames[i]=localStorage.key(i);     		    
	}
	$.each(qNames, function(i, names) {        		       
		$("ui").append("<li class='disp'>"+names+"</li>");      
	});
     			
    $('.disp').click(function() {
    	$('textarea').val(localStorage.getItem($(this).text()));
	});
	
});

$('#qdel').click(function() {
          
	$("#list").empty();
	$("#list").append("<ui></ui>");
	$("#list").prepend("<p>Delete Query</p>");
          		
	for(var i=0; i<localStorage.length; i++) {
		var x=localStorage.key(i);
		if(x=="null") {
			localStorage.removeItem(x);
			continue;
		}
		qNames[i]=localStorage.key(i);     		    
	}
	$.each(qNames, function(i, names) {        		       
		$("ui").append("<li class='disp'>"+names+"</li>");      
	});
     			
    $('.disp').click(function() {
    	var qChoice=window.confirm("Delete This Query","");
    	if(qChoice) {
    	    localStorage.removeItem($(this).text());	
    	    $('textarea').val("");
    	}
   	});
	
});
</script>
	

<!-- =============== scripts3 ================ -->

	<script type="text/javascript" >  // create the list of database fields and control QueryButtons

    // var fields declared in connect.js
    
    $("#list").append($('<ul></ul>'));
    $('ul').append("<li class='disp'>All</li>");
  
//alert("fields "+fields[1]);  
  
     $.each(fields, function(i, fields) {   
        $("ul").append("<li class='disp'>"+fields+"</li>");      
     });
     
      // var QueryButtons declared in connect.js  		
        
    $.each(QueryButton, function(i, button) {
    $("#sqlcontrols").append("<button type='button' class='sqlcontrols hov'>"+button+"</button>");     		
    });    		
        		      
</script>

<script type="text/javascript" >  // insert MySql elements in <textarea> to create the query

$("button.sqlcontrols").click(function() {

    var table=" `cdata` ";
    var choice = $(this).text();
	   
      switch (choice) {           
          case 'FROM':
            choice=' FROM '+table;  
            insert(choice);            
            break;        
          case 'INSERT':
            choice='INSERT INTO '+table+'(`id`, ) VALUE("", );';              
            insert(choice);          
            break;
          case 'UPDATE':
            choice='UPDATE '+table+' SET '  
            insert(choice);            
            break;
          case 'DELETE':
            choice='DELETE FROM '+table+' WHERE ' 
            insert(choice);            
            break;          
          case 'Clear':
            $('textarea').val('');           
            break;     	
          case 'Execute Query':
	           var query=$('textarea').val();
	           var semiColon=/;$/;             // reg expression - is semi-colon last char
	           if(!semiColon.test(query)) {    // test for semi-Colon and if none add it 
	               query=query+";";
	           }
	       //document.writeln(query);    
			//console.log(query);	           
	           
	         	    getQuery(query); 
	         	    break; 
          default:
            if(choice=="Execute Query") break;
            if(choice != "%") choice=choice+" ";  
            insert(choice);            
            break;	                      
	   } // switch
}); // click

    // var fields declared in connect.js
  //var fields="`Name_ID`, `married`, `spouse`, `address`, `city`, `state`, `zip`, `phone`,`email` ";	
 	
 $('.disp').click(function() {

    	var choice = "`"+$(this).text()+"` ";   
    	if(choice=="`All` ") {
    	    choice="";
    	 	for(var i=0; i<(fields.length)-1; i++) {
    	 		choice+="`"+fields[i]+"`,"; 
    	 	}
    	 choice+="`"+fields[i]+"`";	// last choice no , 	
    	}

    insert(choice);
 });
 	  
	 function insert(choice) {
	 	 $('#thesql').insertAtCaret(choice); // in the file insertAtCaret.js
	 }

    function getQuery(query) {
   		$.ajax({
				type: "POST",
				url: "contactQueries.php",
				data: {"query":query},			
				success: showTable            // function showTable in showTable.js                          
		}); // ajax

}	 	 
</script>


</body>
</html>
Attached Thumbnails
Click image for larger version

Name:	QueryBox.png
Views:	12
Size:	28.3 KB
ID:	39654   Click image for larger version

Name:	Qbox.png
Views:	10
Size:	35.2 KB
ID:	39655  
 
Old 10-02-2022, 06:19 PM   #2
astrogeek
Moderator
 
Registered: Oct 2008
Distribution: Slackware [64]-X.{0|1|2|37|-current} ::12<=X<=15, FreeBSD_12{.0|.1}
Posts: 6,269
Blog Entries: 24

Rep: Reputation: 4206Reputation: 4206Reputation: 4206Reputation: 4206Reputation: 4206Reputation: 4206Reputation: 4206Reputation: 4206Reputation: 4206Reputation: 4206Reputation: 4206
First, this question is obviously related to your previous thread, whether or not it is the exact same problem. It is helpful to others to keep related items together in the same thread so that others can follow the discussion and avoid repeating the same advice already offered and understand why it may have not solved the problem. Let's leave them separate until we see where this one leads, but please refrain from opening new threads for the same or closely related questions.

OK, as for the screenshots you provided, without telling us what you were expecting and how that differs from what you saw, they are not of any help to anyone else.

With an ajax request somewhere between the start and finish states and no explanation of just what it should return, all we can susggest is that you verify each piece of the puzzle separately and hope that you find what is missing.

Questions you need to provide answers for (for yourself as well as others):

* Are the request parameters being sent and recevied by the ajax target as expected? If unsure, have the target log the received requests to a file (easy to do with PHP).
* Is the ajax response correct, and correctly formatted as a JSON object? Again, log it on the server side (to a file) and again when received (alert box).
* Your comments state that the function doesn't need to return anything, why? What becomes of the response? Is there a callback we do not see? What, e-x-a-c-t-l-y is the expected sequence of events and state of the data through that process?

Again, write down explicitly the steps in that process, then veify them one by one until you find something unexpected or realize that your code as written, may not perform the intended function.

Last edited by astrogeek; 10-02-2022 at 06:21 PM.
 
1 members found this post helpful.
Old 10-03-2022, 11:36 PM   #3
astrogeek
Moderator
 
Registered: Oct 2008
Distribution: Slackware [64]-X.{0|1|2|37|-current} ::12<=X<=15, FreeBSD_12{.0|.1}
Posts: 6,269
Blog Entries: 24

Rep: Reputation: 4206Reputation: 4206Reputation: 4206Reputation: 4206Reputation: 4206Reputation: 4206Reputation: 4206Reputation: 4206Reputation: 4206Reputation: 4206Reputation: 4206
Revisiting this thread after a day I still do not understand what you think is wrong with the ajax result.

Is it the appearance of the returned HTML, colors and other style elements? If so then consider that your styling selectors, CSS, may include a parent child relationship which may be different for the ajax response depending on how/where it is written into the page. Or the page making the ajax request may not load a stylesheet present in the other context.

Too much ambiguity. Please be more specific about the nature of the problem.
 
Old 10-05-2022, 05:36 PM   #4
pizzipie
Member
 
Registered: Jun 2005
Location: Hayden, ID
Distribution: Ubuntu 20.04
Posts: 441

Original Poster
Rep: Reputation: 12
Thanks astrogeek,

Quote:
Too much ambiguity. Please be more specific about the nature of the problem.
Referring to the images below: You see the Database Select box, 'Selection_030'. I select a database and you now see the Table Select box, 'Selection_031'. When I click on a Table selection what you are supposed to see is the Query box 'Selection_029'. The 'dbase' and 'table' variables are passed to this program so you are able to query any database/table combination in the MySql database. Once you are done with the query that script will take you back to the front end menu therefore you don't need any return from the ajax request..

The code that I thought would do this is :

Code:
function getTblChoice(data) { 

dbase=data.pop(data); // get last element, dbase, to pass to query function

	$('#dbsbox').show();
	$('#dbsbox').append($("<h4>Choose a Table</h4>"))  // Header
     			 .append("<select id='selbox' name='selbox' size='5'></select>");  // Select Box
    for (const val of data) {
    	$('#selbox').append($("<option>").prop({ value: val, text: val })); // Options
    } // for
    $('#dbsbox').append("<br><br>"); 
    
	 $("#selbox").on('click', function () {                       // pick choice
			myselection=$("#selbox option:selected").text();  
			$('#dbsbox').empty();  //.hide();
				
	 var request = $.ajax({ 
   	 url: "contactQueries.html",    // create phpmyadmin style query box   	 
   	 type:"GET",
   	 data: {"dbase":dbase, "table":myselection},
         dataType: "text" // I'll pass a message back maybe 
  }); // request
 
/* The code to select the dbase is similar to this except that the ajax request
 is to contactQueries.html. The fix to my last thread was to put the code beloe inside the $("#selbox").on('click', function () {;   

Code:
	 var request = $.ajax({
   	 url: "getTbls.php",
   	 type:"GET",
   	 data: {"dbase":myselection},
    	 dataType: "json" 
  }); // request

request.done(function (data) {
	
        getTblChoice(data);
});
*/
}); // click } // end getTblChoice()
Attached Thumbnails
Click image for larger version

Name:	Selection_029.png
Views:	5
Size:	55.0 KB
ID:	39679   Click image for larger version

Name:	Selection_030.png
Views:	4
Size:	46.4 KB
ID:	39680   Click image for larger version

Name:	Selection_031.png
Views:	4
Size:	47.5 KB
ID:	39681  
 
Old 10-05-2022, 07:30 PM   #5
pizzipie
Member
 
Registered: Jun 2005
Location: Hayden, ID
Distribution: Ubuntu 20.04
Posts: 441

Original Poster
Rep: Reputation: 12
I think the problem is in contactsQuery.html. Web Developer Tools show that contactsQuery.html is being called and $_GETS is passing the dbase and table variables to it. It appears the HTML code is run but the <script> code is not see 'Selection_032.png'.

R
Attached Thumbnails
Click image for larger version

Name:	Selection_032.png
Views:	5
Size:	97.7 KB
ID:	39682  
 
Old 10-07-2022, 05:37 PM   #6
pizzipie
Member
 
Registered: Jun 2005
Location: Hayden, ID
Distribution: Ubuntu 20.04
Posts: 441

Original Poster
Rep: Reputation: 12
OK, I've tried to make a simple program which exhibits the same sort of result as contactsQuery.html. As suggested, I have put this post in the same Thread as previous. Output: look at attachment. I'm sure this is some simple thing but I just can't put my finger on it.

R

global_Init.php

Code:
<!DOCTYPE html>

<html>

<head>

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Create phpadmin() style SQL box - using dynamic html creation </title>
<script type="text/javascript" src="../../jquery/jquery-3.2.0.js"></script>

</head>


<body>

    THIS SHOWS UP ON THE SCREEN  -  Hello world! - FROM global_Init.php
  
  
<script type="text/javascript" >
var dbase="contacts";
var myselection="cdata";

		var request = $.ajax({ 
   	 url: "globalQ.php",    // contactQueries.html - create phpmyadmin style query box   	 
   	 type:"GET",
   	 data: {"dbase":dbase, "table":myselection},
    	 dataType: "text"  
  }); // request

 request.done(function (data) {
	alert(data);

}) //request.done


</script>

</body>



</html>
globalQ.php

Code:
<?php

//set_include_path( '../include' );
error_reporting(E_ALL);
ini_set("display_errors", true);
ini_set('html_errors', 'On');

//include "myPhpFunctions.inc";

$db=$_GET['dbase']; // from dbConnect.html
$table=$_GET['table'];

?>

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Create phpadmin() style SQL box - using dynamic html creation </title>

<script type="text/javascript" >
	var dbase=<?php echo $db; ?>;     // note this works see OUTPUT
	var table=<?php echo $table; ?>;  // ditto
	alert("Dbase: "+dbase+"Table: "+table);
</script>
</head>
<body>
  THIS SHOWS UP IN AN ALERT from Localhost containing all the code of this script.
</body>
</html>
Attached Thumbnails
Click image for larger version

Name:	Selection_033.png
Views:	9
Size:	40.3 KB
ID:	39687  

Last edited by pizzipie; 10-07-2022 at 05:44 PM. Reason: typo's
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
[SOLVED] Why does this bash script work if called from the command line but not when called from a php script run by a webpage? KenHorse Linux - General 10 08-23-2021 05:39 AM
JavaScript function disappears after getting called for once mohtasham1983 Programming 2 02-23-2021 11:15 PM
Trying to use a program called "SQUID" as a Website Blocker - why not working? Is it even possible? mike4ty4 Linux - Networking 2 08-30-2018 05:57 AM
[SOLVED] Destructor called on objects in deque without it being called explicitly Snark1994 Programming 4 07-13-2011 08:05 AM
shell scripts ...--can it be called with in a c program narendra.pant Linux - Newbie 2 08-17-2006 07:43 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 06:00 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration