reload an specific div without refresh whole page - php

I want to reload just an specific div. I searched and read some similar questions too. What I made is below. What is wrong with my code that does not refresh the div ?
<html>
<body>
<div id="reloadable">
<?php include 'rand.php'; ?>
</div>
<button class="ref" onclick="refreshDiv();"> refresh </button>
<script type="text/javacript">
function refreshDiv()
{
$('#reloadable').load(location.href + ' #reloadable');
}
</script>
</body>
</html>
<?php
$a= rand(0,10);
echo $a;
?>

The problem is that you're returning an entire HTML document when you use location.href as the URL. The documentation warns:
jQuery uses the browser's .innerHTML property to parse the retrieved document and insert it into the current document. During this process, browsers often filter elements from the document such as <html>, <title>, or <head> elements. As a result, the elements retrieved by .load() may not be exactly the same as if the document were retrieved directly by the browser.
Since you're returning the <html> element, this is being filtered out, so there's nothing to insert into #reloadable.
Instead, you could load directly from rand.php:
function refreshDiv()
{
$('#reloadable').load('rand.php');
}

With the pure respect to all friends that helped me specially Barmar and Ken lee, I can not accept Barmar's answer as correct answer. Because Barmar said $('#reloadable').load(location.href + ' #reloadable'); can not run properly and mentioned some reasons. But I added
<script
src="https://code.jquery.com/jquery-3.6.0.js"
integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
crossorigin="anonymous"></script>
from Ken lee's answer and also added onclick="javascript:refreshDiv() to my original code attached to main question and it worked. So the following code is working
<script
src="https://code.jquery.com/jquery-3.6.0.js"
integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
crossorigin="anonymous"></script>
<html>
<body>
<div id="reloadable"><?php include "rand.php"; ?></div>
<button class="ref" onclick="javascript:refreshDiv();"> refresh </button>
<script>
function refreshDiv() {
$('#reloadable').load(location.href + ' #reloadable');
}
</script>
</body>
</html>

Related

jQuery AJAX Post Error in Head Script

I have a file (lam.php) that displays a database-driven list of countries in Latin America. I would like to include it in various pages on my website as a convenient reference. But rather than simply include it, I'd like to use AJAX, so the users can decide whether or not they want to view the list.
So I'm learning how to work with AJAX. It sounds like I want to use jQuery + AJAX, using Post instead of Get.
But I immediately got hung up on an error on this line:
$.post("http://gx/2b/inc/C/Shared/DBLists/World/lam.php",data,callback);
I don't see any errors displayed when I preview the page, but the error is highlighted in Dreamweaver. Nothing happens when I click the button, so there's obviously an error somewhere. Can anyone spot the error(s) in my script?
This is the entire script:
<head>
<script>
$(document).ready(function(){
$("button#lam").click(function()
$.post("http://gx/2b/inc/C/Shared/DBLists/World/lam.php",data,callback);
)
}
)
</script>
</head>
<body>
<button id="lam">Latin America<button>
</body>
You need to add a DIV to the HTML for the result to be displayed in. Then the callback function has to fill in the DIV with the response from the AJAX call.
Since your PHP script doesn't take any parameters, you don't need the data argument.
<head>
<script>
$(document).ready(function(){
$("button#lam").click(function()
$.post("http://gx/2b/inc/C/Shared/DBLists/World/lam.php", function(response) {
$("#lam-result").html(response);
});
});
});
</script>
</head>
<body>
<button id="lam">Latin America<button>
<div id="lam-result"></div>
</body>

Javascript method call inside PHP page

I have a PHP page in which am hiding a div using a javascript method. This method is called on a hyperlink click. The issue is its giving Uncaught Reference error. Not sure what is the cause. I tried even to have a external JS file and define the method in that, but still not working.
I'll give you a hint:
make sure you have defined your DIV tag before the action script
like:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<div id="hideDiv">Hide on click</div>
<input type="button" value="hide" onClick="javascript:HideIt()"/>
<script type="text/javascript" language="javascript">
function HideIt(){
//what ever it is:Hide codes goes here
$('#hideDiv').hide() // we used it after the defined it :)
}
</script>
</body>
</html>
Uncaught Reference error in javascript usually means that the object or accessor isn't defined at the time of calling the method.
I've seen it when using jQuery when jQuery is included at the bottom of the html and the javascript is being triggered before it.
So
$('divid').text = "blah";
before the
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
Hence the $ method doesn't exist.
The solution would be to put the method call on body load.
Here is the general code to hide any div onClick.
<html>
<head>
//Here to add script tag, which i have writen below
</head>
<body>
<div id="testDiv">This is to be hide on click</div>
<br/>
<br/>
Click to hide!
<br/>
<br/>
Click to show!
</body>
</html>
NOTE: You should write apostrophes carefully. Bcox ' and " have different impact
Here is the script tag which u have to place in head tag:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

Issues since moving javascript to its own file

Alright, if you look at the code below, I am trying to make it more "flexible", moving the JavaScript code to its own file, instead of keeping it in the php file.
The code below is not gonna work anymore, since i cant transfer $yadayada['id'] to the JS file, well okay I dont know how to, and thats where my problem lies.
How can I use the code below, or some variant of it thats gonna work?
Whats gonna happen is that when you press a specific image(button), a modal will open for the specific post in the while statement.
I have skipped out the post part, since thats not the problem here, it is opening a modal window for the correct post.
Thanks in advance!
$yadaya = mysql_query("blablabal")
while($yadayada = mysql_fetch_assoc($yadaya)
{
<div id="kommentera<?=$yadayada['id']?>" class="settingsBox" style="display: none; width:500px; font-size: 14px;">
<textarea id="text<?=$yadayada['id']?>" class="textarea" style="width: 493px; height:80px;"></textarea><br />
<span class="buttons" style="float:left;">
<button id="kommenteraFilm" id1="<?=$yadayada['id']?>" uid1="<?=$yadayada['guid']?>" uid2="<?=$acc_info['id']?>" class="positive" type="submit" name="kommentera"><img src="<?=$static?>/img/bullet_go.png" alt="" />Kommentera</button>
</span>
<?php
?>
</div>
echo '
<div id="se-kommentera'.$yadayada['id'].'" class="testing" style="float:right; margin-top:-2px; cursor:pointer;">
<img src="'.$static.'/img/icon_kommentera.png" height="15px" width="15px" alt="" title="Kommentera" />
</div>'
;
}
footer:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="<?=$static?>/js/mylibs/dependency.js"></script
dependency.js:
$(function() {
$('#se-kommentera<?=$yadayada['id']?>').click(function (e) {
$('#kommentera<?=$yadayada['id']?>').modal();
return false;
});
});
UPDATE
To answer some of the responses, I think you are forgetting that I cannot access the while statement outside the statement itself, so making the js file a php file is kind of useless.
The JS file must be below the jQuery library file, which is in the footer.
You can generate Javascript through PHP (but it's not a good idea)
To directly answer your question: you can "generate" Javascript dynamically through PHP code. For example:
<!-- note that the source is .php so that the server processes it as such -->
<script type="text/javascript" src="dependency.php"></script
And dependency.php would look like:
<?php
// tell the browser how to interpret what we 'll be sending
header('Content-Type: text/javascript');
// get reference to any variables we need
$yadayada = /* ... */
?>
$(function() {
$('#se-kommentera<?=$yadayada['id']?>').click(function (e) {
$('#kommentera<?=$yadayada['id']?>').modal();
return false;
});
});
All of this is really the same thing you are doing when outputting HTML with PHP, only now you are outputting Javascript. But the problem is that you are doing the same work (what is required to get to $yadayada) two times once for your HTML, and once for your JS.
So what is a good idea?
Simply change your markup so that you do not need to know anything inside $yadayada when you write your JS; this way, the code can remain static. For example:
HTML:
<div class="se-kommentera testing">
<img src="..." height="15px" width="15px" alt="" title="Kommentera" />
<div class="settingsBox kommentera">
</div>
</div>
JS:
$(function() {
$('.se-kommentera').click(function (e) {
$(this).find(".kommentera").modal();
return false;
});
});
What I did here is provide a way of finding the appropriate .kommentera div not with an absolute identifier (the id) but in a manner relative to the .se-kommentera that was clicked.
For convenience, I chose to put one div inside the other and get a hold of it with .find; but this is not binding and you could really make dozens of different choices here. For example, you can give both divs an id like you did before and then do something like this:
$(function() {
$('.se-kommentera').click(function (e) {
var id = this.id.replace("se-", "");
$("#" + id).modal();
return false;
});
});
One simple way to do it would be to give the JavaScript-file a .php extension, instead of the regular .js. That way the PHP-code will be executed on the server, before the JavaScript is sent to the client. As you specify the type="text/javascript" on the script tag the browser won't mind the .php extension on your JS-file.
have you tried to echo $yadayada inside the js file?
This thread might help you Passing a PHP Variable in external JS file
If you want your javascript files to be able to output PHP variables, the best way I can think of is to add a mimetype to your htaccess file.
Something like the following would work for Apache...
AddType application/x-httpd-php .js

Trying to display a calendar using jquery ui

I am using the framework codeigniter and trying to use jquery for the purpose of displaying and allowing the user to chose a time period in which he would like to preform his search. I have the date and the text field displayed but when I click on the text field I don't get any calendar to chose a date from.
This is my view:
<html>
<head>
<script type="text/javascript" src="<?php echo $jquery?>"></script>
<script type="text/javascript">
$(function() {
$( "#datepicker" ).ui-datepicker();
});
</script>
</head>
<body>
<div class="demo">
<p>Date: <input id="datepicker" type="text"></p>
</div><!-- End demo -->
<div style="display: none;" class="demo-description">
<p>The datepicker is tied to a standard form input field. Focus on the input (click, or use the tab key) to open an interactive calendar in a small overlay. Choose a date, click elsewhere on the page (blur the input), or hit the Esc key to close. If a date is chosen, feedback is shown as the input's value.</p>
</div><!-- End demo-description -->
www.msn.ca
<?php echo form_open('search/submit'); ?>
</body>
</html>
It's been taken from the sample code: http://jqueryui.com/demos/datepicker/
FYI I am using jQuery UI 1.8.16
Not sure what's wrong here.
If anyone thinks the controller is relevant then here it is:
<?php
class calendarController extends CI_Controller{
public function index()
{
$this->load->helper('url');
$data['jquery'] = base_url("jquery.js");
$this->load->view("jqueryView", $data);
}
}
?>
I do not see links to jQuery JS and CSS files on you page. Try something like this:
<link href="Content/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.7.min.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui-1.8.16.min.js" type="text/javascript"></script>
You can place them anywhere on your page. Better at the end so that your pages shows faster. Use datepicker() inside jQuery load function, like in your code to make sure that nothing is broken
You're building your url wrong.
Should be:
$data['jquery'] = base_url().'jquery.js';
which gives in your view: http://www.yoursite.com/jquery.js.
I have some doubt on the actual true position of that script. Change it accordingly to your folder structure, just keep in mind that base_url() returns your url like this, with the trailing slash:
http://www.yoursite.com/
Also, you you're not loading jQuery UI, so add that too (same way as above)
Another thing, your input lacks the name attribute, you need it in case you want it to be fetched by php. AND, it's outside the form, so it won't work. This is just a note, maybe you don't want to use it that way, but just in case...
Shouldn't you place your datepicker initialization inside the jquery ready event handler ?
Like so:
$(document).ready(function(){
$( "#datepicker" ).datepicker();
});

noob question about autosuggest jquery plugin

I want to do some autosuggest for my text field, using this plugin AutoSuggest jQuery Plugin
I have an array, already json_encoded, and the files on the server, js, css, but Im not getting yet how the example works, here my code,
<html>
<head>
<title>test-data</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="inc/css/admin_style.css" rel="stylesheet" type="text/css">
<link href="inc/css/autoSuggest.css" rel="stylesheet" type="text/css">
<script language="javascript" src="inc/js/functions.js"></script>
<script language="javascript" src="inc/js/jquery-1.5.1.js"></script>
<script language="javascript" src="inc/js/jquery.autoSuggest.js"></script>
<script language="javascript" type="text/javascript">
</script>
</head>
<body>
<center><br><font class="title">test</font></center>
<form action="dataAll.php" method="post">
Name: <input type="text" name="fname" />
<input type="submit" />
</form>
<p> </p>
<p>JSON</p>
<p> </p>
<?php
$encoded = json_encode ($familyNames);
echo $encoded;
?>
</body>
</html>
so Im supposed to put this code,
$(function(){
$("input[type=text]").autoSuggest(data);
});
but the question is where??( as if I put it inside the php tags, it gives me an error
where should I put the name of my json formatted array? "$encoded" for the function to recognize that is the source of data?
thanks a lot!
You've got all the pieces, but your order/methodology is a bit off. Try creating a second file, named something like ajax.php, and place all of your php code in there. To ensure you are outputting good JSON, add the line header('Content-Type: text/json; charset=ISO-8859-1'); at the very beginning of the ajax.php file (you must set the header before any output is sent or you'll get an error). Now you've got to request your suggestion data:
$(document).ready(function() { // Runs when your page is loaded in the user's browser
$.getJSON('ajax.php', function(data) { // Runs ajax.php, then executes an anonymous function to handle the response
$('input[name="fname"]').autoSuggest(data); // Set your input field to use automatic suggestions with the returned data
}); // end getJSON
}); // end ready
This code simply executes an asynchronous HTTP request for ajax.php, and hands off the returned JSON data to the auto-suggest jQuery plugin. Place it inside a <script type="text/javascript"></script> tag. It will run once when the page loads due to the use of $(document).ready(...). I added the small optimization (input[name="fname"]) so jQuery doesn't attempt to attach the auto suggestion functionality to every text input you have on your page. If thats what you wanted to do (unlikely), just change it back to input[type=text].
You really do not need a separate php file to get this to work. There is nothing stopping you from doing it all in one file, but you'll soon realize how cluttered and unmanageable that can get. For me, its easiest to think of my "ajaxy" php code as a single, modular piece of my web application.
Be sure to reference these pages for detailed information:
http://api.jquery.com/
http://api.jquery.com/ready/
http://api.jquery.com/jQuery.getJSON/
You put it inside a tag in the html.
<script type="text/javascript">
$(function(){
$("input[type=text]").autoSuggest(data);
});
</script>

Categories