CodeRed-Alpha Posted April 18, 2023 Share Posted April 18, 2023 (edited) Good day all, I have a function that does not work when implemented onto my app. The function works fine by itself and I verified the action takes place if I just call the function with appropriate arguments. The issue I am having is that the checkbox is being created dynamically and the output of it comes from another page which is included on this page. So... On file called Benefits.php I have a function What I want to happen: When checkbox is clicked, it kicks up a MySQL update query to place 1s in any column with the checkbox checked. I am focused on trying to get this to execute just one at time to verify its function. Benefits.php function Set_Checks($Data_Connect, $user, $step) { if (!mysqli_error($Data_Connect)) { $upd_qry = "UPDATE `Benefits_Steps` SET `Step_".$step."_Check`='1' WHERE `Username` ='".$user."'"; if (!$Data_Connect) { die("Connection failed: " . mysqli_connect_error()); } if (mysqli_query($Data_Connect, $upd_qry)) { header('Location: Benefits.php'); } else { echo "Error updating record: " . mysqli_error($Data_Connect); } } } Based on the output conditions this page generates a package and assigned to a variable on a page called Page_components.php Object generating the actual Checkbox and rest of row data coming from Page_Components.php 'Benefits_Module'=>'<article class="benefits_module %s"><div class="module_information"><div class="task_number"><img src="images/icons/%s" alt="%s"></div><div class="task_instructions">%s</div><div class="benefits_task"><input type="checkbox" id="%s" name="%s" onclick="%s" value="%s"%s><label for="%s"></label></div></div><section class="module_admin_edit"></section></article>', Finally, the while statement producing the arguments/variables for the output are like this. Generated from Benefits.php $Insurance_Task.=sprintf($Page_Bones['Benefits_Module'], $insurance_data['Class_Marker'], $insurance_data['Task_Image_Link'], $insurance_data['Task_Image_Alt'], $insurance_data['Task_Message'].$insurance_data['Task_Links'], 'Benefits_Task_'.$insurance_data['Benefits_Task_Id'], $insurance_data['Task_Name'], 'Set_Checks($Data_Connect, '.$usrname.', '.$stepcount.')', '', ${"Task_Checked_" . $stepcount}, 'Benefits_Task_'.$insurance_data['Benefits_Task_Id']); All of this is being displayed and marked up on page Benefits.php Ultimately this is the error I keep receiving. nefits.php:49 Uncaught ReferenceError: Set_Checks is not defined at HTMLInputElement.onclick (Benefits.php:49:1969) onclick @ Benefits.php:49 As I watch the variables, they are producing the right output into the statement. however, I am thinking it is the way that I am trying to handle my connection string that is does not like? I know it is alot easier to all this from a single page, but this is the workflow here and I cannot change it without potentially ruining other stuff. Is my syntax just wrong? Is my approach wrong? I should note that the arguments being passed coming from that package string are 'Set_Checks($Data_Connect, '.$usrname.', '.$stepcount.')' And it is obiously trying to kick off SET_CHECKS() Edited April 18, 2023 by CodeRed-Alpha Quote Link to comment https://forums.phpfreaks.com/topic/316153-running-php-function-from-onclick-action-not-working/ Share on other sites More sharing options...
kicken Posted April 18, 2023 Share Posted April 18, 2023 46 minutes ago, CodeRed-Alpha said: Is my approach wrong? Yes. Your falling afoul of the common misunderstanding of the line between JavaScript and PHP. onclick and any other such user-interaction mechanism are in the realm of JavaScript, not PHP. JavaScript cannot directly call a PHP function, they are two completely separate things. What JavaScript can do is make a web request to a PHP file, which then calls your PHP function to do whatever needs done. You need modify your onclick handler to call a JavaScript function which will issue a web request to a PHP script with any information required. That PHP then needs to take that information and call your PHP function. Quote Link to comment https://forums.phpfreaks.com/topic/316153-running-php-function-from-onclick-action-not-working/#findComment-1607429 Share on other sites More sharing options...
CodeRed-Alpha Posted April 18, 2023 Author Share Posted April 18, 2023 I am realizing now that the checkbox htmlk is run through javascript. So I know I have to call the php update function from a javascript function. However my rust with js is evident at this point. Here is what I have so far. function Set_Checks($Data_Connect, $user, $step) { if (!mysqli_error($Data_Connect)) { $upd_qry = "UPDATE `Benefits_Steps` SET `Step_".$step."_Check`='1' WHERE `Username` ='".$user."'"; if (!$Data_Connect) { die("Connection failed: " . mysqli_connect_error()); } if (mysqli_query($Data_Connect, $upd_qry)) { header('Location: Benefits.php'); } else { echo "Error updating record: " . mysqli_error($Data_Connect); } } } <script language="javascript> function Update_Checks(con, user, step) { var stepname = "<?php echo $stepcount ?>"; document.getElementById("Benefits_Task_").innerHTML = "<?php Set_Checks($Data_Connect, $usrname, $stepcount); ?>"; </script> Quote Link to comment https://forums.phpfreaks.com/topic/316153-running-php-function-from-onclick-action-not-working/#findComment-1607435 Share on other sites More sharing options...
Strider64 Posted April 18, 2023 Share Posted April 18, 2023 (edited) 38 minutes ago, CodeRed-Alpha said: I am realizing now that the checkbox htmlk is run through javascript. So I know I have to call the php update function from a javascript function. However my rust with js is evident at this point. Here is what I have so far. function Set_Checks($Data_Connect, $user, $step) { if (!mysqli_error($Data_Connect)) { $upd_qry = "UPDATE `Benefits_Steps` SET `Step_".$step."_Check`='1' WHERE `Username` ='".$user."'"; if (!$Data_Connect) { die("Connection failed: " . mysqli_connect_error()); } if (mysqli_query($Data_Connect, $upd_qry)) { header('Location: Benefits.php'); } else { echo "Error updating record: " . mysqli_error($Data_Connect); } } } <script language="javascript> function Update_Checks(con, user, step) { var stepname = "<?php echo $stepcount ?>"; document.getElementById("Benefits_Task_").innerHTML = "<?php Set_Checks($Data_Connect, $usrname, $stepcount); ?>"; </script> You missing the point - JavaScript is Client Side and PHP is Server Side. 38 minutes ago, CodeRed-Alpha said: Quote JavaScript is a client-side scripting language that runs in the browser on the client-side (i.e., the user's device). It is used to create interactive web applications and dynamic user interfaces. JavaScript code is executed in the browser and can manipulate the web page's content, styling, and behavior in response to user actions. On the other hand, PHP is a server-side scripting language that runs on the web server. It is used to generate dynamic web pages, handle forms, manage databases, and perform various server-side tasks. When a user requests a web page that contains PHP code, the server processes the code and generates an HTML output that is sent to the client's browser for display. In summary, the key difference between JavaScript and PHP is that JavaScript is executed in the client's browser, whereas PHP is executed on the server. JavaScript is mainly used to create interactive client-side web applications, while PHP is mainly used to handle server-side tasks, such as generating dynamic web pages and processing user input. You need to use AJAX or FETCH have communication between the two. Example: // Add an event listener to the edit form's submit event editForm.addEventListener("submit", async function(event) { // Prevent the default form submit behavior event.preventDefault(); // Create a FormData object from the edit form const formData = new FormData(editForm); console.log("form data", formData); // Send a POST request to the update_question.php endpoint with the form data const response = await fetch("update_question.php", { method: "POST", body: formData, }); // Check if the request was successful if (response.ok) { const result = await response.json(); console.log(result); // If the response has a "success" property and its value is true, clear the form if (result.success) { const searchTerm = document.getElementById("searchTerm").value; await displayRecord(searchTerm); } } else { console.error( "Error submitting the form:", response.status, response.statusText ); // Handle error response } }); }); Edited April 18, 2023 by Strider64 Quote Link to comment https://forums.phpfreaks.com/topic/316153-running-php-function-from-onclick-action-not-working/#findComment-1607439 Share on other sites More sharing options...
kicken Posted April 18, 2023 Share Posted April 18, 2023 (edited) 54 minutes ago, CodeRed-Alpha said: function Update_Checks(con, user, step) { var stepname = "<?php echo $stepcount ?>"; document.getElementById("Benefits_Task_").innerHTML = "<?php Set_Checks($Data_Connect, $usrname, $stepcount); ?>"; You can't just stick your PHP code into a JavaScript function like that. By the time your page is rendered in the browser and JavaScript can start doing it's thing, PHP is done. There's no going back for that request. If you want to do more PHP stuff, you have to make a new request in some way, such as via a redirect, a form post, or a background request with fetch(). That new request needs to include whatever information your script will need to perform the appropriate action. A good way to pass this information along is with data attributes on your HTML elements. Here is a quick example of making a request and taking some action according to the response. fetch('/the/url/to/request', {method: 'post', body: 'the content to send'}).then(function(response){ //Check if the response is successful. if (response.ok){ //Decode JSON body of the response. return response.json(); } else { throw new Error(response.statusText); } }).then(function(data){ //Consume the JSON response data to do something if (data.complete){ e.target.disabled = true; } }, function(err){ //Handle any errors. alert('Failed to make request.'); }); When you have your JS making a request on click, then you just need to develop a PHP page for that request to go to. That page will take the data in and call your Set_Checks function. Edited April 18, 2023 by kicken Quote Link to comment https://forums.phpfreaks.com/topic/316153-running-php-function-from-onclick-action-not-working/#findComment-1607440 Share on other sites More sharing options...
CodeRed-Alpha Posted April 19, 2023 Author Share Posted April 19, 2023 Thank you. I have never tried to invoke a PHP function from JavaScript before like this. I rarely packaged things up into JS Json in the past most of my work work used direct PHP output or I was getting my data from an API prebuilt. Quote Link to comment https://forums.phpfreaks.com/topic/316153-running-php-function-from-onclick-action-not-working/#findComment-1607466 Share on other sites More sharing options...
CodeRed-Alpha Posted April 20, 2023 Author Share Posted April 20, 2023 (edited) Ok, So my PHP MySQL update is working fine. If I set the values manually. We don't use GET variables. Error Uncaught TypeError: Cannot set properties of null (setting 'innerHTML') function updateBeneData(step, val){ let benefits_form=new FormData(); benefits_form.append('STEP', step); benefits_form.append('VAL', val); let update_benefits=new XMLHttpRequest(); update_benefits.onreadystatechange=function (){ if (update_benefits.readyState===4 && update_benefits.status===200){ document.getElementById(step).innerHTML=update_benefits.responseText; } } update_benefits.open('POST', 'scripts/Update_Benefits.php', true); update_benefits.send(benefits_form); } Really all I want to do is call 'Update_Benefits.php' from my onlick but I need to pass 2 variables through a POST method in my onClick. my onlcick currently looks like this. onlick="updateBeneData(1, 1)" Obviously i am overlooking something very straight forward. Edited April 20, 2023 by CodeRed-Alpha Quote Link to comment https://forums.phpfreaks.com/topic/316153-running-php-function-from-onclick-action-not-working/#findComment-1607539 Share on other sites More sharing options...
kicken Posted April 20, 2023 Share Posted April 20, 2023 32 minutes ago, CodeRed-Alpha said: document.getElementById(step) That is going to be looking for some element with id="1", since step is equal to 1 according to you. Since it's not finding one (the cause of your null error), you must not have any such element in your HTML. You need to make sure you are searching for the correct ID value, or reference the element some other way. Quote Link to comment https://forums.phpfreaks.com/topic/316153-running-php-function-from-onclick-action-not-working/#findComment-1607541 Share on other sites More sharing options...
CodeRed-Alpha Posted May 5, 2023 Author Share Posted May 5, 2023 I ended up packaging my form data up into a single string package. JSON encoding it and then JSON decoding it on the SQL SELECT query return of data. ISo I am having a SIMILAR issue but unrelated to the other one and I did not feel like it should be in it's own thread, but we'll see. I am running a sql query that requires the Id of a document or a record to be passed from javascript. The reason I have to do it this way is the same as before. We do not use GET variables here for security purposes so I have to run the delete trigger through an onclick. My javcascript looks like this. function removeNotification(Record_Id){ let remove_request=new FormData(); remove_request.append('REMOVE_NOTIFICATION', Record_Id); let remove_data=new XMLHttpRequest(); remove_data.onreadystatechange=function(){ if (remove_data.readyState===4 && remove_data.status===200){ console.log(Record_Id); } } remove_data.open('POST', 'scripts/Notifications_Delete.php', true); remove_data.send(remove_request); } And my Notifications_Delete.php is trying to get the POST data but I am not receiving the Record ID i am passing. if(isset($_POST['Record_Id'])) { $doc_id = $_POST['Record_Id']; $Queue_Name = 'Documents'; } My doc_id is not being set so I am receiving no POST data from my js. Quote Link to comment https://forums.phpfreaks.com/topic/316153-running-php-function-from-onclick-action-not-working/#findComment-1608098 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.