Load a bootstrap modal through ajax - PHP - php

I want to load a modal using ajax, here's my code :
jQuery(document).ready(function() {
jQuery("a").click(function() {
var Id = jQuery(this).attr("id");
jQuery.ajax({
type: 'POST',
data: {
'modal_id' : Id,
},
url : "ajax.php",
success: function(reponse) {
if(reponse) {
alert(reponse);
} else {
alert('Error');
}
}
});
});
});
And here's my {a} tag :
<a id="2" data-original-title="Preview" data-placement="top" class="data-tooltip" rel="tooltip" data-toggle="modal" href="#modal_2"><span class="btn btn-default btn-sm glyphicon glyphicon-new-window"></span></a>
ajax.php :
echo "<div class='modal fade' id='modal_".$_POST['modal_id']."'>
<div class='modal-dialog'>
<div class='modal-content'>
<div class='modal-header'>
<button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>
<h4 class='modal-title'>Preview</h4>
</div>
<div class='modal-body'>";
echo "</div>
</div>
</div>
</div>";
How I can display the modal through ajax and why my code doesn't work? Thanks.

You forgot to append the content of the modal box to the document body and actually opening the box.
$(document).ready(function() {
$("a").click(function() {
var Id = jQuery(this).attr("id");
$.ajax({
type: 'POST',
data: {
'modal_id' : Id,
},
url : "ajax.php",
success: function(response) {
if(response) {
$('body').append(response);
$('#modal_'+Id).modal('show');
$(document).on('hidden.bs.modal', modal_id, function (event) {
$(this).remove();
});
} else {
alert('Error');
}
}
});
});
});

try
<a id="2" data-original-title="Preview" data-placement="top" class="data-tooltip" rel="tooltip" data-toggle="modal" href="#modal_2"><span class="btn btn-default btn-sm glyphicon glyphicon-new-window">gdfgdf</span></a>
<div id="alert"></div>
<script>$(document).ready(function() {
$("a").click(function() {
var Id = $(this).attr("id");
$.ajax({
type: 'POST',
data: {
'modal_id' : Id,
},
url : "db_search.php",
success: function(data) {
$('#alert').html(data); $('#alert').show();
}
});
});
$('#2').trigger('click');
});
</script>

Related

Code breaks with PHP "if" statement, otherwise both functions work independently

I have 2 functions in php which I'm using to display page content on a website.
Both of these functions work from inside the page independently and so the $_POST variables from the ajax call I have proven to myself are all present.
There are 2 pages involved plus the button, I won't bother with the button below.
pages/pages.php (where the problem statement is and which is called by ajax from the button)
<?php
include('../config/connection.php');
$page=$_POST['page'];
$lang=$_POST['lang'];
function pageDivs($dbc, $id, $lang){
$q="SELECT * FROM content WHERE page='$id' AND status=1";
$r = mysqli_query($dbc, $q);
while ($data=mysqli_fetch_assoc($r)){
?>
<div class="content" >
<?php
if ($lang =='FR'){
echo $data['contentfr'];
}else{
echo $data['contenten'];
}
?>
</div>
<?php
}
}
function blog($dbc,$lang){
?>
<div class="bgImage homeImg"><img src="images/bgs/1566337061.jpg"></div>
<div class="gradient"></div>
<div class="col-md-12">
<?php
$q = "SELECT * FROM blog WHERE status = 1 ORDER BY id DESC";
$r = mysqli_query($dbc,$q);
$i=0;
while ($data=mysqli_fetch_assoc($r)){
$i++;
?>
<div id="post<?php echo $i; ?>" class="post snap">
<div class="postBox">
<article id="article<?php echo $i; ?>" class="article col-md-7">
<h3><?php echo $data['titleen'] ?></h3>
<?php echo $data['contenten']; ?>
</article>
<div id="pictureFrameLand<?php echo $i; ?>" class="pictureFrameLand col-md-4">
<img src="<?php
$q2 = "SELECT * FROM tbl_images WHERE image_id=$data[artimage]";
$r2 = mysqli_query($dbc, $q2);
$src= mysqli_fetch_assoc($r2);
echo $src['urlFront']
?>">
</div>
<div class="gradientLand col-md-4"></div>
</div>
</div>
<div class="spacer snap"></div>
<?php
}
?>
</div>
<?php
}
if ($page !== 'home'){
pageDivs($dbc, $page, $lang);
} else{
blog($dbc, $lang);
include('../js/home.php');
}
?>
js/myJS.php(ajax calls from here, button.on(click, function(){}) )
<script type="text/javascript">
// JavaScript Document
$(document).ready(function() {
// Create vars for Pages
var page = 'home';
var lang = '<?php echo $_GET['
lang ']; ?>';
var dataTosend = 'page=' + page + '&lang=' + lang;
//Ajax Home Page on load
$.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
//Ajax 1st 2 buttons
$('#home').click(function() {
page = 'home';
lang = '<?php echo $lang; ?>';
dataTosend = 'page=' + page + '&lang=' + lang;
$('.active').addClass('inactive').removeClass('active');
$('#home').removeClass('inactive').addClass('active');
$('.content').fadeOut(500, function() {
$('.content').remove(),
$.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
});
});
$('#bio').click(function() {
page = 'bio';
lang = '<?php echo $lang; ?>';
dataTosend = 'page=' + page + '&lang=' + lang;
$('.active').addClass('inactive').removeClass('active');
$('#bio').removeClass('inactive').addClass('active');
$('.content').fadeOut(500, function() {
$('.content').remove(), $.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
});
});
//Ajax Work Dropdown
$('#work').click(function() {
page = 'work';
lang = '<?php echo $lang; ?>';
dataTosend = 'page=' + page + '&lang=' + lang;
$('.active').removeClass('active');
$('#work').addClass('active');
$('.content').fadeOut(500, function() {
$('.content').remove(), $.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
});
});
$('.install').click(function() {
page = 'install';
lang = '<?php echo $lang; ?>';
dataTosend = 'page=' + page + '&lang=' + lang;
$('.active').removeClass('active');
$('#install').addClass('active');
$('.content').fadeOut(500, function() {
$('.content').remove(), $.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
});
});
$('.write').click(function() {
page = 'write';
lang = '<?php echo $lang; ?>';
dataTosend = 'page=' + page + '&lang=' + lang;
$('.active').removeClass('active');
$('#write').addClass('active');
$('.content').fadeOut(500, function() {
$('.content').remove(), $.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
});
});
$('.video').click(function() {
page = 'video';
lang = '<?php echo $lang; ?>';
dataTosend = 'page=' + page + '&lang=' + lang;
$('.active').removeClass('active');
$('#video').addClass('active');
$('.content').fadeOut(500, function() {
$('.content').remove(), $.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
});
});
$('.photo').click(function() {
page = 'photo';
lang = '<?php echo $lang; ?>';
dataTosend = 'page=' + page + '&lang=' + lang;
$('.active').removeClass('active');
$('#photo').addClass('active');
$('.content').fadeOut(500, function() {
$('.content').remove(), $.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
});
});
//Ajax Workshops dropdown
$('#works').click(function() {
page = 'works';
lang = '<?php echo $lang; ?>';
dataTosend = 'page=' + page + '&lang=' + lang;
$('.active').removeClass('active');
$('#works').addClass('active');
$('.content').fadeOut(500, function() {
$('.content').remove(), $.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
});
});
$('.child').click(function() {
page = 'child';
lang = '<?php echo $lang; ?>';
dataTosend = 'page=' + page + '&lang=' + lang;
$('.active').removeClass('active');
$('#child').addClass('active');
$('.content').fadeOut(500, function() {
$('.content').remove(), $.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
});
});
$('.adols').click(function() {
page = 'adols';
lang = '<?php echo $lang; ?>';
dataTosend = 'page=' + page + '&lang=' + lang;
$('.active').removeClass('active');
$('#adols').addClass('active');
$('.content').fadeOut(500, function() {
$('.content').remove(), $.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
});
});
$('.adult').click(function() {
page = 'adult';
lang = '<?php echo $lang; ?>';
dataTosend = 'page=' + page + '&lang=' + lang;
$('.active').removeClass('active');
$('#adult').addClass('active');
$('.content').fadeOut(500, function() {
$('.content').remove(), $.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
});
});
//Ajax Last button
$('#contact').click(function() {
page = 'contact';
lang = '<?php echo $lang; ?>';
dataTosend = 'page=' + page + '&lang=' + lang;
$('.active').removeClass('active');
$('#contact').addClass('active');
$('.content').fadeOut(500, function() {
$('.content').remove(), $.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
});
});
//Collapse Dropdowns with other buttons
$('.bbutt').click(function() {
$('#collapseOne1').removeClass('show');
$('#collapseTwo1').removeClass('show');
});
$('#work').click(function() {
$('#collapseTwo1').removeClass('show');
});
$('#works').click(function() {
$('#collapseOne1').removeClass('show');
});
//debug
$('#console-debug').hide();
$('#btn-debug').on("click", function() {
$('#console-debug').toggle();
});
// Hide NavBar after 5s and show on rollover
//$('#navCol').hide("slide", { direction: "left" }, 1000);
//$('#navCol').show("slide", { direction: "right" }, 1000);
});
</script>
I know there's a lot of code there and you only really need 2 of the button ajax calls to see the method but it's worth pointing out that there are that many potential calls from buttons; so I included the whole file.
The Culprit Statement is at the end of pages.php:
<?php
}
if ($page !== 'home'){
pageDivs($dbc, $page, $lang);
} else{
blog($dbc, $lang);
include('../js/home.php');
}
?>
Now, what's strange is that only home works like this, so !=='home' is skipped and blog runs, proving that both $dbc and $lang are available. no button changes from this page.
But if I do this:
pageDivs($dbc, $page, $lang);
/*
if ($page !== 'home'){
} else{
blog($dbc, $lang);
include('../js/home.php');
}
*/
Then pageDivs() runs, proving that infact $page is set and available...
Edit
I should also point out that I started the If statement as just != and then later moved to !== and had no effect.
Edit2:
For Rasclatt, here is the button html output. I had to keep the href or my css breaks, but I can remove it and rewrite my css if it's gonna need to be buttons:
<div id="navCol" class="col-sm-1">
<!--nav in here-->
<ul id="mainNav" class="nav navbar">
<!--beginning of main list-->
<li class="nav navbar navbar-text">
<a id="home" href="#home" data-acton="#home" data-page="home" class="bbutt do-action active"> Home </a>
</li>
<li class="nav navbar navbar-text">
<a id="bio" href="#bio" data-acton="#bio" data-page="bio" class="bbutt do-action inactive"> Biography </a>
</li>
<li>
<div id="accordion1" class="accordion" role="tablist">
<div id="header-card" class="card accordion">
<div class="card-header accordion accordion-header work" role="tab" id="headingOne1">
<h5 class="mb-0"> <a id="work" class="do-action" data-page="work" data-toggle="collapse" data-acton="#work" href="#collapseOne1" role="button" aria-expanded="true" aria-controls="collapseOne1"> Work </a> </h5>
</div>
<div id="collapseOne1" class="collapse accordion" role="tabpanel" aria-labelledby="headingOne1" data-parent="#accordion1">
<div class='card-body accordion accordion-item inactive'>
<a id="install" data-page="install" class="do-action install" href="#install" data-acton="#install" class="subs first">
Installations
</a>
</div>
<div class='card-body accordion accordion-item inactive'>
<a id="write" data-page="write" class="do-action write" href="#write" data-acton="#write" class="subs">
Writing
</a>
</div>
<div class='card-body accordion accordion-item inactive'>
<a id="video" data-page="video" class="do-action video" href="#video" data-acton="#video" class="subs">
Video
</a>
</div>
<div class='card-body accordion accordion-item inactive'>
<a id="photo" data-page="photo" class="do-action photo" href="#photo" data-acton="#photo" class="subs last">
Photography
</a>
</div>
</div>
</div>
</div>
</li>
<li>
<div id="accordion2" class="accordion" role="tablist">
<div id="header-card" class="card accordion">
<div class="card-header accordion accordion-header2 works" role="tab" id="headingTwo1">
<h6 class="mb-0"> <a id="works" class="do-action" data-toggle="collapse" href="#collapseTwo1" data-acton="#workshops" data-page="works" role="button" aria-expanded="true" aria-controls="collapseTwo1">Workshops</a> </h6>
</div>
<div id="collapseTwo1" class="collapse accordion" role="tabpanel" aria-labelledby="headingTwo1" data-parent="#accordion2">
<div class='card-body accordion accordion-item inactive'>
<a id="child" data-page="child" class="do-action child" href="#child" data-acton="#child" class="subs first">
Children
</a>
</div>
<div class='card-body accordion accordion-item inactive'>
<a id="adols" data-page="adols" class="do-action adols" href="#adols" data-acton="#adols" class="subs">
Adolescents
</a>
</div>
<div class='card-body accordion accordion-item inactive'>
<a id="adult" data-page="adult" class="do-action adult" href="#adult" data-acton="#adult" class="subs last">
Adults
</a>
</div>
</div>
</div>
</div>
</li>
<li class="nav navbar navbar-text">
<a id="contact" href="#contact" data-acton="#contact" data-page="contact" class="bbutt do-action inactive"> Contact </a>
</li>
</ul>
</div>
when you load the page for the first time it goes on home which is fine, but when you click on other button (bio,work,etc.) it fetch the content of both because every time you include the js/home.php it executes the ajax function below along with the $('#other').click . due to which you end up making 2 ajax call
//Ajax Home Page on load
$.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
before including the page i suggest you to add extra flag variable just to skip ajax call to home
}
if ($page !== 'home'){
pageDivs($dbc, $page, $lang);
} else{
blog($dbc, $lang);
$donotloadhome = true;
include('../js/home.php');
}
and in the script add a varible too.
var skipflag = '<?php echo ($donotloadhome)?'call':''; ?>';
if(skipflag != 'call')
{
//Ajax Home Page on load
$.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
}
Couple things here; you have a PHP syntax anomaly in your javascript on this line:
var lang = '<?php echo $_GET['
lang ']; ?>';
try bringing it up on one line and remove spaces in the key name:
var lang = '<?php echo $_GET['lang']; ?>';
Secondly, you should not be repeating your JavaScript sections over and over. You can reduce it to one ajax function and then use other DOM elements to indicate your intentions to that function, for example:
<script>
// Wrap your stuff in one function and inject what you need that changes
function doAjaxCall(btn, page, lang)
{
// Set the query string
var dataTosend = 'page=' + page + '&lang=' + lang;
// If is obj do the button stuff
if(btn !== false) {
$('.active').addClass('inactive').removeClass('active');
btn.removeClass('inactive').addClass('active');
}
// Run the ajax and all that jazz
$('.content').fadeOut(500, function() {
$('.content').remove();
$.ajax({
url: "pages/pages.php",
cache: false,
type: 'POST',
data: dataTosend,
async: true,
}).done(function(html) {
$("#contentCol").append(html);
$('.content').fadeIn(1000);
});
});
}
// Set document ready
$(function(){
// Just send the language once, make sure to try and remove any possible
// user hackery...
var lang = '<?php echo htmlspecialchars($_GET["lang"], ENT_QUOTES) ?>';
// Run the default ajax on page load
doAjaxCall(false, 'home', lang);
// Just listen for one element on click now
$(this).on('click', '.do-action', function(){
// If the element that is being clicked is the same one that is going
// to have the .active done to it, then just use $(this) only
doAjaxCall($($(this).data('acton')), $(this).data('page'), lang);
});
});
//Collapse Dropdowns with other buttons
$('.bbutt').click(function() {
$('#collapseOne1').removeClass('show');
$('#collapseTwo1').removeClass('show');
});
$('#work').click(function() {
$('#collapseTwo1').removeClass('show');
});
$('#works').click(function() {
$('#collapseOne1').removeClass('show');
});
//debug
$('#console-debug').hide();
$('#btn-debug').on("click", function() {
$('#console-debug').toggle();
});
</script>
The trigger html would be something like this:
<!-- Add the "do-action" class to everything that you want to fire the ajax -->
<!-- Then you can put the page destination in the data attribute -->
<!-- Using $(this) probably would work in the js but, use the acton data attribute to send the intended object to act on -->
<button id="home" class="do-action" data-acton="#home" data-page="home">Home<button>
<button id="install" class="do-action" data-acton="#install" data-page="install">Install<button>
Anyway, by making only one function, you reduce the chances you will make a copy/paste error and will clean up your JS greatly.
Finally, since you are mixing all kinds of html/functions/business/view login together, you may want to wrap your PHP functions with a check for exists:
if(!function_exists('pageDivs')) {
function pageDivs($dbc, $id, $lang)
{
$r = mysqli_query($dbc, "SELECT * FROM content WHERE page='$id' AND status = 1");
while ($data = mysqli_fetch_assoc($r)): ?>
<div class="content" >
<?php echo ($lang =='FR')? $data['contentfr'] : $data['contenten'] ?>
</div>
<?php endwhile;
}
}
if(!function_exists('blog')) {
function blog($dbc, $lang)
{ ?>
<div class="bgImage homeImg">
<img src="images/bgs/1566337061.jpg">
</div>
<div class="gradient"></div>
<div class="col-md-12">
<?php
$r = mysqli_query($dbc, "SELECT * FROM blog WHERE status = 1 ORDER BY id DESC");
$i=0;
while($data = mysqli_fetch_assoc($r)):
$i++; ?>
<div id="post<?php echo $i; ?>" class="post snap">
<div class="postBox">
<article id="article<?php echo $i; ?>" class="article col-md-7">
<h3><?php echo $data['titleen'] ?></h3>
<?php echo $data['contenten']; ?>
</article>
<div id="pictureFrameLand<?php echo $i; ?>" class="pictureFrameLand col-md-4">
<img src="<?php
$q2 = "SELECT * FROM tbl_images WHERE image_id = ".$data['artimage'];
$r2 = mysqli_query($dbc, $q2);
$src= mysqli_fetch_assoc($r2);
echo $src['urlFront']
?>" />
</div>
<div class="gradientLand col-md-4"></div>
</div>
</div>
<div class="spacer snap"></div>
<?php endwhile ?>
</div>
<?php
}
}

I am using laravel5.5 Ajax paging. When I click on page second, It will output data in JSON format

I'm using laravel5.5 Ajax paging. I am the HTML part assembled in the controller. When I clicked on page second, I jumped to this method. How to make the compiled HTML code continue to display on the page?
After clicking on the second page, a string of JSON data is returned. This is a problem. How can we make the data on the second page continue to display in the original page?
PHP
//Screen video, playback volume and key points.
public function accept(Request $ request){
$id=$_GET['id'];
$summer=$_GET['key'];
$name=DB::table('vd_category')->where('address',$summer)->value('name');
if($id=='1'){
$video=DB::table('vd_video_'.$summer)->orderBy('state','desc')->paginate(25);
}else if($id=='2'){
$video=DB::table('vd_video_'.$summer)->orderBy('thumbs','desc')-
>paginate(25);
}
$data='';
foreach($video as $list){
$data.='<div class="col-md-1-5 col-sm-4 col-xs-6" style="padding:0
5px;"><div class="movie-item">';
$data.="<a style='position:relative;display:block;' title='$list-
>video_name' target='_blank' href='details?id=$list->id&key =$summer'>";
$data.="<img alt='$list->video_name' title='$list->video_name'
src=\"uploads/$list->image_address\" height=\"230px\" width='100%'>";
$data.="<button class='bdtag'></button>";
$data.="</a>";
$data.="<div class=\"meta\"><div
style=\"width:100%;overflow:hidden;height:20px;\">";
$data.="<a href='/details?id='$list->id'&key='$summer'
target='_blank' title='$list->video_name' class=\"movie-name\">$list-
>video_name</a>";
$data.="<span class=\"otherinfo\"> 5.0分</span></div><div
class=\"otherinfo\">类型:$name</div></div></div></div>";
}
$datav['1']=$data;
$datav['2']="<div>"."{$video->appends(['id' =>
$id,'key'=>$summer,'name'=>'page'])->links()}"."</div>";
return json_encode($datav);
}
HTML
<div id="data">
#foreach($video as $list)
<div class="col-md-1-5 col-sm-4 col-xs-6" style="padding:0 5px;">
<div class="movie-item">
<a style="position:relative;display:block;" title="{{$list-
>video_name}}" target="_blank" href="/details?id={{$list->id}}&key=
{{$status}}">
<img alt="{{$list->video_name}}" title="{{$list-
>video_name}}" src="{{asset('uploads')}}/{{$list->image_address}}"
height="230"
width="100%">
<button class="bdtag"></button>
</a>
<div class="meta">
<div style="width:100%;overflow:hidden;height:20px;"><a
href="/details?id={{$list->id}}&key={{$status}}" target="_blank" title="
{{$list-
>video_name}}" class="movie-name">{{$list->video_name}}</a><span
class="otherinfo"> 5.0分</span></div>
<div class="otherinfo">类型:{{$namme}}</div>
</div>
</div>
</div>
#endforeach
</div>
</div>
</div>
<div id="datav" style="background:#FFF;padding-left:15px;">
{{$video->appends(['id' => $page,'name'=>'page'])->links()}}
</div>
JavaScript
<select name="" required id="where_id" style="float: right;padding-
left:10px;border-left:8px;width: 90px;height: 30px;">
<option value="">Click screening</option>
<option value="1">Sort by play volume</option>
<option value="2">Ranking by points</option>
</select>
<input type="hidden" id="summer" value="{{$status}}">
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#where_id").change(function () {
var id=$("#where_id").val();
var summer=$("#summer").val();
$.ajax({
type:"get",
url:"accept",
dataType:'json',
data:{id:id,key:summer},
success:function (event){
$("#data").html(event[1]);
$("#datav").html(event[2]);
}
});
});
</script>
It has been solved.js has been modified.
That is, the parameters carried by the URL through the Ajax request to the
back-end again, and then the back-end returned JSON data inserted into the
specified location again, probably this is the solution, my English is not
very good, please forgive me.
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#where_id").change(function () {
fun();
});
function fun() {
var id=$("#where_id").val();
var summer=$("#summer").val();
$.ajax({
type:"get",
url:"accept",
dataType:'json',
data:{id:id,key:summer},
success:function (event){
$("#data").html(event[1]);
$("#datav").html(event[2]);
pagedata();
}
});
}
function pagedata(){
$(".page-item a").click(function (){
var href=this.href;
this.href="javascript:void(0);";
var id=getQueryVariable('page',href);
var key=getQueryVariable('key',href);
var page=getQueryVariable('page',href);
$.ajax({
type: "get",
url: "accept",
dataType: 'json',
data: {id: id, key: key,page:page},
success:function (event){
$("#data").html(event[1]);
$("#datav").html(event[2]);
pagedata();
}
})
})
}
// Intercept the parameter values carried by URL, such as page parameters
//and some custom parameters.
function getQueryVariable(name,url) {
var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
var data=url.slice(url.indexOf('?'));
var r =data.substr(1).match(reg);
if (r != null) {
return unescape(r[2]);
}
return null;
}
</script>

Div not showing in a jQuery Ajax Call

I have a page using bootstrap 3 framework that has a button which when pressed collects data from another page (mydata.php) with ajax and echoes it out within <div id="results"> on the page. The code works fine but as soon as I add <div class=\"col-xs-6\"> to mydata.php nothing appears on the page although I can see it within firebug.
If I change $("#results").append(html); to $("#results").text(html); the html echoes onto the page but as text without any formatting. If I remove <div class=\"col-xs-6\"> from mypage.php the data gets displayed on the page as expected. Why is the data from mydata.php not displayed when I add <div class=\"col-xs-6\">?
<div class="container">
<div class="row">
<div class="col-xs-12 col-centered">
<div class="col-xs-8 col-md-3 col-lg-3">
<button type="submit" name="btn" value="search" id="myButton" class="search_button btn btn-small btn-default btn-pull-right">Press</button>
</button>
</div>
</div>
</div>
<div class="row">
<div id="results"><!--data displayed here-->
</div>
</div><!--Row-->
</div><!--Cont-->
jQuery
$(document).ready(function(){
$(function() {
$("#myButton").click(function() {
var btn = $("#myButton").val();
var data = 'btn='+ btn;
// if location is not empty
if(data) {
// ajax call
$.ajax({
type: "POST",
url: "mydata.php",
data: data,
success: function(html){
$("#results").append(html);
}
});
}
return false;
});
});
});
mydata.php looks like this:
<?php
if (isset($_POST['btn'])) {
echo "
<div class=\"col-xs-6\">
<ul>
<li><h4>Data in this Div</h4></li>
</ul>
</div>
<div class=\"col-xs-6\">
<ul>
<li><h4>And Data in this Div</h4></li>
</ul>
</div>";
}
?>
if you do not add jQuery library then include it
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-xs-12 col-centered">
<div class="col-xs-8 col-md-3 col-lg-3">
<button type="submit" name="btn" value="search" id="myButton"
class="search_button btn btn-small btn-default btn-pull-right">Press
</button>
</button>
</div>
</div>
</div>
<div class="row">
<div id="results"><!--data displayed here-->
</div>
</div><!--Row-->
</div><!--Cont-->
<script>
$(document).ready(function () {
$(function () {
$("#myButton").click(function () {
var btn = $("#myButton").val();
var data = 'btn=' + btn;
// if location is not empty
if (data) {
// ajax call
$.ajax({
type: "POST",
url: "http://localhost/edit.php", // your file path
data: data,
success: function (html) {
$("#results").append(html); // if you want to replace results div then change $("#results").html(html);
}
});
}
return false;
});
});
});
</script>
it is working fine my side, i have tested in my local side
this is output:
Removing the ajax part works without problems... Are you sure you are receiving that exact HTML?
$('#result').append("<div class=\"col-xs-6\">"+
"<ul>"+
"<li><h4>Data in this Div</h4></li>"+
"</ul>"+
"</div>"+
""+
"<div class=\"col-xs-6\">"+
""+
"<ul>"+
"<li><h4>And Data in this Div</h4></li>"+
"</ul>"+
"</div>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result">
</div>
$('#myButton').on('click',function(){
var form = jQuery("#form");
$.ajax({
url: 'mydata.php',
type: 'POST',
data: form.serialize(),
cache: false,
dataType : 'json',
success: function(data){
if(data==true){
$("#results").append(data);
}
if(data==false){
}
},
error: function(){
}
});
return false;
});

Why is this facebook app refreshing endlessly

I kindly request that you help me identify the reason in the code why my app keeps refreshing endlessly. This does not allow me to navigate to other pages, Iam a learner in php and I suspect this could be the issue, help. Could it be a problem with the php arrangement?
Here is the code in index.php
<script type="text/javascript">
$(document).ready(function() {
$('#premium_b').click(function(e) {
e.preventDefault();
$('#tabs').tabs( "select" , 4 );
});
$('#tabs').bind('tabsselect', function(event, ui) {
if (ui.index == 4 )
$('#premium_b').css ('display', 'none');
else
$('#premium_b').css ('display', 'block');
});
});
</script>
<div id="bloc_134" class="li_bloc"><ul class="menu"><li>Home
</li>
<li>Config
</li>
<li>Customize
</li>
<li>Export
</li>
<li>Premium
</li>
<li>Statistics
</li>
<li>Doc
</li>
<li>About
</li>
<li>Other Apps
</li>
<li>FAQ
</li>
</ul>
Upgrade to Premium to get white branding and help us improve your favourite apps! : Click her
<div class="clear"></div>
</div>
</div>
<div id="alerts">
</div>
<div id="zone2" class="li_zone li_x1 li_y2">
<div id="contact_form_about"><div class="zone2">
</div></div>
<div id="contact_form_config"><div class="zone2"><script type="text/javascript">
function refreshApp (url) {
$.get(url, function(data) {
$('*').html(data);
});
}
$(document).ready(function() {
var options = {
success: showResponse,
beforeSubmit: disableButton
};
$('#tab_info_form_0').ajaxForm(options);
});
function addToPage() {
var obj = {
method: 'pagetab',
redirect_uri: 'https://apps.facebook.com/mtkenya-dev/?page_id=#contact_form_config',
};
FB.ui(obj);
}
</script>
<script>top.location.href='https://www.facebook.com/dialog/oauth?client_id=461688580525581&redirect_uri=https%3A%2F%2Fapps.facebook.com%2Fmtkenya-dev%2F%3Ftab%3Dcontact_form_config&scope=email,manage_pages'</script></div>
<div class="zone2"><script type="text/javascript">
$(document).ready(function() {
var options = {
success: showResponse,
beforeSubmit: disableButton
};
$('#contact_form').ajaxForm(options);
$('#customize_css').ajaxForm(options);
});
</script>
<div id="bloc_133" class="li_bloc"><p>Page non trouv?e</p>
</div>
</div>
</div>
<div id="contact_form_css"><div class="zone2"><script type="text/javascript">
function refreshApp (url) {
$.get(url, function(data) {
$('*').html(data);
});
}
$(document).ready(function() {
var options = {
success: showResponse,
beforeSubmit: disableButton
};
$('#tab_info_form_0').ajaxForm(options);
});
function addToPage() {
var obj = {
method: 'pagetab',
redirect_uri: 'https://apps.facebook.com/mtkenya-dev/?page_id=#contact_form_css',
};
FB.ui(obj);
}
</script>
<script>top.location.href='https://www.facebook.com/dialog/oauth?client_id=461688580525581&redirect_uri=https%3A%2F%2Fapps.facebook.com%2Fmtkenya-dev%2F%3Ftab%3Dcontact_form_css&scope=email,manage_pages'</script></div>
</div>
<div id="contact_form_doc"><div class="zone2"><script type="text/javascript">
$(function() {
$("#bloc_223").tabs({
ajaxOptions: {
error: function( xhr, status, index, anchor ) {
$( anchor.hash ).html( "Couldn't load this tab. We'll try to fix this as soon as possible. ");
}
},
cache: true
});
});
</script>
</div>
</div>
<div id="contact_form_export"><div class="zone2"><script type="text/javascript">
function refreshApp (url) {
$.get(url, function(data) {
$('*').html(data);
});
}
$(document).ready(function() {
var options = {
success: showResponse,
beforeSubmit: disableButton
};
$('#tab_info_form_0').ajaxForm(options);
});
function addToPage() {
var obj = {
method: 'pagetab',
redirect_uri: 'https://apps.facebook.com/mtkenya-dev/?page_id=#contact_form_export',
};
FB.ui(obj);
}
</script>
<script>top.location.href='https://www.facebook.com/dialog/oauth?client_id=461688580525581&redirect_uri=https%3A%2F%2Fapps.facebook.com%2Fmtkenya-dev%2F%3Ftab%3Dcontact_form_export&scope=email,manage_pages'</script></div>
<div id="footer" class="li_zone li_x1 li_y4"> </div>
</div>
</body>
</html>
Well, I see 3 times:
top.location.href=....
without any condition and not in a function call. That would certainly keep your page jumping.

Deleting a list item <li> with jquery?

I'm trying to delete a li item using jquery, but its not working. Here's my code:
the html file:
<li>
<img class="avatar" src="images/$picture" width="48" height="48" alt="avatar" />
<div class="tweetTxt">
<strong>$username</strong> $auto
<div class="date">$rel</div>
$reply_info
<div class="date"></div>
<a class ="delbutton" href="#" id = $id> Delete </a>
</div>
<div class="clear"></div>
</li>
The jquery file:
$(function () {
$(".delbutton").click(function () {
var del_id = element.attr("id");
var info = 'id=' + del_id;
if (confirm("Sure you want to delete this update? There is NO undo!")) {
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function () {}
});
$(this).parents(".record").animate({
backgroundColor: "#fbc7c7"
}, "fast")
.animate({
opacity: "hide"
}, "slow");
}
return false;
});
});
the delete.php file:
<?php
include("includes/connect.php");
if($_POST['id'])
{
$id=$_POST['id'];
$sql = "delete from {$prefix}notes where id='$id'";
mysql_query( $sql);
}
?>
There is no element in your HTML with a class of record. I would try something like this:
<li class="record">
<!-- a bunch of other stuff -->
<a class="delbutton" href="#">Delete</a>
</li>
then in the JS:
$(function ()
{
$(".delbutton").click(function ()
{
if (confirm("..."))
{
$.ajax({ /* ... */});
$(this).closest(".record").fadeOut();
}
return false;
});
});
If your div look like this:
<ul>
<li>One | <a href='#' class='delete'>Delete</a></li>
<li>Two | <a href='#' class='delete'>Delete</a></li>
<li>Three | <a href='#' class='delete'>Delete</a></li>
<li>Four | <a href='#' class='delete'>Delete</a></li>
</ul>
jQuery:
jQuery(document).ready(function(){
jQuery('.delete').live('click', function(event) {
$(this).parent().fadeOut()
});
});​
Check: http://jsfiddle.net/9ekyP/
EDIT:
You can remove your li after getting response in success function something like this:
jQuery(document).ready(function(){
jQuery('.delbutton').live('click', function(event) {
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function(){
$(this).parent().parent().fadeOut();
}
});
});
});​
There are several issues with your code...
element.attr("id") references undeclared element but this should probably be $(this).attr("id")
The <li> block has no class ".record" either
EDIT: You only fade your <li> but do not actually remove it from the DOM (don't know if this was deliberate though)
The <a>'s ID is not quoted (and not escaped either... as are the other strings you insert in PHP (EDIT) and the ID you use in your delete script - this is very dangerous as it allows cross-site scripting / XSS and SQL injection as TokIk already pointed out)
PHP:
echo '<li class="record">
<img class="avatar" src="images/'.htmlentities($picture).'" width="48" height="48" alt="avatar" />
<div class="tweetTxt">
<strong>'.htmlentities($username).'</strong> '.htmlentities($auto).'
<div class="date">'.htmlentities($rel).'</div>'.htmlentities($reply_info).'<div class="date"></div> <a class="delbutton" href="#" id="'.htmlentities($id).'"> Delete </a>
</div>
<div class="clear"></div>
</li>';
JavaScript:
$(document).ready(function() {
$(".delbutton").click(function(){
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
if(confirm("Sure you want to delete this update? There is NO undo!")) {
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function(){
alert('success');
},
error: function(){
alert('error');
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
EDIT: Delete script (note the additional error check that $_POST['id'] exists and the pseudo-function for quoting the ID):
<?php
include("includes/connect.php");
if( isset($_POST['id']) ) {
$id = quote($_POST['id']);
$sql = "delete from {$prefix}notes where id='$id'";
mysql_query( $sql);
}
?>
I am assuming that '.records' is the container.
You can pass through your ID value to make <li> unique, result being:
<li id='record_12'>
//CONTENT
</li>
<li id='record_13'>
//CONTENT
</li>
And change your SUCCESS script to the following:
$(".delbutton").click(function(){
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Sure you want to delete this update? There is NO undo!"))
{
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function(){
//Getting the unique LI and fading it out
$('#record_' + del_id).fadeOut();
}
});
Your code works fine well.I was trying to code a form that has multiple textbox, then after each textbox threre will be link called add which POST call the other php called addnew.php.
In addnew.php data will we added to database(postgres). But I am geting problem while getting the post variable itself.
this is my code for form (I will chage for multiple textbox once it works fine)
script:
<script type='text/javascript'>
$(window).load(function() {
jQuery(document).ready(function() {
jQuery('.add').live('click', function(event) {
var da = $('form#myform').serialize();
alert(da);
$.ajax({
type: "POST",
url: "addnew.php",
data:da,
success: function(data) {
if (data === "ok") {
$(this).parent().fadeOut();
$('#results').html(data);
}
else {
alert(data);
}
}
});
});
});
});
Form
<form name='myform' id='myform'>
<input name='da' type='text' id='da' value='none'>
<a href='#' class='add'>Add</a>
</form>
addnew.php code here
<? php
if( isset($_POST['da']) )
{
echo (da);
}
?>

Categories