Change div's content after clicking on a link using Ajax request - javascript

My div contains a PHP function having an sql query which fetch latest threads from threads table. The structure of my page is something like this;
Section # 1 --- Link 1
Section # 2 --- Link 2
Section # 3 --- Link 3
What I want to do is to make it so like when Link 1 is clicked it shows the latest threads from Section 1, and when Link 3 is clicked then it shows latest threads of Section 3.
PLEASE NOTE: I know that I can use slidetoggle() jQuery function to show and hide div, but I want to make it so that WHEN link is clicked THEN runs the sql query to show latest threads. I'm using the following jQuery;
jQuery(document).ready(function($)
{
$('a[id^="forum_name"]').on('click', function (e)
{
e.preventDefault();
var fid = $(this).attr("fid");
$.ajax(
{
type: "POST",
url: 'latest_threads.php?fid='+fid,
dataType: 'json',
success: function (data)
{
$("#forum_threads_"+fid).html(data).stop().slideToggle("fast");
}
});
});
});
My PHP file latest_threads.php has the following code;
<?php
define("IN_MYBB", 1);
require_once "./global.php";
if ($mybb->input['fid'] != "")
{
require_once MYBB_ROOT."inc/functions.php";
$fid = intval($mybb->input['fid']);
$forum['forum_threads'] = kalachi_forum_threads($fid);
}
?>
and My HTML is like;
{$forum['threads']}
<div id="forum_threads_{$forum['fid']}" style="display: none;">{$forum['forum_threads']}</div>
But it doesn't works, please help!

jQuery:
jQuery(document).ready(function($){
$('a[id^="forum_name"]').on('click', function (e){
e.preventDefault();
var fid = $(this).attr("fid");
$.ajax(
{
type : "post",
dataType: "html",
url : "misc.php?action=forum_threads&fid="+fid,
cache: false,
success : function(response)
{
$("#forum_threads_"+fid).stop().slideToggle("fast").html(response);
}
});
});
});
PHP:
<?php
define("IN_MYBB", 1);
require_once "./global.php";
if ($mybb->input['fid'] != "")
{
require_once MYBB_ROOT."inc/functions.php";
$fid = intval($mybb->input['fid']);
echo $forum['forum_threads'] = kalachi_forum_threads($fid);
exit;
}
?>
In HTML:
Change the last line to this:
<div id="forum_threads_{$forum['fid']}"></div>

You're not outputting your response as far as I can see.
Try something like this:
...
$forum['forum_threads'] = kalachi_forum_threads($fid);
echo $forum['forum_threads']
exit();
...
I added the echo line to output the actual response back to your browser.

You can read Ajax tutorial.
But in your case, you should know, the data that you are showing in your div in this part of your code :
success: function (data)
{
$("#forum_threads_"+fid).html(data).stop().slideToggle("fast");
}
is the response of your php code.
Your php response is any output of your php code, it can be a simple echo 'something' or a html code, or including a html file etc.
generete a html code or include a html file in your php code, anything that you want to show in your div.
Note: always put a die() or exit() in the end of your php code.
This is a simple example :
HTML :
<div id="c1" onclick="javascript:loadcontent(1);">click</div><br>
<div id="c2" onclick="javascript:loadcontent(2);">click</div><br>
<div id="c1" onclick="javascript:loadcontent(3);">click</div><br/
Javascript (jquery) :
<script>
function loadcontent(id) {
$.post("yourphp.php", {id: id}, function(data) {
if (data) {
$("#c" + id).html(data);
}
else
{
alert("error");
}
});
}
</script>
PHP - yourphp.php :
<?php
$id = $_POST['id'];
require 'filename'.$id.".html";
die;
?>
Then you must create 3 html files with names : filename1.html , filename2.html , filename3.html
and put any content in them that you want to show in your divs with id c1,c2 or c3 .
Thats it

Related

How to pass variable from php for() to ajax when clicking a button?

when clicking (.refresh)button、how would you pass $data_name to ajax which you'll get by for() in body field of php script?
I would like to pass the variable for selecting data from database.
2Scripts:
(1) html formated .php file>
ajax written in header field,
php for() written in body field
(2) SQL select script in php, added
$dataname= $_POST['dataname'];
In for() I'm getting data from DB and showing data tables, DATA A~C.
When clicking the button for each data, I would want to get the new data from data base.
I was able to get it, just writting "A" for Ajax, but I would want to pass variable for many tables.
[enter image description here][1]
[1]: https://i.stack.imgur.com/zpJ7B.png
<head>
<script>
$(document).ready(function(){
$('.refresh').click(function(){
$.ajax({
// 通信先ファイル名
url: "select.php",
type: "POST",
data: ({"data_name": $data_name}),
success: function(data) {
//more code
},
error: function(data) {
//more code
}
});
</script>
</head>
<body>
<?php
//more code for(){  getting $data_name(A、B、C)here >
echo <<<EOD
<button class='refresh'>REFRESH DATA</button>
<table class='show'></table>
EOD;
?>
</body>
You can use a different PHP to return the JSON or the same.
So if you want to use the same script you basically want to send a JSON with the data when your PHP script gets a POST.
So you have to check:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// The request comes from Javascript doing POST
// Query Database and return a JSON with the field "data_name"
} else {
// Render your form like now you're doing now, the request com from the browser loading the page
}
//select.php
<?php
$data= $_POST["data_name"];
echo json_encode( $data);
?>
<script>
$(document).ready(function(){
$('.refresh').click(function(){
$.ajax({
// 通信先ファイル名
url: "select.php",
type: "POST",
data: ({"data_name": $data_name}),
success: function(data) {
// getting $data_name(A、B、C)here
},
error: function(data) {
//more code
}
});
</script>

Get php variable using jquery on select tag

I'm trying to get a string from a php file, here:
$company = Company::find_by_id($_GET['company_id']);
$string = $company->output_information();
$output = array('key' => $string);
echo json_encode($output);
The main file has the following html:
<select id="step_one_check">
// some options
</select>
<div id="div_company_data">TBA</div>
<div id="step_two" style="display: none">Step two<div>
and the following jQuery:
$(document).ready(function(){
$("#step_one_check").change(function(){
$("#step_two").slideDown();
$.ajax({
url : '../includes/encode/company_information.php',
type : 'GET',
data : "company_id=" + $("#step_one_check").val(),
dataType : 'json',
success : function (result) {
alert("success");
$("#div_company_data").html(result.key);
},
error : function () {
alert("error");
}
});
});
The jQuery script makes step two slides down, but does not alert or #div_company_data. Any idea?
----- UPDATE -----
I've resolved the problem, it's my php file. After I included the Company class, the code worked.

How to use data from one HTML page to retrieve data to be used on another HTML page using ajax

I would like to use the 'sID' in the first HTML form to retrieve data from the database and then use the data retrieved from the database on the second HTML page. I can do this with just php, but I just can't figure out how to do it using ajax.
I'm really new to javascript/ajax so please be gentle with your answers :)
HTML 1
<div class="moreR">
<form action="moreR_2.0.php" method="GET">
<input type="hidden" name="sID[]" value="a_certain_ID"/>
<input type="image" src="Icons/PNG/greater_than.png" alt="submit"/>
</form>
</div>
PHP (moreR_2.0.php)
<?php
include ('session_start.php');
include ('db_connect_mO.php');
if (isset($_GET['sID'])) {
foreach($_GET['sID'] as $sID) {
}
}
$sql = mysqli_query($con, "SELECT * FROM mo WHERE sID=$sID");
$row = mysqli_fetch_array($sql);
while ($row = mysqli_fetch_assoc($sql))
{
$test[]= array(
'pZero'=> $row['pZero'],
'pZero_Gname'=> $row['gZero_key'],
);
}
header('Content-Type: application/json');
echo json_encode ($test);
//detailed error reporting
if (!$sql)
{
echo 'MySQL Error: ' . mysqli_error($db);
exit;
}
?>
JavaScript
$(document).ready(function() {
"use strict";
function connect2mR() {
$.ajax({
url:"moreR_2.0.php",
type: "GET",
data:'sID',
dataType:"json",
//async:false,
success:function(data)
{
$('#pZero').html('<img src="rPlanets/' + this.gZero + '.png" alt=""/>');
$('#pZero_keys').html(this.gZero_key);
}, //success
}); //end of ajax
} //end of function
if (window.attachEvent) {window.attachEvent('onload', connect2mR);}
else if (window.addEventListener) {window.addEventListener('load', connect2mR, false);}
else {document.addEventListener('load', connect2mR, false);}
});
HTML 2
<section class="moreR_section">
<div style="width:20%;"><div id="pZero"></div></div>
<div class="moreR_g" style="margin-left:26%" id="pZero_keys"></div>
</section>
What i'm trying to do is; start from HTML 1, collect sID -> then PHP/JS use sID from HTML 1 to get data from database -> then use the result from database on HTML 2. At the moment i'm struggling on how to make this process work. Can't figure out how to start from HTML 1 and end up in HTML 2.
You are not fetching the data from the input element at all.. change your ajax code to below.
$.ajax({
url:"moreR_2.0.php",
type: "GET",
data:{sID: $('input[name="sID[]"]').val()}, // this is the change
dataType:"json",
//async:false,
success:function(data)
{
$('#pZero').html('<img src="rPlanets/' + this.gZero + '.png" alt=""/>');
$('#pZero_keys').html(this.gZero_key);
}, //success
}); //end of ajax
Edit 1: you can use localstorage to save data and retrieve from there when ever required. So you can do as below
In your HTML 1 write this.
localStorage.setItem('sID', JSON.stringify( $('input[name="sID[]"]').val()));
And in HTML 2 you can access the value by reading it from the local storage like below,
var sIDofHTML1 = JSON.parse(localStorage.getItem('sID'));
You will have to update the ajax as below.
data:'sID', // this has to change to data:'sID='+sID,
$.ajax({
url:"moreR_2.0.php",
type: "GET",
data:'sID', // this has to change to data:'sID='+sID,
dataType:"json",
//async:false,
success:function(data)
{
$('#pZero').html('<img src="rPlanets/' + this.gZero + '.png" alt=""/>');
$('#pZero_keys').html(this.gZero_key);
}, //success
}); //end of ajax

how to use AJAX?

I'm trying to use AJAX so that you don't see the reload refresh.
i want if i change the select button from 1 to 5 that you can see 5 live change and that i can use the 5 in a php variable.
i got this:
<script>
$(document).on('change', '#hoeveelheid', function(e) {
var j_Hoeveelheid = this.options[e.target.selectedIndex].text;
$.ajax({
type: 'POST',
url: 'do.php',
data: {aantal : j_Hoeveelheid},
success: function (data) {
$('.test').html(data);
}
});
}
</script>
Now is my question what i need to set in the do.php file?
so that my script works without any refresh visible.
what i need to set in the do.php file?
At php file you are sending this object:
data: {aantal : j_Hoeveelheid},
so you need to get the key aantal at php end.
You can do this in your php file:
<?php
$aantal = $_POST['aantal'];
echo $aantal . " is the posted value of dropdown.";
?>

Ajax POST is not posting onclick to current page

Alright so this has been bugging me for a long time now... I have tried everything but I cant get it to work!
So what I want to have is a link that acts as a button, and once you click it, it POSTs an ID number of the button in the form "{ 'id' : id }"
edit-homepage.php:
<script>
$(function() { // document ready
$('a.inactive').on('click', function(event) {
event.preventDefault(); // instad of return false
var id = $(this).data('id');
// use $.post shorthand instead of $.ajax
$.post('edit-homepage.php', {id: id}, function(response) {
// after you get response from server
editSlide(id);
});
});
});
</script>
The a href button is created using PHP and I want it to call the ajax function postID( id ) which will post the id so that later I can populate a form via PHP using the posted id.
edit-homepage.php:
echo '<li><a class="inactive" id="slide-'.$info["id"].
'" onClick="postID('.$info["id"].'); editSlide('.$info["id"].'); return false;">'
.'<img src="../images/'.$info["img"].'" width="175"/><p>Edit Slide '
. $info["id"] .'</p></a></li>';
Currently, when I click the link, it opens the alert but it is EMPTY or Undefined. It is supposed to display "ID: 1" for example if the link clicked has a ID of 1.
edit-homepage.php:
<script>
function editSlide($id) {
<?PHP
if (isset ($_POST['id'])) {
echo "alert('success!2');";
}$id = !empty($_POST['id']) ? $_POST['id'] : '';
$data = mysql_query("SELECT * FROM slider WHERE id='$id'") or die(mysql_error());
$info = mysql_fetch_array( $data );?>
document.getElementById("edit-slide-id").innerHTML="Edit Slide #"+$id;
document.getElementById("edit-form").style.display = "block";
document.getElementById("short-title").value="<?PHP echo $info['s_title']; ?>";
}
</script>
Thanks!
With jquery, you don't need to use attributes to attach events, like that:
$(function() { // document ready
$('a.inactive').on('click', function(event) {
event.preventDefault(); // instad of return false
var id = $(this).data('id');
// use $.post shorthand instead of $.ajax
$.post('edit-homepage.php', {id: id}, function(response) {
alert('ID:' + response);
// after you get response from server
editSlide(id);
});
});
});
As of server side, try replacing raw
<?PHP echo $_POST['id']; ?>
With
<?php echo !empty($_POST['id']) ? $_POST['id'] : '' ?>
You likely get notice about Undefined index id, which breaks javascript if there is no post data.
UPDATE
edit-homepage.php shold be separated something like that:
if(!empty($_POST)) {
// here you process your post data and return
// only wenever you want to pass to script
// not all the html
} else {
// here you output html and scripts, but don't do request processing
}
You should always remember, that your HTML rendering must always be separated from your logic. It is better to put views in separate files from logic, though it is not required, it is much easier to debug and maintain.
You can not include PHP code that is supposedly to run after the ajax call. The PHP code will be run only to generate the page. Anything you want to include in alert should be provided in the ajax response, in your case the data variable.
You need to use alert('ID: ' + id).
The $_POST['id'] part of the script does not react to the AJAX request. It is whatever the $_POST['id'] value is when the script is output to the browser (i.e. when the page is first loaded).
You will see this if you view the source.
alert ("ID:"+data);
then only you will get response
or
alert("ID"+id);
this will alert the id passes to function
http://jsfiddle.net/U54ME/
$(".checkthisclass").click(function() {
$.ajax({
type: "POST",
url: "edit-homepage.php",
data: { 'id' : $(this).attr("slideid"); },
success: function(data) {
alert(data);
}
});
}
});
--
<ul>
<li><a class="inactive checkthisclass" id="slide-5" slideid = "5" ><img src="http://blog.entelo.com/wp-content/uploads/2013/04/stackoverflow-logo.png" width="175"/><p>Edit Slide 5</p></a></li>
</ul>

Categories

Resources