AJAX load content using link instead of button? - php

I am trying to load content of a URL which is in a href of a Link using AJAX/JQUERY.
For some reason, the AJAX doesn't get executed and when i click on the Link, the URL will open in a new window!
but I need to load the content of URL on the same page that has the AJAX without opening a new window!
this is my current code:
<div id="content"></div>
<a id='listc' class='lisitem' href='file.php?id=".$id."' >".$id."</a>
and the AJAX:
<script type="text/javascript">
$("#listc").click(function() {
$("#content").load(this.href);
return false;
});
</script>
just to clarify, I do have the jquery lib included in my page header and I am using it for other stuff on the same page. so the issue is not that.
could some please advise on this issue?
Thanks

You need to prevent the default action of the link:
<script type="text/javascript">
$("#listc").click(function(e) {
e.preventDefault();
$("#content").load(this.href);
return false;
});
</script>

You need to do something with your AJAX return :
<script type="text/javascript">
$("#listc").click(function() {
$("#content").load(this.href, function(result){
alert("AJAX done");
});
return false;
});
</script>

You can change the href from the actual page, to a javascript: call. This way, you wouldn't have to concern about the default link redirect.
<a id='listc' class='lisitem' href=javascript:LoadFunction('file.php?id=".$id."'); >".$id."</a>
JS:
function LoadFunction(url) {
$("#content").load(url, function(result){
//something
});
}

Give the following a try:
document.getElementById('listc').addEventListener('click', function() {
$("#content").load(this.href);
return false;
});
UPDATE
Change:
<a id='listc' class='lisitem' href='file.php?id=".$id."' >".$id."</a>
to:
<a id="listc" class="listitem" data-id="<?= $id; ?>" href="#"> <?= $id; ?></a>
And AJAX to:
$(document).delegate('.listitme','click',(function() {
var id = $(this).data('id');
$('#content').load('file.php?id=' + id);
return false;
}
or:
$(document).delegate('.listitme','click',(function() {
var id = $(this).data('id');
$.post('file.php', {id : id}, function(answer) {
$('#content').html(answer);
});
}

Try something like that :
When you click on the link, do an AJAX call then print the result in your container.
<script type="text/javascript">
$("#listc").click(function(e) {
e.preventDefault();
$.ajax({
url: $(e.currentTarge).attr('href'),
complete: function () {
// remove loading status if neeed
},
success: function (response) {
$("#content").html(response)
},
error: function() {
//manage error here
}
});
});
</script>

Related

call function url page with ajax

I have tried several times but it didn't work. I want to call the function nama() on the dom_area.php page.
This is dom_area as target
<?php
function nama()
{
echo $_POST['data_area'];
}
?>
and this is the page where I call the function
<button id='acc'>asas</button>
<script>
$(document).ready(function() {
$('#acc').click(function() {
let data_area = 2;
let url_address = "<?= 'dom_area.php/nama()'; ?>";
$.ajax({
url:url_address,
type:'post',
data:{data_area:data_area} ,
}).done(function(output){
console.log(output);
// alert(data);
});
// console.log(url);
});
});
</script>
You can only cause a php file to be launched, NOT a specific function within that script
However if you pass a parameter to control what to do in the script you can achieve what you are trying to do
<button id='acc'>asas</button>
<script>
$(document).ready(function(){
$('#acc').click(function(){
let data_area = 2;
$.ajax({
url:'dom_area.php', // the script file name
type:'post',
// add a control parameter
data:{control:"Nama", data_area:data_area},
}).done(function(output){
console.log(output);
// alert(data);
});
// console.log(url);
});
});
</script>
Now in the PHP
<?php
function nama()
{
echo $_POST['data_area'];
}
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
// form was submitted
switch($_POST['control'])
case 'Nama':
nama();
break;
default:
echo json_encode(['status'=>'failed']);
}
}
?>
try this:
<?php include_once('dom_area.php') ?>
<button id='acc'>asas</button>
<script>
$(document).ready(function(){
$('#acc').click(function(){
let data_area = 2;
let url_address = "<?= json_encode(nama()); ?>";
$.ajax({
url:url_address,
type:'post',
data:{data_area:data_area} ,
}).done(function(output){
console.log(output);
// alert(data);
});
// console.log(url);
});
});
</script>
Please try this in call part.
<button id='acc'>asas</button>
<script>
$(document).ready(function(){
$('#acc').click(function(){
let data_area = 2;
$.ajax({
url:'dom_area.php/nama',
type:'post',
data:{data_area:data_area} ,
}).done(function(output){
console.log(output);
// alert(data);
});
// console.log(url);
});
});
</script>

JQuery won't load clear url?

I want to load simple codeignitier controller, but no success i get 404 error.
It looks like jquery load does not support pretty/clear urls? Is it possible and how?
When i try to load some file using this same code it works perfectly, but when i try to load codeignitier controller function nope, i get 404 in Console.
<script type="text/javascript">
$(document).ready(function () {
$("#season").load('https://www.example.co/index.php/system/example');
//i already tried without 'index.php'
});
</script>
when i check does load function works using some simple file, it works perfectly:
<script type="text/javascript">
$(document).ready(function () {
$("#season").load('https://www.example.co/test.php');
});
</script>
and controller:
public function example(){
echo "EXAMPLE";
}
This link exists and is not 404 (of course without example):
https://www.example.co/index.php/system/example
Try by pass it as
window.location.href = '<?php echo base_url('controller/method'); ?>'
I solve it by adding '?' before index.php.
So this is result:
<script type="text/javascript">
var PI = {
onReady: function() {
$.ajax({
type: 'GET',
url: '/index.php?/system/getseasons/SC0',
success: function (response) {
alert('success');
$("#season").html(response);
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
})
},
};
$( document ).ready( PI.onReady );
</script>

connecting ajax and php not work

what is the problem of this code?
it is menu and page change by ajax with out refreshing the page, but its not working
it is my ajax code
<script>
$(document).ready(function() {
$('.news').click(function give(id){
$('#main-unit').text('Please Wait...');
var place= id;
$.ajax({
url:'pages/news.php',
type:'POST',
data:'where='+place,
statusCode:{
success: function(data){
$('#main-unit').html(data);
}
}
});
});
});
</script>
this is my html tags
<ul>
<li><a class="news" onclick=\"give('news')\" href="#">news</a></li>
</ul>
and php code
mysql_connect("localhost", "root", "")
or die(mysql_error());
mysql_select_db("basi")
or die(mysql_error());
if($_POST['where']=='news'){
$result = mysql_query("SELECT * FROM contents WHERE type = 0");
while ($row = mysql_fetch_array($result)){
$title = $row['title'];
$text = $row['text'];
echo"
<div class='title'><span>$title</span></div>
<div class='content'>
$text
</div>
";
}
}
the information read from DB but dont return to html file.
The problem is with your JavaScript. You're waiting for document ready and (incorrectly) binding a click event listener that isn't being used! Try:
<a class="news" onclick="give('news')" href="#">news</a>
with the JavaScript:
<script>
function give(id) {
$('#main-unit').text('Please Wait...');
var place = id;
$.ajax({
url:'pages/news.php',
type:'POST',
data:'where='+place,
statusCode:{
success: function(data){
$('#main-unit').html(data);
}
}
});
}
</script>
A better solution would be to separate HTML from JavaScript - remove the onclick attribute from your menu link, and use pure jQuery to select it and bind an event that calls give() when it is clicked:
$(document).ready(function() {
$('.news').click(function(e) {
give('news');
});
});
FTFY
<script>
$(document).ready(function() {
$('.news').click(function give(id){
$('#main-unit').text('Please Wait...');
var place= id;
$.ajax({
url:'pages/news.php',
type:'POST',
data:'where='+place,
//I believe your mistake was here
success: function(data){
$('#main-unit').html(data);
}
});
});
});
</script>

Change DIV content using ajax, php and jQuery

I have a div which contains some text for the database:
<div id="summary">Here is summary of movie</div>
And list of links:
Name of movie
Name of movie
..
The process should be something like this:
Click on the link
Ajax using the url of the link to pass data via GET to php file / same page
PHP returns string
The div is changed to this string
<script>
function getSummary(id)
{
$.ajax({
type: "GET",
url: 'Your URL',
data: "id=" + id, // appears as $_GET['id'] # your backend side
success: function(data) {
// data is ur summary
$('#summary').html(data);
}
});
}
</script>
And add onclick event in your lists
<a onclick="getSummary('1')">View Text</a>
<div id="#summary">This text will be replaced when the onclick event (link is clicked) is triggered.</div>
You could achieve this quite easily with jQuery by registering for the click event of the anchors (with class="movie") and using the .load() method to send an AJAX request and replace the contents of the summary div:
$(function() {
$('.movie').click(function() {
$('#summary').load(this.href);
// it's important to return false from the click
// handler in order to cancel the default action
// of the link which is to redirect to the url and
// execute the AJAX request
return false;
});
});
try this
function getmoviename(id)
{
var p_url= yoururl from where you get movie name,
jQuery.ajax({
type: "GET",
url: p_url,
data: "id=" + id,
success: function(data) {
$('#summary').html(data);
}
});
}
and you html part is
<a href="javascript:void(0);" class="movie" onclick="getmoviename(youridvariable)">
Name of movie</a>
<div id="summary">Here is summary of movie</div>
This works for me and you don't need the inline script:
Javascript:
$(document).ready(function() {
$('.showme').bind('click', function() {
var id=$(this).attr("id");
var num=$(this).attr("class");
var poststr="request="+num+"&moreinfo="+id;
$.ajax({
url:"testme.php",
cache:0,
data:poststr,
success:function(result){
document.getElementById("stuff").innerHTML=result;
}
});
});
});
HTML:
<div class='request_1 showme' id='rating_1'>More stuff 1</div>
<div class='request_2 showme' id='rating_2'>More stuff 2</div>
<div class='request_3 showme' id='rating_3'>More stuff 3</div>
<div id="stuff">Here is some stuff that will update when the links above are clicked</div>
The request is sent to testme.php:
header("Cache-Control: no-cache");
header("Pragma: nocache");
$request_id = preg_replace("/[^0-9]/","",$_REQUEST['request']);
$request_moreinfo = preg_replace("/[^0-9]/","",$_REQUEST['moreinfo']);
if($request_id=="1")
{
echo "show 1";
}
elseif($request_id=="2")
{
echo "show 2";
}
else
{
echo "show 3";
}
jQuery.load()
$('#summary').load('ajax.php', function() {
alert('Loaded.');
});
<script>
$(function(){
$('.movie').click(function(){
var this_href=$(this).attr('href');
$.ajax({
url:this_href,
type:'post',
cache:false,
success:function(data)
{
$('#summary').html(data);
}
});
return false;
});
});
</script>
<script>
function getSummary(id)
{
$.ajax({
type: "GET",//post
url: 'Your URL',
data: "id="+id, // appears as $_GET['id'] # ur backend side
success: function(data) {
// data is ur summary
$('#summary').html(data);
}
});
}
</script>

Refresh a table with jQuery/Ajax every 5 seconds

So I have a table pulling information from a database and I was wondering how I could make it refresh its information without reloading the whole page.
You'll need a getTable.php page that displays your table, and nothing else: no headers, footers, etc.
PHP (getTable.php) - this can be any server side code (asp, html, etc..)
<?php
echo '<table><tr><td>TEST</td></tr></table>';
?>
Then, in your JS, you can easily refresh the table by using the load() method:
HTML
<div id="tableHolder"></div>
JS
<script type="text/javascript">
$(document).ready(function(){
refreshTable();
});
function refreshTable(){
$('#tableHolder').load('getTable.php', function(){
setTimeout(refreshTable, 5000);
});
}
</script>
Use ajax, following example is in jQuery:
$(function() {
var prevAjaxReturned = true;
var xhr = null;
setInterval(function() {
if( prevAjaxReturned ) {
prevAjaxReturned = false;
} else if( xhr ) {
xhr.abort( );
}
xhr = $.ajax({
type: "GET",
data: "v1="+v1+"&v2="+v2,
url: "location/of/server/script.php",
success: function(html) {
// html is a string of all output of the server script.
$("#element").html(html);
prevAjaxReturned = true;
}
});
}, 5000);
});
The success function assumes that your server script outputs the html that you want to replace in the element with id 'element'.
You should have a page that return the information and pull data using Ajax / jQuery.
<div class="result"></div>
setInterval(function() {
$.get('table.php', function(data) {
$('#result').html(data);
});
}, 5000);
Here is another option for you to use. This solution is using an IIFE which is preferred over setInterval. You can read more about IIFE at the link above.
JAVASCRIPT:
var $results = $('#results'),
loadInterval = 5000;
(function loader() {
$.get('script.php', function(html){
$results.hide(200, function() {
$results.empty();
$results.html(html);
$results.show(200, function() {
setTimeout(loader, loadInterval);
});
});
});
})();
HTML:
<div id="results"></div>
setTimeout(function(){
jqueryFunction(Args);
},100);
will work...
100 = 100 milliseconds
The following works with JQuery Datatables 1.10
`var tableName;
//Set AJAX Refresh interval.
$(function() {
setReloadInterval(10); //Refresh every 10 seconds.
}
//Because function takes seconds we * 1000 to convert seconds to milliseconds.
function setReloadInterval(reloadTime) {
if(reloadTime > 0)
internalId = setInterval("reloadTable()", (reloadTime * 1000);
}
//Auto Refresh JQuery DataTable
function reloadTable() {
tableName.ajax.reload();
}
//Table defined...
$(document).ready(function () {
tableName = $('#tableName').DataTable({
"sAjaxSource": "/someUrl",
});`

Categories