Jump to content

button to perform function without reloading the page


Go to solution Solved by maxxd,

Recommended Posts

Hi Everyone

 

I'm pretty new to coding, and I have come across my first page where i need to perform a function, within a bootstrap modal

without refreshing the page, I have looked this up and I'm guessing ajax is what i need.

 

I have never coded Ajax before

 

What i have is a list of "tasks" displayed as alerts within the modal which is created by a while loop within php

In those action bars i have 2 buttons 1 is 'dismiss' (just basically hides the task, which is working) and the 2nd button is 'completed' which needs to perform a function that sets a status of 2 (0 being new, 1 being extended, 2 being completed)  against that note, I dont have a problem performing this, what i need help with is running that function without leaving the page or closing the modal.

 

Any advice or help with implementing Ajax would be greatly appreciated.

 

Thanks 

 

Start here.

 

Basically, you write your php script that validates and sanitizes user-supplied data, runs an update on the database with that data, then prints a JSON-encoded result string - this script is a separate file on the web server from the file you're using to display the task list. On the task list display, you'll set up a .click() event on the completed button that will create the AJAX request, gather the record ID to be updated from the displayed page (usually a data-* attribute on the button), send the data to the php script, then read and parse the return string to see if the process was successful or not.

Hey so i've been reading up on AJAX, i dont "do" those guides so well i usually learn from examples and then can manipulate them until i fully understand it,

Although I can get the AJAX to work as it is displaying the page alert, I cant get its to POST to my php script here's the code below:

 

the AJAX part

<script type="text/javascript">
	
	
	function removeTask() {
      $.ajax({
			url: 'dashboard.php',
			data:{action:'removeTask'},
			type: 'post',
			success:function(output) {
            alert(output);
           }

      });
 }
</script>

The PHP part

<?php
echo "error should be here";

if (isset($_POST['action'])){
echo "try removing this task";
/* will soon be calling the function with this once the echo works
removeTask($TaskName,$taskID);
*/
}
	
?>

Any help would be massively appreciated, I am really work hard to learn as much as i can :)

Hey Thanks for your help maxxd, I have got it working :)

 

any way i could clean this up, or is this acceptable?

 

AJAX script (in dashboard.php)

<script>	
	function removeTask() {
      $.ajax({
			url: '<?php echo Thisurl();?>',
			data:{TaskName: $('#taskName').val(),
				  TaskId: $('#taskId').val()	
			},
			type: 'post',
			success:function(output) {
            alert(output);
           }

      });
 }
</script> 

php (in dashboard.php)

<?php
// This is if AJAX has inputted the post information.
if (isset($_POST['TaskName'])) {
	if (isset($_POST['TaskId'])){
		
$TaskName=$_POST['TaskName'];
$taskID=$_POST['TaskId'];	
//Remove the Task with the correct information
removeTask($TaskName,$taskID);

echo "welldone";
}
}

functions.php (called in my layout.php so all pages load functions)

function removeTask($TaskName,$taskID){
	
	if (isset($TaskName)){
	echo "Taskname is set";	
	}
	else {
	header ('Location: index.php?error="Task completion variables not set [E/1]"');	
	}
	
	if (isset($TaskID)){
	echo "TaskID is set";
	}
	else {
	header ('Location: index.php?error="Task completion variables not set [E/2]"');	
	}

	if (file_exists('../database/mysqli_connection.php')){
	require('../database/mysqli_connection.php');
	} else {
	require('database/mysqli_connection.php');	
	}
	
	$updateTask = "UPDATE MC_Tasks SET status='2' WHERE TaskName ='".$TaskName."' AND TaskId='".$taskID."'";
	
	$completedTaskResult = mysqli_query($mysqli_connection,$updateTask);
	
	if (mysqli_affected_rows($mysqli_connection) > 0){
	echo "task Completed!";	
	} else {
	echo "Task could not be removed, lets check the query on what went wrong";
	echo $updateTask;
	}
}

Thanks for all your help Maxxd really appreciate the advice :)

The logic flow of your script is correct.

 

However, right now it's wide-open to several different types of attack. You're using MySQLi, which is a good start - look into using prepared statements. I'm also questioning your logic on the connection script include - at what point would it not be where you expect it to be (one directory up), and if it's not, how do you know it's in the current directory?

Well I've put everything in a directory up bar a few main pages. So if it's not in the directory below and then database then it must just be up one directory although if you have a better solution for this I would be your best buddy forever lol

  • Solution

Things like database connections, configuration files, and ... well, honestly any functionality file, be it a class or function sheet, should be exactly where you put it. The idea of a database connection file being in one of two places is a bit scary - that means it could be within the webroot, where it's viewable under the right circumstances, or it could be above the webroot, where it's not. And - most importantly - your application doesn't know which it is. Needless to say, above the webroot is better.

 

How it's accessed from there depends on your system - if you're using a front controller pattern with a routing system, for instance, everything is going through a single entry point - index.php in the main webroot. From there, you always know where your includes directory is ('../includes/'). If you're using separate files for each page and serving them from within separate directories, then you'll have to do a bit more calculation to get it. However, if you're still using this style, you're probably duplicating a bit of code and content already, so it shouldn't add too much to your current overhead.

Yeh i have it in a "database" directory, so for instance I have Functions/functions.php and I have Tasks/tasks.php, but i also have index.php which is in the root directory which if there is no session it points you to secure/login.php, 

If i try to perform a function using Functions/functions.php from index.php It needs needs to be database/mysqli_connection.php but if I need a function performed by Tasks/tasks.php It needs ../database/mysqli_connection.php, the problem is if I call a function using Functions/functions.php from a root file e.g index.php it needs the directory to be database/mysqli_connection.php, but if I call that same function from Tasks/tasks.php is needs the directory to be ../database/mysqli_connection.php, I've never quite figured out how to get around this one.

Edited by moosey_man1988
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.