How Does One Reload the Contents of an Element Without Refreshing the Page After Sending a Form (The Cake Way)

How does one reload the contents of an element without refreshing the page after sending a form (The cake way)?

With HTML like this:

<div id="comments">
<!-- list of comments here -->
</div>

<form method="post" action="/comments/add" id="qCommentForm">
<textarea name="Comment.content"></textarea>
<input type="submit" value="Leave comment">
</form>

You can use JavaScript (and jQuery in this case) to intercept the submit event and send the comment data with Ajax (assuming the PHP form handler returns an HTML fragment for the new comment):

// run on document ready
$(function () {
// find the comment form and add a submit event handler
$('#qCommentForm').submit(function (e) {
var form = $(this);

// stop the browser from submitting the form
e.preventDefault();

// you can show a "Submitting..." message / loading "spinner" graphic, etc. here

// do an Ajax POST
$.post(form.prop('action'), form.serialize(), function (data) {
// append the HTML fragment returned by the PHP form handler to the comments element
$('#comments').append(data);
});
});
});

If the PHP form handler returns the whole list of comments (as HTML) instead of just the new one, you can use .html() instead of .append():

$('#comments').html(data);

You can find the jQuery documentation at http://docs.jquery.com/.


Update: I'm not a CakePHP expert, but the "cake way" AFAICT:

  1. Set up JsHelper:

    1. Download your preferred JavaScript library

    2. Include the library in your view/layout, e.g.

      echo $this->Html->script('jquery');
    3. Write the JsHelper buffer in your view/layout, e.g.

      echo $this->Js->writeBuffer();
    4. Include JsHelper in your controller, e.g.

      public $helpers = array('Js' => array('Jquery'));
  2. Use JsHelper::submit() instead of FormHelper::submit() to generate a submit button that will do Ajax form submission, e.g.

    echo $this->Js->submit('Leave comment', array('update' => '#comments'));
  3. In your controller, detect if the request is an Ajax request, and if so, render using the Ajax layout, e.g.

    if ($this->request->is('ajax')) {
    $this->render('comments', 'ajax');
    }

Not sure if/how RequestHandlerComponent figures into this though.

how to reset/clear the input field without reloading the input field

Since you are trying to reset to 0 <td> elements you can set their values by using .text() property like following:

$("#clear").click(function() { 
$('.dataReset').text(0);
return false;
});

Here's a Fiddle implementing the above with your code.

EDIT: If you want to implement a confirm box just simply do:

$("#clear").click(function() {
if (confirm('Are you sure?')) {
$('.dataReset').text(0);
}
return false;
});

Updated fiddle.

How to reload page in cakephp using jQuery when clicking the submit button

You can just redirect to the same page after clicking the comment button

return $this->redirect($this->here); OR

return $this->redirect($this->request->here); // cake 2.x

suppose we have a function handling comment inside your controller

public function comment() {
// process content here...

// redirects the user immediately with a nice message
$this->flash('Your comment has been saved, thanks', '<page you wish to redirect');

OR

$this->setFlash('blablablabla');
return $this->redirect($this->here); // this->here refers to the current pageurl
OR
return $this->redirect($this->request->here); // cake 2.x (// this->request->here refers to the current pageurl)


}

How to change route and content without page refresh? (robot friendly)

Here is something that could represent a starting point for a solution.
Before you go on reading these are the main things to keep in mind about my answer:

  • all vanilla javascript
  • ajax call to load new content
  • change url on address bar without reloading the page
  • register url changes in browser history
  • seo friendly

But be aware that all is presented in draft code meant to explain the solution, you'll need to improve the code if you want to implement it on production.

Let's start with the index page.

index.php

<!DOCTYPE html>
<html>
<head>
<title>Sample page</title>
<meta charset="UTF-8">
<script type="text/javascript" src="ajax_loader.js"></script>
</head>
<body>

<h1>Some static content</h1>
<a href="?main_content=external_content.php">
Link to load dynamic content
</a>
<div id="main_content">
<!--
Here is where your dynamic content will be loaded.

You can have as many dynamic container as you like.

In my basic example you can attach one link to a
single container but you can implement a more
complete solution to handle multiple containers
at the same time
-->

<!-- Leave this empty for the moment... some php will follow -->
</div>
</body>
</html>

Now let's see how the javascript can handle the links for loading content with ajax

ajax_loader.js

window.onload = function() {

var load = function(e) {
// prevent browser to load link
event.preventDefault();

// exit if target is undefined
if(typeof(e.target) == 'undefined' ) {return;}

// exit if clicked element is not a link
if (e.target.tagName !== 'A') {return;}

// get href from clicked element
var href = e.target.getAttribute("href");

// retrieve container and source
var href_parts = href.split('=');
var container = href_parts[0].substr(1);
var source = href_parts[1];

// instantiate a new request
var request = new XMLHttpRequest();

// bind a function to handle request status
request.onreadystatechange = function() {
if(request.readyState < 4) {
// handle preload
return;
}
if(request.status !== 200) {
// handle error
return;
}
if(request.readyState === 4) {
// handle successful request
successCallback();
}
};

// open the request to the specified source
request.open('GET', source, true);
// execute the request
request.send('');

successCallback = function() {
// on success place response content in the specified container
document.getElementById(container).innerHTML = request.responseText;

// change url in the address bar and save it in the history
history.pushState('','',"?"+container+"="+source);
}
};

// add an event listener to the entire document.
document.addEventListener('click', load, false);
// the reason why the event listener is attached
// to the whole document and not only to the <a>
// elements in the page is that otherwise the links
// included in the dynamic content would not
// liste to the click event

};

now let's give a look back to some specific elements of our html

As said before the proposed script will attach the behavior to any link, you only need to format it so to be read properly by the load() function. The format is "?container_name=filename.php". Where container_name is the id of the div in which you want the content to be loaded in, while filename.php is the name of the file to be called by ajax to retrieve the content.

So if you have some content in your 'external_content.php' file and want it loaded in the div with id 'main_content' here is what you do

<a href="?main_content=external_content.php">Your link</a>
<div id="main_content"></div>

In this example the div 'main_content' is empty when the page first loads and will be populated on click of your link with the content of the external_content.php file.
At the same time the address bar of your browser will change from
http://www.example.com/index.php
to
http://www.example.com/index.php?main_content=external_content.php
and this new url will be registered in your browser history

Now let's go further and see how we can make this SEO friendly so that
http://www.example.com/index.php?main_content=external_content.php
is a real address and the 'main_content' div is not empty when we load the page.

We can just add some php code to handle this.
(Please not that you could even write some javascript to to a similar job, but since you mentioned the use of server side language I decided to go for php)

<a href="?main_content=external_content.php">Load</a>
<div id="main_content">
<?php dynamicLoad('main_content','default_main_content.php'); ?>
</div>

Before showing it I want to explain what the php function dynamicLoad() does. It take two parameters, the first is equivalent to the container id, the second if the file where the default content is.
To be more clear, if the requested url is
http://www.example.com/
the function will put the content of default_main_content.php in the main_content div
but if the url requested by the browser is
http://www.example.com/index.php?main_content=external_content.php
then function will put the content of external_content.php in the main_content div.

This mechanism helps the page to be SEO friendly and user friendly, so when the search engine crawler will follow the href
"?main_content=external_content.php"
that brings to the url
"http://www.example.com/index.php?main_content=external_content.php" will find the same content displayed dynamically with the ajax call.
And this is also true for the user who will reload the page with a refresh or from the history.

Here is the simple dynamicLoad() php function

<?php
function dynamicLoad($contaner,$defaultSource){
$loadSource = $defaultSource;
if(isset($_GET[$contaner])) {
$loadSource = $_GET[$contaner];
}
include($loadSource);
}
?>

As said in the first lines, this is not a code ready for production, it's just the explanation of a possible solution to the request you made

to change the url showing and according to that change the content of
the page and make the urls and the content of the page to be robot
friendly

update database without refreshing the page using a hyperlink

I'd suggest the AJAX approach but just to mention it, the effect could be achieved without AJAX by placing the button in an iframe, this iframe could then follow the the link without the page having to refresh.

cakephp saving data without reload page

if you don't wanna reload the page to do this, you need to use Ajax..since you've already got unique id for this, what you need to do is use Jquery Ajax to handle this.

first download jquery lib and put it into your app/webroot/js folder and load it

http://jquery.com/download/ download Jquery lib here

then you can do:

<script>
$( document ).ready(function() {
//do sth when click on #btPrice
$('#btPrice').click(function(){
$.ajax({
type:"POST",
//the function u wanna call
url:"<?php echo $this->webroot;?>example/increase_price/",
/* data you wanna pass, as your $param1 is serverSide variable,
you need to first assign to js variable then you can pass:
var param1 = '<?php echo $param1;?>';*/
data:{increase_price:param1},
success:function(data)
{
//update your div
}
});
});
});
</script>

Also you have to modify your increase_price function

As we are passing increse_price as parameter in ajax call and method is post, in your function, you have to use $_POST['increase_price'] to catch it then assign to another variable

eg: $param1 = $_POST['increase_price']; then you can use it..

Should do the trick for you

Force page reload with html anchors (#) - HTML & JS

I would suggest monitoring the anchor in the URL to avoid a reload, that's pretty much the point of using anchors for control-flow. But still here goes. I'd say the easiest way to force a reload using a simple anchor-link would be to use

<a href="?dummy=$random#myanchor2"></a>

where in place of $random insert a random number (assuming "dummy" is not interpreted server side). I'm sure there's a way to reload the page after setting the anchor, but it's probably more difficult then simply reacting to the anchor being set and do the stuff you need at that point.

Then again, if you reload the page this way, you can just put myanchor2 as a query parameter instead, and render your stuff server side.

Edit

Note that the link above will reload in all circumstances, if you only need to reload if you're not already on the page, you need to have the dummy variable be more predictable, like so

<a href="?dummy=myanchor2#myanchor2"></a>

I would still recommend just monitoring the hash though.

Not reloading the page after delete in Vue component

Once I reload the page after the response came then it reload the page & remove deleted item. solution is as follows.

axios.post('/delete-item' +this.id, data).then( response => {
this.isDelete =false
location.reload()
});


Related Topics



Leave a reply



Submit