How to refresh images without page reloading after ajax call? - php

I have a script below that uploads images to the server. Upon completion it updates the img source by html. The issue I'm having is that I wrote my php code to rename the files to a predefined name (ext-pix0.png, ext-pix1.png, ext-pix3.png, etc.) when they are being uploaded. Because of this, the pictures on the screen won't refresh even though the new images replaced the old ones when uploading is done. I also turn off no cache, but it doesn't work. How do I get around this issue?
SCRIPT
<script>
$('input[name="ext_pix[]"]').on('change',function(){
var account_list = $('#account_list').val();
var order_list = $('#order_list').val();
var id_list = $('#id_list').val();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url: 'sql/ext-pix-upload.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success:function(data){
$('#ext-pix0').html('<img src="accounts/'+account_list+'/'+order_list+'/pix/'+id_list+'/ext-pix0.png" height="103.5%" width="100%"/>').fadeIn(500);
$('#ext-pix1').html('<img src="accounts/'+account_list+'/'+order_list+'/pix/'+id_list+'/ext-pix1.png" height="103.5%" width="100%"/>').fadeIn(500);
$('#ext-pix2').html('<img src="accounts/'+account_list+'/'+order_list+'/pix/'+id_list+'/ext-pix2.png" height="103.5%" width="100%"/>').fadeIn(500);
$('#ext-pix3').html('<img src="accounts/'+account_list+'/'+order_list+'/pix/'+id_list+'/ext-pix3.png" height="103.5%" width="100%"/>').fadeIn(500);
},
error: function(data){
}
});
});
</script>
HTML
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate"/>
<meta http-equiv="Pragma" content="no-cache"/>
<meta http-equiv="Expires" content="0"/>
<form>
<div class="card-wrapper">
<div class="card mt-3">
<h5 class="card-header pb-2">Exterior Pictures</h5>
<div class="card-block" style="height:322px">
<div style="height:50%">
<div id="ext-pix0" class="ext-pix">
<img src="images/profile/property-pix.png" height="103.5%" width="100%"/>
</div>
<div id="ext-pix1" class="ext-pix">
<img src="images/profile/property-pix.png" height="103.5%" width="100%"/>
</div>
</div>
<div class="lower-row">
<div id="ext-pix2" class="ext-pix">
<img src="images/profile/property-pix.png" height="103%" width="100%"/>
</div>
<div id="ext-pix3" class="ext-pix">
<img src="images/profile/property-pix.png" height="103%" width="100%"/>
</div>
</div>
<div class="ext-btn">
<input id="ext_pix" class="hidden" name="ext_pix[]" type="file" accept="image/*" multiple/>
<label class="gi gi-camera mb-0 text-white" for="ext_pix" title="Change Picture"></label>
</div>
</div>
</div>
</div>
</form>

Clear the images first?
success:function(data){
$('#ext-pix0').html('');
$('#ext-pix1').html('');
$('#ext-pix2').html('');
$('#ext-pix3').html('');
$('#ext-pix0').html('<img src="accounts/'+account_list+'/'+order_list+'/pix/'+id_list+'/ext-pix0.png" height="103.5%" width="100%"/>').fadeIn(500);
$('#ext-pix1').html('<img src="accounts/'+account_list+'/'+order_list+'/pix/'+id_list+'/ext-pix1.png" height="103.5%" width="100%"/>').fadeIn(500);
$('#ext-pix2').html('<img src="accounts/'+account_list+'/'+order_list+'/pix/'+id_list+'/ext-pix2.png" height="103.5%" width="100%"/>').fadeIn(500);
$('#ext-pix3').html('<img src="accounts/'+account_list+'/'+order_list+'/pix/'+id_list+'/ext-pix3.png" height="103.5%" width="100%"/>').fadeIn(500);
},

Why don't you try to update img element in html file with id, inside the onSuccess() of ajax.
<img id="img_id" src="#"/>
OnSuccess function of Ajax,
success: function (data) {
$("#img_id").attr("src", data.pictureUrl);
}

Try like this:
success:function(data){
$('#ext-pix0').fadeOut('500', function(){
$(this).find("img").attr("src", "accounts/'+account_list+'/'+order_list+'/pix/'+id_list+'/ext-pix0.png");
$(this).fadeIn(500);
});
$('#ext-pix1').fadeOut('500', function(){
$(this).find("img").attr("src", "accounts/'+account_list+'/'+order_list+'/pix/'+id_list+'/ext-pix1.png");
$(this).fadeIn(500);
});
$('#ext-pix2').fadeOut('500', function(){
$(this).find("img").attr("src", "accounts/'+account_list+'/'+order_list+'/pix/'+id_list+'/ext-pix2.png");
$(this).fadeIn(500);
});
$('#ext-pix3').fadeOut('500', function(){
$(this).find("img").attr("src", "accounts/'+account_list+'/'+order_list+'/pix/'+id_list+'/ext-pix3.png");
$(this).fadeIn(500);
});
},

Please update what response you are getting in data in success function and update the src element only in ajax success. OR instead assign some class or ID to img tag and update only the src element.
<img class="ext-pix0" id="ext-pix0" src="images/profile/property-pix.png" height="103.5%" width="100%"/>
updated Script
success:function(data)
{
for(vari=0;i<data.length.i++)
{
$('#ext-pix'+i).attr(src,'data[i].url').fadeIn(500);
}
},

fadeOut "$('#ext-pix...')" before calling AJAX
success:function(data){
for(i=0;i<=3;i++){
$('#ext-pix'+i).html('');
let Image = $('<img/>',{src:'accounts/'+account_list+'/'+order_list+'/pix/'+id_list+'/ext-pix'+i+'.png' , style:'height:103.5%;width:100%';});
$('#ext-pix'+i).html(Image).fadeIn(500);
}
},

Related

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;
});

Ajax not posting the variable to another page

Hi I have problem of sending my variable to another PHP page using ajax.
My problem is am getting the id of the element from main page. Its for edit operation.
Main page modal:
<a href='javascript:' data-id={$row['customer_id']} class='btn small bg-blue-alt tooltip-button modal-customeredit' data-placement='top' title='Edit'><i class='glyph-icon icon-edit' ></i>
</a>
it will open modal on same page:
<div class="hide" id="modal-projedit" title="Edit Project Info">
<div class="pad10A">
<h3>Edit Project Info</h3>
<p class="font-gray-dark"> Fides Admin uses colors & styles from both the default theme color schemes and the included core color helpers. </p>
<div class="divider mrg25B"></div>
<form id="project-edit" action="" class="col-md-12 center-margin" method="">
<div class="form-row">
<div class="form-label col-md-3">
<label for="name">
Project Name:
<span class="required">*</span>
</label>
</div>
<div class="form-input col-md-9">
<input id="project_name" name="project_name" placeholder="Name" data-required="true" class="parsley-validated" type="text">
</div>
</div>
<div class="divider"></div>
<div class="form-row">
<div class="form-input col-md-8 col-md-offset-3">
<a href="javascript:;" class="btn medium primary-bg radius-all-4" id="project-edit-valid" onclick="javascript:$('#project-edit').parsley( 'validate' );" title="Validate!">
<span class="button-content">
Update
</span>
</a>
</div>
</div>
</form>
</div>
</div>
SCRIPT:
$( ".modal-customeredit" ).click(function() {
var myGroupId = $(this).data('id');
alert( myGroupId);
$.ajax({
type: "POST",
url: "sample.php",
data: { id: myGroupId }, // data retrieve on server-side ($_POST['id'])
})
$( "#modal-customeredit" ).dialog({
modal: true,
minWidth: 700,
minHeight: 200,
dialogClass: "modal-dialog",
show: "fadeIn"
});
$('.ui-widget-overlay').addClass('bg-black opacity-60');
});
});
Try the following:
Change the ajax function,
var myGroupId = $(this).attr('data-id'); // data-id
data = {'id':myGroupId };
$.ajax({
type: "POST",
url: "sample.php",
data: data, // data retrieve on server-side ($_POST['id'])
success:function(response){
alert(response); //do the rest of operations.
}
});
You didn't mention what the alert says.
Though I guess it shows a Null value since the ajax request seems good.
My bet goes for your selector, try this :
var myGroupId = $(this).attr('data-id');
HTML (with quotes) :
<a href="javascript:void(0)" data-id="{$row['customer_id']}" class="...">
<i class='glyph-icon icon-edit' ></i>
</a>
jQuery (width data-id and callback):
$( ".modal-customeredit" ).click(function() {
var myGroupId = $(this).attr('data-id'); // data-id
$.ajax({
type: "POST",
url: "sample.php",
data: { id: myGroupId },
}).done(function(response) { // data returned by server
var d = $('<div id="dialog">'+response+'</div>').appendTo('body');
d.load(function(){
$( "#dialog").dialog({
modal: true,
minWidth: 700,
minHeight: 200,
dialogClass: "modal-dialog",
show: "fadeIn"
});
$('.ui-widget-overlay').addClass('bg-black opacity-60');
});
});
});
You will not get the value because you are using echo to your php code in data-id attribute.
This is what you need to do to your html
<a href="javascript:void(0)" data-id="<?php echo $row['customer_id']?>" class="...">
<i class='glyph-icon icon-edit' ></i>
</a>
and use #seenath's code to check if you get the value

jQuery AJAX response not displaying PHP

I don't know what I am doing wrong, but the PHP does run (I can notice it with the POST data on Firebug), but isn't echoed.
Here's my JS file :
$('.table_item').click(function() {
var ticket_nbr = $(this).children('td').attr("class");
var dataString = 'ticket_nbr='+ ticket_nbr;
$.ajax({
url: 'display.php',
type: 'POST',
data: dataString,
success: function(data) {
console.log(data);
$("#DisplayTicket").modal('setting', 'transition', 'vertical flip').modal('show');
},
error: function(e) {
console.log(e)
}
});
});
and the called PHP file :
if($_POST)
{
$ticket_nbr=$_POST['ticket_nbr'];
?>
<div id="DisplayTicket" class="ui large modal transition active visible" style="margin-top: -110px;">
<i class="close icon"></i>
<div class="header">
<?php echo $ticket_nbr; ?>
</div>
</div>
<?php
}
And here's the output I get on Firebug :
<div id="DisplayTicket" class="ui large modal transition hidden" style="margin-top: -110px;">
<i class="close icon"></i>
<div class="header">
ticket_3 // The post data sent
</div>
<div class="content">
<p>Merci, <span class="test_display"></span>.
</div>
</div>
Any help or hint would be great !
Thanks.
You're returning HTML but never adding it to body
success: function(data) {
console.log(data);
$(data).appendTo('body'); // <----------------------
$("#DisplayTicket").modal('setting', 'transition', 'vertical flip').modal('show');
},
Also, ideally dataString = 'ticket_nbr='+ ticket_nbr should be dataString = {'ticket_nbr': ticket_nbr}
You have to show/append the below div in the body or div.
<div id="DisplayTicket" class="ui large modal transition active visible" style="margin-top: -110px;">
<i class="close icon"></i>
<div class="header">
<?php echo $ticket_nbr; ?>
</div>
</div>
then use the below code on success.
$('#DisplayTicket').addClass('active');
$('#DisplayTicket').css('visibility','visible');

ajax php GET/POST without refresh

I need to execute the following code, without refreshing the page... this code already includes ajax but where am I going wrong with getting it to execute without refreshing the page....? the .vote class is attatched to an anchor in my index.php file, and I need this all to still work when the anchor is clicked if possible. Re-coding this to perform on a button click would not be ideal.
$(".vote").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var eData = $(this).attr("data-options");
var dataString = 'id='+ id + '&' + eData ;
var parent = $(this);
if(name=='up')
{
$(this).fadeIn(200).html('');
$.ajax({
type: "POST",
url: "up.php",
data: dataString,
cache: false,
success: function(html){
parent.html(html);
}
});
}
else
{
$(this).fadeIn(200).html('');
$.ajax({
type: "POST",
url: "down.php",
data: dataString,
cache: false,
success: function(html){
parent.html(html);
}
});
}
});
here is the html from my index.php
<div id="main">
<div id="left">
<span class='up'><img src="up.png" alt="Down" /></span><br />
<?php echo $totalvotes1; ?><br />
</div>
<div id="message">
<?php echo $message1; ?>
</div>
<div class="clearfix"></div>
</div>
<div id="main">
<div id="right">
<br />
<?php echo $totalvotes2; ?><br />
<span class='down'><img src="down.png" alt="Down" /></span>
</div>
<div id="message">
<?php echo $message2; ?>
</div>
<div class="clearfix"></div>
</div>
You need to either enclose your code with $(document).ready(function() {});, or stick your code at the end of the <body> tag. Personally, instead of making the browser parse synchronous javascript before the DOM has loaded (in the <head> section), I stick it near the end. This is also what Bootstrap recommends.
Without a DOM loaded, there are no elements created for jQuery to register Events with, and so your code literally sits there doing nothing after being parsed.
Aside from that, the .click() function is executed on click. It doesn't matter what element it's bound to. If it's clickable, it's executable.
Also to answer your question properly: <a href=""> will refresh the page. You want to use
<a href="#">. This, however, will make you jump to the top of the page. You could also define a <label> and use #labelname instead to avoid this. Or just don't use href at all. It's not needed.
Also, a little trick for echoing variables into HTML is to use <?= $var ?>

Categories