I have a div element which is populated by the query result(in index.php). I have also another file widget.php which has same query to update page. I have variable in widget.php "page" which navigates through the pages. If I use widget.php?page=2 it will load next page with results. I want to update a div element in index.php on click.(Click "next" and show another 8 news without reloading page).
in index.php :
<button type="button" id="prevbutton">Previous</button>
<button type="button" id="nextbutton">Next</button>
<div id="list"></div>
in script.js:
$("#prevbutton, #nextbutton").click(function () {
var id_name = $(this).attr('id');
var page = 0;
if (id_name == '#prevbutton' || id_name == '#nextbutton') {
if (id_name == '#prevbutton') {
page -= 1;
}
if (id_name == '#nextbutton') {
page +=1;
}
}
$.ajax({
url: 'widget.php',
type: 'GET',
data: "page=" + page,
success: function (data) {
//called when successful
$("#list").html(data);
},
error: function (e) {
//called when there is an error
//console.log(e.message);
}
});
});
in widget.php :
<?php
header("Cache-Control: public, max-age=60");
include("logindb.php");
$page = $_GET['page'];
$page = $page*9;
?>
<div id="list">
<?php
$abfrage59 = "SELECT n.news_title,n.news_id,FLOOR(TIMESTAMPDIFF(HOUR, n.timestamp, NOW())) as diff
FROM news n
WHERE n.domain_id = '2' AND n.timestamp < NOW()
ORDER BY timestamp DESC
LIMIT $page,9";
$ergebnis59 = mysql_query($abfrage59);
while ($row59 = mysql_fetch_object($ergebnis59)) {
$newstitleslug = $row59->news_title;
$newstitleslug = str_replace(' ', '-', $newstitleslug);
$newstitleslug = strtolower($newstitleslug);
echo "<div class=\"col-sm-6 col-md-4\" style=\"padding-bottom: 15px;\">
<div class=\"item\">
<img class=\"main\" src=\"http://www.example.com/news/$row59->news_id.png\" />
<div class=\"text\">
<div class=\"inner\">
<a href=\"http://www.example.com/$newstitleslug/$row59->news_id/\" style=\"color:white;\">$row59->news_title<br />
<span class=\"date\">$row59->diff hours ago</span>
</div>
</div>
</div>
</div>";
}
?>
<?php
include("close_connect.php");
?>
So I want to update value $page on click and refresh content of DIV with new data. Thanks in advance.
Edit: removed script from script.js and put in the end of the index.php body:
<script>
$("#prevbutton, #nextbutton").click(function () {
var id_name = $(this).attr('id');
var temppage = 1;
if (id_name == 'prevbutton' || id_name == 'nextbutton') {
if (id_name == 'prevbutton') {
temppage -= 1;
}
if (id_name == 'nextbutton') {
temppage +=1;
}
var page = temppage;
}
$.ajax({
url: 'widgets/news_archive_widget.php',
type: 'GET',
data: "page=" + page,
success: function (data) {
//called when successful
$("#list").html(data);
},
error: function (e) {
//called when there is an error
//console.log(e.message);
}
});
});
</script>
Remove the # you're prefixing to prevButton and nextButton as $(this).attr('id') will return the id without the #. The value of id_name will either be prevButton or nextButton.
UPDATE:
Your final js script should look like this:
$("#prevbutton, #nextbutton").click(function () {
var id_name = $(this).attr('id');
var page = $("#currPageNumber").val();
if (id_name == 'prevbutton' || id_name == 'nextbutton') {
if (id_name == 'prevbutton') {
page -= 1;
}
if (id_name == 'nextbutton') {
page +=1;
}
}
$.ajax({
url: 'widget.php',
type: 'GET',
data: "page=" + page,
success: function (data) {
//called when successful
$("#list").html(data);
},
error: function (e) {
//called when there is an error
//console.log(e.message);
}
});
});
PHP script:
<?php
header("Cache-Control: public, max-age=60");
include("logindb.php");
$page = $_GET['page'];
$page = $page*9;
?>
<div id="list">
<?php
$abfrage59 = "SELECT n.news_title,n.news_id,FLOOR(TIMESTAMPDIFF(HOUR, n.timestamp, NOW())) as diff
FROM news n
WHERE n.domain_id = '2' AND n.timestamp < NOW()
ORDER BY timestamp DESC
LIMIT $page,9";
$ergebnis59 = mysql_query($abfrage59);
while ($row59 = mysql_fetch_object($ergebnis59)) {
$newstitleslug = $row59->news_title;
$newstitleslug = str_replace(' ', '-', $newstitleslug);
$newstitleslug = strtolower($newstitleslug);
echo "<div class=\"col-sm-6 col-md-4\" style=\"padding-bottom: 15px;\">
<div class=\"item\">
<img class=\"main\" src=\"http://www.example.com/news/$row59->news_id.png\" />
<div class=\"text\">
<div class=\"inner\">
<a href=\"http://www.example.com/$newstitleslug/$row59->news_id/\" style=\"color:white;\">$row59->news_title<br />
<span class=\"date\">$row59->diff hours ago</span>
</div>
</div>
<input type='hidden' value='".$_GET['page']."' id='currPageNumber'>
</div>
</div>";
}
?>
<?php
include("close_connect.php");
?>
Related
Hello I am new here and working on a project that requires this option of "Viewing content in DIV .posts_area, from database using AJAX",
I had a problem that the content I get in .posts_area sometimes duplicate itself.
Can anyone help me with the solution and I would also be happy for more detailed explanation about the subject.
// AJAX in
<script type="text/javascript">
$(document).ready(function() {
var flag = 0;
$.ajax({
type: 'GET',
url: 'getData.php',
data: {
'offset': 0,
'limit': 6
},
async: true,
success: function(data) {
$('.posts_area').append(data);
flag += 3;
}
});
$(window).scroll(function() {
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
$.ajax({
type: 'GET',
url: 'getData.php',
data: {
'offset': flag,
'limit': 5
},
success: function(data) {
$('.posts_area').append(data);
flag += 3;
}
});
}
});
});
</script>
//getData.php
<?php
include ('config/config.php');
include 'includes/classes/user.php';
include 'includes/classes/post.php';
if(isset($_GET['offset']) && isset($_GET['limit'])){
$limit = $_GET['limit'];
$offset = $_GET['offset'];
$data = mysqli_query($con,"SELECT * FROM posts WHERE deleted='no' ORDER by id DESC LIMIT {$limit} OFFSET {$offset} ");
if(mysqli_num_rows($data ) > 0) {
while($row = mysqli_fetch_array($data) ){
$id = $row['id'];
$comments_check = mysqli_query($con, "SELECT * FROM comments WHERE post_id='$id'");
$comments_check_num = mysqli_num_rows($comments_check);
?>
<script>
function myFunction<?php echo $id; ?>() {
var x = document.getElementById("toggleComment<?php echo $id; ?>");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
</script>
<?php
$added_by_user = $row['added_by_user'];
$post_profile_pic = $row['post_profile_pic'];
$added_by = $row['added_by'];
$body = $row['body'];
$date_time = $row['date_added'];
$user_session = $_SESSION['user'];
if($user_session == $added_by_user)
$delete_button = "<form action = 'delete_post.php?id=$id' method='POST' id = 'delete_post_id_form'>
<input type ='submit' class = 'delete_post_class_input' id = 'delete_post_id_input' value = 'Delete'></input>
</form>";
else
$delete_button = "";
// if($user_session == $added_by_user)
// $update_button = "<form action = 'update_post.php?post_id=$id' method='POST'>
// <input type ='submit' class = 'update_post_class' id = 'update_post_id' value = 'Update'></input>
// </form>";
// else
// $update_button = "";
$str .= "<div class='status_post' >
<div class='on_post_profile_pic_class' id = 'on_post_profile_pic_id'>
<a href='$added_by_user' class='posted_by_on_img'><img src='$post_profile_pic' width='50' id = 'on_post_profile_img_id'></img></a>
</div>
<div class='posted_by1' id='added_by_on_post' style='color:#ACACAC;'>
<a href='$added_by_user' class='posted_by'> $added_by </a>
</div>
<img src='assets/images/icons/more_info_button_black_down.png' onClick='show_hide()'alt='more_info_on_post_button_black_down_button_alt' class='more_info_on_post_button_black_down_btn' id ='more_info_on_post_button_black_down_btn_id' name ='more_info_name'></img>
<img src='assets/images/icons/more_info_button_black_up.png' alt='more_info_on_post_button_black_up_button_alt' class='more_info_on_post_button_black_up_btn' id ='more_info_on_post_button_black_up_btn_id'></img>
<div class = 'date_added_on_post_class' id = 'date_added_on_post_id'>$date_time</div>
<div class = 'update_post_class' id = 'update_post_id'>$update_button</div>
<div class = 'delete_post_class_div' id = 'delete_post_id'>$delete_button</div>
<div id='post_body' dir=auto>
$body
</div>
</div>
</div>
<div class='span_class' id='span_id' onclick='myFunction$id()' >Comments($comments_check_num) </div>
<hr>
<div class='post_comment' id='toggleComment$id' >
<iframe src='comment_frame.php?post_id=$id' class = 'comment_iframe_class' id='comment_iframe' frameborder='0'></iframe>
</div>
<hr class ='hr'>";
}
echo $str;
}
}
?>
$('.posts_area').html(data);
Use this instead of append()
How do you update multiple progress bars when posting a form via ajax? Here is the code I have but I can't figure it out:
Form code:
<form id="upload-form" class="no-padding" method="post" enctype="multipart/form-data">
<p><label for="folder">Create folder:</label><input type="text" name="folder" placeholder="Enter a folder name"></p>
<p><label for="file">Create file:</label><input type="text" name="file" placeholder="Enter a file name with extension (e.g. home.php)"></p>
<p class="no-margin">Upload file(s):</p>
<div class="custom-upload">
<input id="upload" type="file" name="upload[]" multiple>
<div class="fake-file">
<a class="browse text-center"><i class="fa fa-list"></i> Browse</a><input placeholder="No file(s) selected..." disabled="disabled" >
</div>
</div>
<div id="selectedFiles" class='selectedFiles'></div>
<?php echo "<input name='url' hidden value='" . $_SERVER['REQUEST_URI'] ."'>";?>
<button id="submit" name="submit"><i class="fa fa-upload"></i> Upload</button>
<p id="uploading" class='success text-right' hidden>Please be patient while your files are uploading.</p>
</form>
Javascript code:
var selDiv = "";
document.addEventListener("DOMContentLoaded", init, false);
function init() {
document.querySelector('#upload').addEventListener('change', handleFileSelect, false);
selDiv = document.querySelector("#selectedFiles");
}
var files, filesToUpload;
// populates files into array (filesToUpload) and displays selected files to the user
function handleFileSelect(e) {
if(!e.target.files) return;
selDiv.innerHTML = "";
var files = e.target.files;
filesToUpload = Array.prototype.slice.call(files);
if (files.length > 0) {
selDiv.innerHTML += '<p id="file-upload-paragraph" class="no-padding no-margin">Files selected for upload. Click the <b>x</b> to cancel file upload for a specific file:</p>';
}
for(var i = 0; i < files.length; i++) {
var f = files[i];
selDiv.innerHTML += '<div class="selectedFiles"><i class="fa fa-remove"></i><progress id="progress' + i + '" class="text-right" value="0" hidden></progress><span class="file-holder">' + f.name + ' <i class="fa fa-file"></i></span></div>';
}
}
// removes user selected file before upload
$(document).on('click', '.cancel', function () {
filesToUpload.splice($(".cancel").index(this), 1);
$(this).closest('div').remove();
if (filesToUpload.length == 0) {
$('#file-upload-paragraph').remove();
$('.custom-upload input[type=file]').val('');
}
$('.custom-upload input[type=file]').next().find('input').val(filesToUpload.length + ' files selected!');
});
// sets progress bar for each loaded file
$('#upload-form').submit(function(e){
e.preventDefault();
var url = location.href;
$("#upload").remove();
$(".cancel").hide();
$("progress").show();
var data = new FormData($('form')[0]);
if (filesToUpload.length != 0) {
for (var i = 0, j = filesToUpload.length; i < j; i++) {
data.append("upload[]", filesToUpload[i]);
}
}
$.ajax({
url: url,
type: 'POST',
data: data,
cache: false,
contentType: false,
processData: false,
xhr: function(progress) {
for (var i = 0, j = filesToUpload.length; i < j; i++) {
var progressBar = 'progress' + i;
if(document.getElementById(progressBar) == null) {
j++;
continue;
}
var xhr = new XMLHttpRequest();
(function(progressBar) {
xhr.upload.onprogress = function(e) {
$('#' + progressBar).attr({value: e.loaded, max: e.total});
};
}(progressBar));
}
return xhr;
},
success: function(res){
if(!res.error) location.reload(true);
}
});
});
PHP code:
// function call
uploadFiles(count($_FILES["upload"]["name"]), $_FILES["upload"]["tmp_name"], $_FILES["upload"]["name"], $path);
// function that uploads selected files
function uploadFiles($total, $tmpFiles, $uploadedFiles, $path) {
for($i=0; $i < $total; $i++) {
$tmpFilePath = $tmpFiles[$i];
if ($tmpFilePath != ""){
$newFilePath = "$path/" . $uploadedFiles[$i];
if(file_exists($newFilePath)) {
unlink($newFilePath);
}
move_uploaded_file($tmpFilePath, $newFilePath);
}
}
}
Here is a picture of the form, just in case:
Form image
Thanks in advance for any help.
I don't know if anyone will be looking to do the same thing but I found my own answer. Basically, replace my initial code for catching when the form is submitted with the following:
// sets progress bar for each loaded file
$('#upload-form').submit(function(e){
e.preventDefault(); // removes the default behavior of the form button
var url = location.href; // returns the current location
$("#upload").remove(); // removes the file upload box which is replaced with an array in my other code
$(".cancel").hide(); // hides the cancel buttons
$("progress").show(); // shows the hidden progress bars
// checks to see if files were selected for being uploaded
if (filesToUpload.length != 0) {
var progressBars = [];
// this loop accounts for files that were deleted after selection
for (var i = 0, j = filesToUpload.length; i < j; i++) {
if(document.getElementById('progress' + i) == null) {
j++;
continue;
}
progressBars.push(i);
}
// call to postNext function
postNext(0, progressBars, url);
// executes when only the other form elements are submitted with no file upload
} else {
var data = new FormData($('form')[0]);
$.ajax({
url: url,
type: 'POST',
data: data,
cache: false,
contentType: false,
processData: false,
success: function(res){
if(!res.error) location.reload(true);
}
});
}
});
// posts each file separately
function postNext(i, progressBars, url) {
// continues as long as there are more files to display progress bars
if (i < progressBars.length) {
var index = progressBars[i];
var data = new FormData($('form')[0]);
// after first ajax send, resets form so only the remaining file uploads are resubmitted
if (i == 0) {
$("#upload-form")[0].reset();
}
data.append("upload[]", filesToUpload[i]); //append the next file
$.ajax({
url: url, // url for post
type: 'POST',
data: data,
cache: false,
contentType: false,
processData: false,
xhr: function(progress) {
// set the progress for a given progress bar
var xhr = new XMLHttpRequest();
var progressBar = 'progress' + index;
(function(progressBar) {
xhr.upload.onprogress = function(e) {
$('#' + progressBar).attr({value: e.loaded, max: e.total});
};
}(progressBar));
return xhr;
},
beforeSend: postNext(i + 1, progressBars, url) // begins next progress bar
});
}
}
// refreshes the page only after all ajax requests are completed
$(document).bind("ajaxSend", function () {
console.log("waiting for all requests to complete...");
}).bind("ajaxStop", function () {
location.reload(true);
});
I want to add photos dynamically but I have a problem, I confused where fix this error.
This error is:
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
This is my pages index.html
<?php
//Foto_ID
$dr = (rand(100,10000));
$ymdhis = date("ymdhis");
$rd = $dr.$ymdhis;
?>
<div id="main-content2">
<script>
var maxSlide = 5;
var curSlide = 1;
var Ids = 1;
var ajaxCheckInterval = "";
function readImage(input,ids)
{
if (input.files && input.files[0])
{
var reader = new FileReader();
reader.onload = function (e) {
$('#img_'+ids).attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
function generateSlide()
{
if( curSlide <= maxSlide )
{
var html ='<br/><div id="slideAdd_'+Ids+'" >';
html+=' <form action="#" id="slide_'+Ids+'" class="form-horizontal" enctype="multipart/form-data">';
html+=' <div class="form-group">';
html+=' <label class="col-sm-3 control-label">Foto Barang</label>';
html+=' <div class="col-sm-9">';
html+=' <input type="hidden" name="ft_'+Ids+'" id="ft_'+Ids+'" value="<?php echo $rd ?>">';
html+=' <input type="hidden" name="ur_'+Ids+'" id="ur_'+Ids+'" value="'+Ids+'" >';
html+=' <input onChange="readImage(this,'+Ids+')" type="file" id="foto_'+Ids+'" name="foto_'+Ids+'" />';
html+=' <img src="images/noimage.jpg" id="img_'+Ids+'" style="width: 300px; height: 250px;" />';
html+=' </div>';
html+=' </div>';
html+=' <div class="form-group">';
html+=' <div class="col-sm-9 col-sm-offset-3 col-lg-10 col-lg-offset-2">';
html+=' <button onClick="removeSlide(\''+Ids+'\'); return false;" class="btn btn-danger"><i class="fa fa-times"></i> Remove</button>';
html+=' </div>';
html+=' </div>';
html+=' </form>';
html+='</div><br/>';
$("#main-content2").append(html);
curSlide++;
Ids++;
}
else
{
}
}
function removeSlide(Ids)
{
$('#slideAdd_'+Ids).slideUp('slow');
setTimeout(function(){ $('#slideAdd_'+Ids).remove(); }, 2000);
curSlide--;
}
function getSlide()
{
showLoading("show");
ajaxCheckInterval = setInterval(function(){ redirectMe() }, 1000);
var a = 1;
for( var i = 0; i <= Ids; i++ )
{
try{
var formData = new FormData();
formData.append("file", $( '#foto_'+i )[0].files[0]);
formData.append("ft", $( '#ft_'+i ).val()) ;
formData.append("ur", $( '#ur_'+i ).val()) ;
uploadSlide(formData,i,Ids);
a++;
}catch(e){
}
}
}
function redirectMe()
{
if($.active == 0){
setTimeout(function(){
showLoading("show");
myStopFunction();
window.location.href = "barang";
}, 1000);
}
}
function myStopFunction() {
clearInterval(ajaxCheckInterval);
}
function uploadSlide(formData,x,Ids2)
{
$.ajax({
url: 'crud.php?type=Foto_Barang',
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(response) {
if( response != "OK" )
{
// Error In Here
dataSlide = JSON.parse(response);
}
}
});
}
function showLoading( type )
{
if( type == "show" )
{
var html = '';
html += '<div id="loader">';
html += '<div id="loadOver" class="loadOver"></div>';
html += '<div class="loading">';
html += '<img src="images/animatedCircle.gif" />';
html += '</div></div>';
$('body').append(html);
}
else
{
$('#loader').remove();
}
}
</script>
</div>
<center>
<button type="button" class="btn btn-success" onClick="generateSlide()" ><i class="fa fa-plus"></i> Add Photos (Maks : 5)</button>
<button onClick="getSlide()" class="btn btn-primary"><i class="fa fa-check"></i> Save</button>
</center>
and this my PHP crud.php
<?php
include "../element/connection.php";
switch ($_REQUEST['type'])
{
case "Foto_Barang":
{
$foto_id = $_REQUEST['ft'];
$urut = $_REQUEST['ur'];
$path = '../images/barang/';
$url = $path.$foto_id."_".$_FILES["file"]["name"];
if($_FILES['file']['size'] < 500000) // 500 kb
{
move_uploaded_file($_FILES["file"]["tmp_name"],$url);
}
else {
function compress_image($source_url, $destination_url, $quality)
{
$info = getimagesize($source_url);
if ($info['mime'] == 'image/jpeg')
$image = imagecreatefromjpeg($source_url);
elseif ($info['mime'] == 'image/gif')
$image = imagecreatefromgif($source_url);
elseif ($info['mime'] == 'image/png')
$image = imagecreatefrompng($source_url);
imagejpeg($image, $destination_url, $quality);
return $destination_url;
}
compress_image($_FILES["file"]["tmp_name"], $url, 20);
}
$sql ="INSERT INTO foto_barang
(foto_id,foto,urut) VALUES ('".$foto_id."','".$foto_id."_".$_FILES["file"]["name"]."','".$urut."')";
if( mysqli_query($con,$sql) ){
echo "OK";
}else{
echo "NOK";
}
break;
}
}
?>
You needs to create correct JSON response instead "echo 'ok';" or "echo 'nook';"
echo json_encode('ok/nook');
And also you need set headers to 'application/json':
headers('Content-Type: application/json');
This is wrong,
dataSlide = JSON.parse(response);
In php, you are echoing OK or NOK, you cannot use parse on that.
Also in php
this will not work
return $destination_url;
Instead,
echo json_encode($destination_url);
I just want to ask if how to merge this two array from all id value and data-rate value on my list order? there is too many ul li, so i need to get them all and store it into array.
this is my code in javascript:
var h = [];
$("ul.reorder-photos-list li").each(function() { h.push($(this).attr('id').substr(9)); });
var x = [];
$("ul.reorder-photos-list li").each(function() { x.push($(this).attr('data-rate').substr(9)); });
$.ajax({
type: "POST",
url: "order_update.php",
data: {
ids: " " + h + "",
rate: " " + x + ""
},
success: function(html)
{
window.location.reload();
/*$("#reorder-helper").html( "Reorder Completed - Image reorder have been successfully completed. Please reload the page for testing the reorder." ).removeClass('light_box').addClass('notice notice_success');
$('.reorder_link').html('reorder photos');
$('.reorder_link').attr("id","");*/
}
});
and this is my html code:
<li id="image_li_<?php echo $row['id']; ?>" class="ui-sortable-handle">
<input id="rate" type="text" value="<?= $row['rate']?>" data-rate="<?php echo $row['rate']; ?>" >
and then in my order_update.php this is my code.
$idArray = explode(",",$_POST['ids']);
$rateArray = explode(",",$_POST['rate']);
$ids = array();
foreach ($idArray as $id) {
$ids[] = $id;
}
$rates = array();
foreach ($rateArray as $rate) {
$rates[] = $rate;
}
$n = 0;
$orderArray = array();
while( $n <= count($idArray) )
{
$orderArray[] = array("id" => $ids[$n], "data" => $rates[$n]);
$n++;
}
and this is my insert query from orderArray
function updateOrder($orderArray){
$count = 1;
foreach ($orderArray as $array){
$update = mysqli_query($this->connect,"UPDATE `test` SET `order` = $count, `rate`=$array[rate] WHERE id = $array[id]");
$count ++;
}
return true;
}
hope someones helps me. :)thanks in advance!
When setting up your data, you don't need to have multiple loops. You can loop through the data once:
var dataArray = [];
$("ul.reorder-photos-list li").each(function() {
var el = $(this),
input = el.children(':input'); // This gets the input decendent of the li
// When adding one item at a time to an array, array[array.length] = item is better
dataArray[dataArray.length] = {
id: el.attr('id').substr(9),
rate: input.val(),
};
});
$.ajax({
type: "POST",
url: "order_update.php",
data: { items: dataArray }, // items gives the PHP something to use as a key in the POST data
success: function(html) {...}
});
Your PHP will look like this:
// The data passed from the Ajax call is already an array
$itemsArray = $_POST['items'];
// Your function to process the array
function updateOrder($orderArray) {
foreach ($orderArray as $index => $array) {
// $index will already have a count, you need to +1 because it's 0-based
mysqli_query($this->connect, "UPDATE `test` SET `order` = " . ($index + 1) . ", `rate`=" . $array['rate'] . " WHERE id = " . $array['id']);
}
return true;
}
var rates;
$("ul.reorder-photos-list li").each(function() {
rates.id.push($(this).attr('id').substr(9));
rates.rate.push($(this).attr('data-rate').substr(9));
});
This will create your JSON object of h/x pairs.
$.ajax({
type: "POST"
, url: "order_update.php"
, data: { JSON.stringify(rates); }
, success: function(html) {
window.location.reload();
/* $("#reorder-helper").html(
* "Reorder Completed - Image reorder have been successfully completed.
* Please reload the page for testing the reorder."
* ).removeClass('light_box').addClass('notice notice_success');
* $('.reorder_link').html('reorder photos');
* $('.reorder_link').attr("id","");
*/
}
});
This should fix your call to send the correct data.
Your PHP side is going to want to have something similar to this:
if(isset($_POST['rates'])) {
$ratesString = $_POST['rates'];
$rates = json_decode($ratesString);
}
// Do other things with $hx`
Your insert query is off, too. You need to declare each value as a variable or your compiler is going to hate your PHP, too. You also have some unnecessary quotes in your query.
function updateOrder($orderArray){
$count = 1;
foreach ($orderArray as $array){
$rate = $array['rate'];
$id = $array['id'];
mysqli_query($this->connect,"UPDATE test SET order = $count, rate = '$rate' WHERE id = '$id'");
$count ++;
}
return true;
}
For your HTML, I think this is what you were going for, but not sure since it's not really explained all that well...Feel free to comment on your intentions.
<ul>
<?php foreach($orderArray as $array) : ?>
<li id="image_li_<?php echo $array['id']; ?>" class="ui-sortable-handle">
<input id="rate" type="text" value="<?php echo $array['rate']?>" data-rate="<?php echo $array['rate']; ?>" ></li>
<?php endforeach; ?>
</ul>
Hope this helps.
-C§
I got the code now. thanks for your help guys!
var h = [];
$("ul.reorder-photos-list li").each(function() { h.push($(this).attr('id').substr(9)); });
var x = [];
$("input").each(function() { x.push($(this).val()); });
$.ajax({
type: "POST",
url: "order_update.php",
data: {ids: " " + h + "",rate: " " + x + ""},
/*data: { items: dataArray },*/
success: function(html)
{
...
}
});
In Php side:
$idArray = explode(",",$_POST['ids']);
$rateArray = explode(",",$_POST['rate']);
$ids = array();
foreach ($idArray as $id) {
$ids[] = $id;
}
$rates = array();
foreach ($rateArray as $rate) {
$rates[] = $rate;
}
$n = 0;
$orderArray = array();
while( $n <= count($idArray) )
{
$orderArray[] = array("id" => $ids[$n] , "rate" => $rates[$n]);
$n++;
}
$db->updateOrder($orderArray);
function updateOrder($orderArray){
$count = 1;
foreach ($orderArray as $array){
mysqli_query($this->connect, "UPDATE `test` SET `morder` = " . $count . ", `mtoursrate`=" . $array['rate'] . " WHERE id = " . $array['id']);
$count ++;
}
return true;
}
I have a PHP program that takes in a image name and loads the image and displays the name and the image on the page.
The variable in javascrip is written as
var latest_image_name = '<?=$post_img_name?>';
The PHP code is
<?php
foreach($files_assoc_array_keys as $file_name){
if($file_name==$post_img_name){
?>
<label class="lbl_image_name active"><?=$file_name?></label>
<?php
}else{
?>
<label class="lbl_image_name"><?=$file_name?></label>
<?php
}
}
?>
the html output, is being rendered as
<div id="image_list_wrapper">
<label class="lbl_image_name"><?=$file_name?></label>
</div>
And as you can see it seems that PHP has not replaced the tag with the posted image name.
The code works on the original server that it was developed on, it does not work when i migrated it to another server, i have tried two other servers both Centos 6.4 with apache and PHP installed. I am not sure what the setup was for the original server that it as does work on.
the full code is seen below
<?php
header('Refresh: 5; URL=display.php');
print_r($_POST['post_img_name']);
$target_directory = "uploaded_images";
if(!file_exists($target_directory)){
mkdir($target_directory);
}
if(isset($_POST['del_image'])) {
$del_image_name = $_POST['del_img_name'];
if(file_exists($target_directory."/".$del_image_name.".jpg")){
unlink($target_directory."/".$del_image_name.".jpg");
}
if(is_dir_empty($target_directory)){
die("Last image delete. No images exist now.");
}
$post_img_name = basename(get_latest_file_name($target_directory), '.jpg');
}else if(isset($_POST['post_img_name'])){
$post_img_name=$_POST['post_img_name'];
$post_img_temp_name = $_FILES['post_img_file']['tmp_name'];
}else{
$post_img_name = basename(get_latest_file_name($target_directory), '.jpg');
}
$files_array = new DirectoryIterator($target_directory);
$total_number_of_files = iterator_count($files_array) - 2;
$files_assoc_array = array();
$already_exists = "false";
if($total_number_of_files != 0){
foreach ($files_array as $file_info){
$info = pathinfo( $file_info->getFilename() );
$filename = $info['filename'];
if ($filename==$post_img_name) {
$already_exists = "true";
}
}
}
if(!isset($_POST['del_image']) && isset($_POST['post_img_name'])){
$target_file = "$target_directory"."/".$post_img_name.".jpg";
$source_file = $post_img_temp_name;
if($already_exists == "true"){
unlink($target_file);
}
move_uploaded_file($source_file, $target_file);
}
foreach ($files_array as $file_info){
$info = pathinfo( $file_info->getFilename() );
$filename = $info['filename'];
if(!$file_info->isDot()){
$files_assoc_array[$filename] = $target_directory."/".$file_info->getFilename();
}
}
$files_assoc_array_keys = array_keys($files_assoc_array);
function get_latest_file_name($target_directory){
$files_array = new DirectoryIterator($target_directory);
$total_number_of_files = iterator_count($files_array) - 2;
$timestamps_array = array();
if($total_number_of_files!=0){
foreach($files_array as $file){
if(!$file->isDot()){
$timestamps_array[filemtime($target_directory."/".$file)] = $file->getFilename();
}
}
}
$max_timestamp = max(array_keys($timestamps_array));
return $timestamps_array[$max_timestamp];
}
function is_dir_empty($dir) {
if (!is_readable($dir))
return NULL;
$handle = opendir($dir);
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
return FALSE;
}
}
return TRUE;
}
?><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<link rel="stylesheet" href="css/style.css"/>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
var files_array_text = '<?php echo implode(", ", $files_assoc_array)?>';
var files_array_keys_text = '<?php echo implode(", ", $files_assoc_array_keys)?>';
var files_array = files_array_text.split(", ");
var files_array_keys = files_array_keys_text.split(", ");
var files_assoc_array = createAssociativeArray(files_array_keys, files_array);
var latest_image_name = '<?=$post_img_name?>';
display_image(latest_image_name);
$('.lbl_image_name').click(function(){
$('#img_loading').show();
$('#img_display').hide();
var image_name = $(this).text();
$('.active').removeClass('active');
$(this).addClass('active');
display_image(image_name);
});
function createAssociativeArray(arr1, arr2) {
var arr = {};
for(var i = 0, ii = arr1.length; i<ii; i++) {
arr[arr1[i]] = arr2[i];
}
return arr;
}
function display_image(image_name){
var image_path = files_assoc_array[image_name];
$('#img_display').attr('src', image_path);
$('#img_display').load(image_path, function(){
$('#img_loading').hide();
$('#img_display').show();
})
}
});
</script>
</head>
<body>
<div id="container">
<div id="image_list_wrapper">
<?php
foreach($files_assoc_array_keys as $file_name){
if($file_name==$post_img_name){
?>
<label class="lbl_image_name active"><?=$file_name?></label>
<?php
}else{
?>
<label class="lbl_image_name"><?=$file_name?></label>
<?php
}
}
?>
</div>
<div class="separator"></div>
<div id="image_display_wrapper">
<div id="img_loading_wrapper">
<img src="images/loading.gif" id="img_loading"/>
</div>
<img src="" id="img_display"/>
</div>
<div style="clear: both">
</div>
</div>
Go Back
</body>
</html>
As arbitter has pointed out my server did not support <?= ... ?> it worked after i changed to <?php print $variable_name ?>