JQuery Value to PHP with Ajax? - javascript

My Website has a Video Player with a random Playlist and a Comments List.
All Comments ever written are loaded. Now I want to change the comments ID, everytime a new Video starts, so that the Site shows only comments for this Video.
The Player is set up in Javascript and has an on Ready Function, that fires an ajax function.
The Comments are set up as a php line with a $value.
This is my code:
<div id="comments">
<?php
$commentsID= 3; //Testnumber 3 shows all comments to video 3
Comment::getCommentSystem($commentsID);
?>
</div>
<script>
onReady: function(event) {
videoID; // actual videoID
//and here comes some Ajax Magic, to tell $commentsID = videoID, but how?
// My example doesn't work because it's my first try with Ajax whoohooo
$.ajax({
type: "GET",
url: "index.php",
data: videoID,
success: function(videoID){
$('#comments').empty(); // Clear Testnumber'n stuff
$(' <?php
$commentsID= videoID;
Comment::getCommentSystem($commentsID);
?>
').appendTo('#comments'); // rewrite the comments Div with the videoID
}
});
</script>
EDIT:
Now my code looks like this:
<div id="comments">
</div>
<script>
[...]
onReady: function(event) {
videoID; // actual videoID
$.ajax({
type: "GET",
url: "get_comments.php?videoId=" + videoID,
success: function(response){
$('#comments').html(response);
}
});
}
[...]
</script>
get_comments.php
<?php
session_start();
include "comment.class.php";
$videoID = $_GET["videoId"];
$comments = Comment::getCommentSystem($videoID);
return($comments);
?>
and it produces this:
<div id="comments">
<!-- The Form to add a comment ( always display none ) -->
<div style="display:none;">
<div class="comment-post comment-child">
<form id="addCommentForm" action="" method="post">
<!-- The Form container, that shows the Form comment -->
<!-- ( should be visible - maybe session fail? ) -->
<div class="comment-container" style="display:none;">
<div class="comment-content">
<!-- all comments to videoID 3 -->
<ul class="comment-list-3">
</div>

Do not send it index.php, send request to another endpoint like get_comments.php,
<script>
onReady: function(event) {
videoID; // actual videoID
//and here comes some Ajax Magic, to tell $commentsID = videoID, but how?
// My example doesn't work because it's my first try with Ajax whoohooo
$.ajax({
type: "GET",
url: "get_comments.php?videoId=" + videoID,
success: function(response){
$('.comment-list-3').empty(); // Clear Testnumber'n stuff
var html = '';
$.each(response, function(i, item) {
// Do your html here. I assume, your comment object has a field "text". Update it according too your need
html += '<div>' + item.text + '</div>';
});
$('.comment-list-3').html(html); // rewrite the comments Div with the videoID
}
});
</script>
and in your get_comments.php;
<?php
$videoID = $_GET["videoId"];
$comments = Comment::getCommentSystem($videoID); // Let say this is array
echo json_encode($comments);
?>

As Hüseyin BABAL mentioned you could use $_GET to recieve a video id and then prepare the page. Yuou could store the $_GET value in an attribute (for example: data-video-id="3") so you can read it using JS/jQUery. It is possible to fetch URL parts using JS but it is a bit more difficult.
WARNING: If you work with user input (like $_GET and $_POST) ALWAYS validate input.

Related

How to pass dynamically generated div id to ajax?

Hey i've got some problem.
My website is divided into two columns. On the left is sidebar which contains list of users dynamically generated from database, on the right-hand side should be unique chart generated by javascript framework (ajax) based on user_id. And this chart should be shown after choosing some user from list. The php file live-data.php which is used by this javascript/ajax needs GET parameter. Now it's:
url: "php/live-data.php"
and
$.get("php/live-data.php?Consultar=1", function(UltimosDatos)
but it should be
url: "php/live-data.php?user_id=2"
and
$.get("php/live-data.php?user_id=2&Consultar=1", function(UltimosDatos)
Where 2 is user_id got after clicking some user name from dynamically generated list. The php script live-data.php is ready for GET variable and returns proper json for chart framwork (this javascript shown below). I dont know how to pass div id to this ajax code.
HTML+PHP:
<div id="left" class="pre-scrollable col-lg-3">
<div class="list-group">
<?php include("php/dbSettings.php");
$result = $conn->query("SELECT * FROM user ORDER BY user_id");
if (!$result) {
die(mysqli_error($conn));
}
while ($user = mysqli_fetch_array($result)){
echo '' . $user['firstName'] . " " .$user['lastName'] . '';
}
?>
</div>
</div>
<div id="right" class="col-lg-9">
<div class="tab-content">
<?php include( "php/dbSettings.php");
$result=$ conn->query("SELECT * FROM users ORDER BY user_id");
if (!$result) {
die(mysqli_error($conn));
}
while ($user = mysqli_fetch_array($result)){
echo '<div class="tab-pane" id="'.$user['user_id'].'">
<div id="chart" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
</div>';
} ?>
</div>
</div>
Javascript/Ajax:
<script>
$(function() {
$(document).ready(function() {
var ultimox;
var ultimoy;
$.ajax({
url: "php/live-data.php", //i want this line to be "php/live-data.php?user_id=2" and 2 is variable got from user list onlick
type: 'get',
success: function(DatosRecuperados) {
$.each(DatosRecuperados, function(i, o) {
//some deleted code - unimportant
});
//some deleted code - unimportant
$('#chart').highcharts({
//draws chart
});
}
});
});
setInterval(function() {
$.get("php/live-data.php?Consultar=1", function(UltimosDatos) { //i want this line to be "php/live-data.php?php/live-data.php?Consultar=1&user_id=2" and 2 is variable got from user list onlick
//updates chart
}
});
}, 1000);
//some deleted code - unimportant
});
</script>
I hope someone can help me on my way.
Thanks, Paul
It looks like the hash will be set to the user id when the anchor is clicked, based on this <a href="#'.$user['user_id'].'" so you could read the hash value and pass it as data on the request. Either this:
$.ajax({
url: "php/live-data.php?user_id=" + window.location.hash.substr(1),
type: 'get',
success: function(DatosRecuperados) {
// ...
}
});
or this:
var dataObj = {};
dataObj['user_id'] = window.location.hash.substr(1); //create a data object to pass on query string, set user id value
$.ajax({
url: "php/live-data.php",
type: 'get',
data: dataObj, //pass object with request
success: function(DatosRecuperados) {
// ...
}
});

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

codeigniter sending a variable from ajax to controller

I'm currently doing an ajax add,update and delete. And I think I'll just start with the delete since it is the easiest and hope that it might help me in the others.
In jquery (this is inside $doc.ready and the event is triggered properly)
if ($a == "Delete")
{
var postid = $(this).next('.postid').val();
$(this).closest(".todo-content").fadeOut();
jQuery.ajax({
type: "POST",
dataType: 'json',
url: "<?=base_url()?>.index.php/classes/deletepost",
data: {postid: postid},
async: false,
});
}
in html
<form method="post">
<button class="btn" onclick="return confirm('Are you sure to delete this item?')">Delete</button>
<input type="hidden" value="<?php echo $id; ?>" name="postid">
</form>
In controller
public function deletepost(){
$id = $this->input->post('postid');
$data = array('active' => 0);
$this->Model_name->deletepost($id,$data);
redirect('/abc/123');
}
This is already working but then I am planning on making the crud to ajax. I'm trying to pass the postid from ajax to controller to delete this post. The fadeout already works but only the ajax does not. I'm very new to ajax so I do not know where I am going wrong and I might also ask questions again regarding the other parts of crud.
Fixed!
The problem was the url inside the $.ajax. It returns a garbage.
So I added a script in the header
<script type="text/javascript">
var BASE_URL = "<?php echo base_url();?>";
</script>
And just use BASE_URL in the url: like so url: BASE_URL+'classes/deletepost',
Please Try to follow this:
In Codeigniters View:
<!-- Store ID and baseurl as attributes . this would help you to fetch data -->
<button class="btn" postId="5" baseUrl="<?php echo base_url();?>" id="button">Delete</button>
<!-- Store ID and baseurl as attributes . this would help you to fetch data -->
<button class="btn" postId="5" baseUrl="<?php echo base_url();?>" id="button">Delete</button>
<!-- reading jquery file .. -->
<script type="text/javascript" src="http://localhost/jquery/js_search/jquery.js"></script>
<!--you can write file in extra js file .. it depends on you -->
<script type="text/javascript">
$('#button').click(function(){
// ask for confirmation
var result = confirm("Want to delete?");
// if it is confirmed
if (result) {
// get baseURL and ID using attributes
var base_url = $('#button').attr('baseUrl');
var postid = $('#button').attr('postId');
// make a ajax request
$.ajax({
url: base_url,
type: "POST",
dataType: 'json',
success: function (data) {
if(data){
// Fade out the content id
$('#content_id').closest(".todo-content").fadeOut();
}
}
});
}
});
</script>
in controller:
// You just need to delete the post and return a status code of "200"
public function deletepost(){
$id = $this->input->post('postid');
$data = array('active' => 0);
$this->Model_name->deletepost($id,$data);
redirect('/abc/123');
}

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

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

How to use data-toggle with Ajax and PHP

I am using Bootstrap (which is heavily modified) and love the use of data-toggle. My current script is pretty straight forward, it's an image upload script. I use the following code to list images from the database:
$stmt = $db->query('SELECT * FROM img_slider ORDER BY id ');
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<li>
<div class='thumbnail removable'>
<div class='remove' id='{$row['id']}' data-toggle='remove'></div>
<img src='../{$row['path']}'>
</div>
</li>"
;}
Notice data-toggle='remove' - This function works great removing images statically, but what say I want to remove the images in the database? I understand the best method would be to utilise Ajax. Here is what I mean:
My PHP file delete.php:
$id = $_REQUEST['id'];
$db->beginTransaction();
$st = $db->prepare('DELETE FROM img_slider WHERE id = :id');
$st->execute(array(':id' => $id));
$db->commit();
I am trying to execute this with the following jquery/ajax:
$("a[data-toggle=remove]").click(function()
{
var image_id = $(this).attr('id');
$.ajax({
cache: false,
type: 'POST',
url: 'actions/delete.php',
data: 'id='+image_id,
});
});
Any help would be greatly appreciated! I just don't know how to utilise bootstraps data-toggle with PHP, tried search for the solution, came up empty handed. Here is an image of how the image upload works:
If it is the selector that is the problem, tt should be
$('div[data-toggle="remove"]').click(function() {
but if it is click on the image you mean
$('div[data-toggle="remove"]').next().click(function() {
Edit. I just tested your question like so :
<div class='thumbnail removable'>
<div class='remove' id='27' data-toggle='remove'></div>
<img src='1.gif'>
</div>
$('div[data-toggle="remove"]').next().click(function() {
var image_id = $(this).prev().attr('id');
alert(image_id);
$.ajax({
cache: false,
type: 'POST',
url: 'actions/delete.php',
data: 'id='+image_id
});
});
alerts 27 and and try to XHR with id: 27.
If it is click on the data-toggle <div>
$('div[data-toggle="remove"]').click(function() {
var image_id = $(this).attr('id');
Take a look at jQuery function ON: http://api.jquery.com/on/
The issue is you are binding the click event at load, when you are loading elements in to the page async then they will not events binded. On should bind the events now and in the future.
$("body").on( "click", ".remove", function() {
// Remove stuff
});

Categories

Resources