Back button doesn't recall AJAX content location in Chrome - javascript

I am dynamically loading talent content on this page with AJAX: www.icon.pha-group.com it uses pagination to go browse the content. My problem is that in Google Chrome doesnt remember the paginated page you were on. So if I'm on page 2 of content, click an item, then go back, it goes back to page 1. Is there some way I can modify this code to solve the problem? Here is the AJAX function:
function get_posts($params) {
$container = $('#container-async');
$content = $container.find('.content-ajax');
$status = $container.find('.status');
$status.text('Fetching talent...');
$.ajax({
//url: bobz.ajax_url,
url: "/wp-admin/admin-ajax.php",
data: {
action: 'do_filter_posts',
nonce: bobz.nonce,
params: $params
},
type: 'post',
dataType: 'json',
success: function(data, textStatus, XMLHttpRequest) {
if (data.status === 200) {
$content.html(data.content);
}
else if (data.status === 201) {
$content.html(data.message);
}
else {
$status.html(data.message);
}
//all done so call cycle script
script_cycle();
// window.location.hash = $this.closest('span').find('.current');
// console.log(window.location.hash);
//angular.bootstrap(document, ['lightbox']);
},
error: function(MLHttpRequest, textStatus, errorThrown) {
$status.html(textStatus);
/*console.log(MLHttpRequest);
console.log(textStatus);
console.log(errorThrown);*/
},
complete: function(data, textStatus) {
msg = textStatus;
if (textStatus === 'success') {
msg = data.responseJSON.found;
}
// $status.text('Posts found: ' + msg);
$status.text('');
/*console.log(data);
console.log(textStatus);*/
}
});
}
Code update, heres the pagination:
function vb_ajax_pager( $query = null, $paged = 1 ) {
if (!$query)
return;
$paginate = paginate_links([
'base' => '%_%',
'type' => 'array',
'total' => $query->max_num_pages,
'format' => '#page=%#%',
'current' => max( 1, $paged ),
'prev_text' => 'Prev',
'next_text' => 'Next'
]);
if ($query->max_num_pages > 1) : ?>
<ul class="pagination">
<?php foreach ( $paginate as $page ) :?>
<li><?php echo $page; ?></li>
<?php endforeach; ?>
</ul>
<?php endif;
}

You can store/fetch the information that you need in/from javascript local storage variable.
In this way you can remember the paginated page you were on.

That's because you don't change URL after clicking on an item.
$('.youritemclicked').click(function() {
location.hash($(this).attr('id'));
});
Or you can simply wrap your item in a anchor tag:
<a href="#item2">
<!-- Your item body -->
</a>
IMPORTANT
Make sure that you don't have set preventDefault() by clicking on this item
Then you can go back and forward in your browser because now you have history saved also for this items.
UPDATE
if ($query->max_num_pages > 1) : ?>
<ul class="pagination">
<?php foreach ( $paginate as $page ) :?>
<li><?php echo $page; ?></li>
<?php endforeach; ?>
</ul>
<?php endif;

Related

codeigniter ajax form validation with submit

i have this ajax form validation code igniter. my view is something like this
<?php
echo form_open('Provinces/create',array('id' => 'form-user'));
?>
<label for="PROVINCE" class="col-sm-2 control-label col-sm-offset-2">Province Name:</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="PROVINCE" name="PROVINCE" value = "<?= set_value("PROVINCE"); ?>">
</div>
<button class="btn btn-info fa fa-save" type="submit">&nbsp Save</button>
<a href = '<?php echo base_url().'Provinces/index'; ?>' class = 'btn btn-danger fa fa-times-circle'>&nbsp Cancel</a>
<?php
echo form_close();
?>
and i have this javascript
<script>
$('#form-user').submit(function(e){
e.preventDefault();
var me = $(this);
// perform ajax
$.ajax({
url: me.attr('action'),
type: 'post',
data: me.serialize(),
dataType: 'json',
success: function(response){
if (response.success == true) {
// if success we would show message
// and also remove the error class
$('#the-message').append('<div class="alert alert-success">' +
'<span class="glyphicon glyphicon-ok"></span>' +
' Data has been saved' +
'</div>');
$('.form-group').removeClass('has-error')
.removeClass('has-success');
$('.text-danger').remove();
// reset the form
me[0].reset();
url = "<?php echo site_url('Provinces/ajax_add')?>";
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
alert('success');
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}else{
$.each(response.messages, function(key, value) {
var element = $('#' + key);
element.closest('div.form-group')
.removeClass('has-error')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger')
.remove();
element.after(value)
});
}
}
});
});
</script>
i have found this code on google and just customized it. but the problem is, i am not that familiar with ajax, the part where the form validation fails, work perfectly fine, but when it is succes, even though it shows alert('success'); it doesnt add the value in the database. i need to finish this projects in a few weeks. please help.
here is where i get the validations,
public function create(){
$data = array('success' => false, 'messages' => array());
$this->form_validation->set_rules('PROVINCE','Province Name','trim|required|max_length[30]|callback_if_exist');
$this->form_validation->set_error_delimiters('<p class="text-danger"','</p>');
if($this->form_validation->run($this)){
$data['success'] = true;
}else{
foreach ($_POST as $key => $value) {
# code...
$data['messages'][$key] = form_error($key);
}
}
echo json_encode($data);
}
also here is my ajax_add
public function ajax_add()
{
$data = array(
'PROVINCE' => $this->input->post('PROVINCE'),
);
$insert = $this->Provinces_Model->save($data);
echo json_encode(array("status" => TRUE));
}
and here is my model,
public function save($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
i have solved it. just did put
$data = array(
'PROVINCE' => $this->input->post('PROVINCE'),
);
$insert = $this->Provinces_Model->save($data);
echo json_encode(array("status" => TRUE));
into my controller, which makes my controller
public function create(){
$data = array('success' => false, 'messages' => array());
$this->form_validation->set_rules('PROVINCE','Province Name','trim|required|max_length[30]|callback_if_exist');
$this->form_validation->set_error_delimiters('<p class="text-danger"','</p>');
if($this->form_validation->run($this)){
$data['success'] = true;
$data = array(
'PROVINCE' => $this->input->post('PROVINCE'),
);
$insert = $this->Provinces_Model->save($data);
echo json_encode(array("status" => TRUE));
}else{
foreach ($_POST as $key => $value) {
# code...
$data['messages'][$key] = form_error($key);
}
}
echo json_encode($data);
}
and my javascript
$('#form-user').submit(function(e){
e.preventDefault();
var me = $(this);
// perform ajax
$.ajax({
url: me.attr('action'),
type: 'post',
data: me.serialize(),
dataType: 'json',
success: function(response){
if (response.success == true) {
// if success we would show message
// and also remove the error class
$('#the-message').append('<div class="alert alert-success">' +
'<span class="glyphicon glyphicon-ok"></span>' +
' Data has been saved' +
'</div>');
$('.form-group').removeClass('has-error')
.removeClass('has-success');
$('.text-danger').remove();
// reset the form
me[0].reset();
$('.alert-success').delay(500).show(10, function() {
$(this).delay(3000).hide(10, function() {
$(this).remove();
});
})
}else{
$.each(response.messages, function(key, value) {
var element = $('#' + key);
element.closest('div.form-group')
.removeClass('has-error')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger')
.remove();
element.after(value)
});
}
}
});
});
You dont't need to use uppercase when accessing your controller
just use
url = "<?php echo site_url('provinces/ajax_add')?>";
Validation the request data before inserting
try
public function ajax_add()
{
$response = array(
'success' => false
) ;
$this->load->library('form_validation');
// add your validation
$this->form_validation->set_rules('PROVINCE', 'PROVINCE', 'required');
if ($this->form_validation->run() == FALSE)
{
$data = array(
'PROVINCE' => $this->input->post('PROVINCE')
);
$insert = $this->Provinces_Model->save($data);
if($insert){
$response['success'] = TRUE ;
$response['message'] = 'Record created successfully' ;
}
else{
$response['message'] = 'Unable to create record' ;
}
}
else
{
$response['message'] = 'Invalid data' ;
}
echo json_encode($response);
}
Then check for the 'message' index in your ajax response in the javascript code
This will give an idea of where there is problem, whether its from the
view or
controller or'
Model

Posting a comment in PHP with Ajax

I know there are a few of these questions posted on here already but i am having trouble finding a solution to my problem. I am very bad with anything javascript/ajax and i am having difficulties trying to get my ajax code to work.
I am building a simple commenting system on a video page for my website. I have built the commenting system with php but now i want to get more advance and post the data to my comments.php file via ajax. I want the comments to display dynamically without refreshing the page. I've read a few tutorials but for some reason whenever i try work with js i get really confused. I think it's the syntax :S. I'll post my code below and if anyone can tell me where i am going wrong it will be a massive help!
videos.php
// comment box
if($user->isLoggedIn()){
//login to comment
} else { ?>
<div id="user-comment" class="comment-post">
<form id="comment-form" method="post">
<textarea id="comment_body" name="comment"> </textarea>
<input id="submit-btn" type="submit" name="comment_post" value="Post Comment" >
// csrf-token generator
<input type="hidden" id="auth-token" value="<?php echo token::generate(); ?>"></input>
</form>
</div>
//post comments
<div id="comments_post" class="comments-box">
<?php
$get_comments = // query the db here
if(!$get_comments->results()){ ?>
//no comments...
<?php
} else {
foreach ($get_comments->results() as $comment) { ?>
<div class="comment-header">
<?php echo $comment->username . ' | ' . $comment->added;
if ($user == $comment->user OR $user->hasPermission('admin')) { ?>
<i class="fa fa-trash-o onl-link-icon text-right"></i>
<?php
}
?>
</div>
<div class="comment-body">
<p><?php echo $comment->comment; ?></p>
</div>
<?php
}
}
?>
</div>
ajax request
<script type="text/javascript">
$(document).ready(function(){
//Post Comment
$("#submit-btn").on('.submit','click',function(){
var body = $('#comment_body');
$.ajax({
url: 'comments.php',
type: 'post',
async: false,
data:{
'comment_body' : body
},
success:function(){
$('#comment-box').toggleClass("comment-hide");
}
});
});
});
</script>
comments.php
if($_POST['auth_token'] === session::get('access_token')){
if(isset($_POST['comment_body'])) {
$validate = new validate();
// Validate Data from $_POST
$validation = $validate->check($_POST, array(
'comment_body' => array(
'name' => '<b>Comments</b>',
'required' => true,
'str_min' => 1,
'str_max' => 400,
'comment_filter' => true,
'sql_safe' => true
),
));
if($validation ->passed()){
$comment = escape($_POST['comment']);
try {
$user->create('video_comments', array(
'comment' => $comment,
'user_id' => $user->id,
'video_id' => $video,
'username' => $user->username,
'added' => date('Y-m-d H:i:s')
));
} catch(Exception $e) {
die($e->getMessage());
}
redirect::to($page);
} else {
session::flash('comment_error', 'Comment Failed');
redirect::to($page);
die();
}
} else { redirect::to(404); }
} else { redirect::to(404); }
UPDATE #1
the console error is showing me this:
GET (localhost/WEBSITES/myvideosite/css/homepage.css) - Failed to load resource: the server responded with a status of 404 (Not Found)
it points to my jquery <script src="js/jquery-1.11.3.min.js"></script> file which is defiantly there?
Sucess!
After a long day of researching and trying out different things I have finally got it to work!!
<script type="text/javascript">
$(document).ready(function(){
$("#submit-btn").click(function(){
var body = $('#comment_body').val();
var token = $('#auth-token').val();
if(body== null)
{
window.alert('Please enter a comment.');
}
else
{
$.ajax({
type: 'POST',
url: 'comment.php',
async: false,
data:{
'auth_token' : token,
'comment_body' : body
},
success: function(result){
//alert(result);
$('.comment-post').toggleClass("comment-hide");
$('.comment-sucess-hide').toggleClass("comment-sucess");
$('#comments_post').load(document.URL + ' #comments_post');
}
});
}
return false;
});
$('.del-com').click(function(){
var comid = $(this).attr('id');
$.ajax({
url: 'comment.php',
type: 'POST',
async: false,
data:{
'rmv' : comid
},
success:function(){
$('#comments_post').load(document.URL + ' #comments_post');
}
});
});
});
</script>
If anyone has some better suggestions please feel free to share as i am a real novice with js and really want to improve. Thanks to all that shared comments.

Send message from php to ajax with 'echo json_encode' not working

I'm trying to send a message from php to ajax. I'm using echo json_encode to do it. When I do that, the website displays the arrays message. ({"foo":"content of foo"}). How can I get it to not display the message?
Also, the alerts from ajax don't get called.
Here's the code:
<?php
$myString = $_POST['data'];
if ($myString == "") {
echo json_encode(
array()
);
} else if ($myString == "foo" {
echo json_encode(
array(
'foo2' => 'this is the contents of foo'
)
);
} else if ($myString == "foo2") {
echo json_encode(
array(
'foo2' => 'this is the contents of foo2'
)
);
}
?>
<script>
var formData = new FormData($(this)[0]);
$.ajax({
url: $(this).attr("action"),
context: document.body,
data: formData,
type: "POST",
contentType: false,
processData: false,
success: function(response) {
if (response.length == 0) {
alert("empty");
} else if (response.foo) {
alert("foo");
} else if (respons.foo2) {
alert("foo2");
}
}
});
</script>
How can I get the array to not display on the website? And why are the ajax if statements not getting called?
You need to set the HTTP header at the top of the script so you can return son:
header('Content-type: application/json');
Your script is a little confusing. You can't return json AND html/javascript.
It's one or the other.

Get json data stored as text from mysql

First I have html - bootstrap tab:
<ul class="nav nav-tabs">
<li class="active">Opsti podaci</li>
<li><a id="mapa1" href="#mapa" data-toggle="tab">Mapa parcele</a></li>
<li>Dokumenti</li>
<li>Komentari</li>
</ul>
and below:
<div class="tab-pane" id="mapa">
<div id="myMap" style="height:500px;"></div>
</div>
In database I have this:
Now I write this jquery/ajax code to get json stored as text from mySql database:
$( document ).ready(function() {
$('a#mapa1').click(function (e) {
$.ajax({
url: "getMap.php",
type: "POST",
async: true,
data: { ajdi:ajdi}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
console.log(data);
BlitzMap.setMap( 'myMap', true, 'data' );
BlitzMap.init();
},
error: function(data) {
console.log(data);
}
});
});
but when I click on a#mapa1 notning happend... also when I manualy add this code to execude in console i get error: SyntaxError: Unexpected end of input
What can be a problem here? I dont see! Please help! Thanks!
UPDATE:
try {
$result = $db->prepare("SELECT json FROM map WHERE id_parcele=:ajdi AND user_id=:user_id");
$result->execute(array(':ajdi' => $_POST['ajdi'], ':user_id' => $user_id));
$result = $result->fetchAll();
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo $result;
}
this produce me just Array when I chenge echo $result to echo json_encode($result) again dont work... how to get just plain text ?
With print_r I get this code:
Array
(
[0] => Array
(
[json] => {"zoom":7,"tilt":0,"mapTypeId":"hybrid","center":{"lat":20.487486793750797,"lng":74.22363281640626},"overlays":[{"type":"polygon","title":"","content":"","fillColor":"#000000","fillOpacity":0.3,"strokeColor":"#000000","strokeOpacity":0.9,"strokeWeight":3,"paths":[[{"lat":"21.329035778926478","lng":"73.46008301171878"},{"lat":"21.40065516914794","lng":"78.30505371484378"},{"lat":"20.106233605369603","lng":"77.37121582421878"},{"lat":"20.14749530904506","lng":"72.65808105859378"}]]}]}
[0] => {"zoom":7,"tilt":0,"mapTypeId":"hybrid","center":{"lat":20.487486793750797,"lng":74.22363281640626},"overlays":[{"type":"polygon","title":"","content":"","fillColor":"#000000","fillOpacity":0.3,"strokeColor":"#000000","strokeOpacity":0.9,"strokeWeight":3,"paths":[[{"lat":"21.329035778926478","lng":"73.46008301171878"},{"lat":"21.40065516914794","lng":"78.30505371484378"},{"lat":"20.106233605369603","lng":"77.37121582421878"},{"lat":"20.14749530904506","lng":"72.65808105859378"}]]}]}
)
)
but I need to get just this:
{"zoom":13,"tilt":0,"mapTypeId":"hybrid","center":{"lat":45.38591280296377,"lng":19.93632316979983},"overlays":[{"type":"polygon","title":"Polje 1","content":"Vojvodina","fillColor":"#ffbf1a","fillOpacity":0.3,"strokeColor":"#000","strokeOpacity":0.8,"strokeWeight":3,"paths":[[{"lat":"45.37867863632308","lng":"19.948768615722656"},{"lat":"45.370719925928746","lng":"19.941558837890625"},{"lat":"45.36227764550136","lng":"19.92816925048828"},{"lat":"45.359262240003495","lng":"19.942245483398438"},{"lat":"45.35588479505299","lng":"19.955806732177734"},{"lat":"45.35974471568275","lng":"19.958553314208984"},{"lat":"45.36312193024184","lng":"19.959583282470703"},{"lat":"45.365534102931655","lng":"19.960613250732422"},{"lat":"45.36529289029106","lng":"19.96490478515625"},{"lat":"45.37084052080666","lng":"19.970226287841797"}]]}]}
How I can do that?

Wordpress: get terms by ajax

I'm new in wordpress, but i need to collect all photos in posts, and group by categories. My Js is
function get_photos(elem)
{
$.ajax({
cache: true,
type: "GET",
timeout: 20000,
url: 'wp-content/themes/wp_theme/photos.php',
success: function(msg)
{
$(elem).append(msg);
},
error: function(msg)
{
get_photos(elem);
return false;
}
});
}
And the photos.php is the :
<?php
require('../../../wp-load.php');
$tax_terms = get_terms('media_category', 'orderby=count&order=DESC&hide_empty=0');
foreach ( $tax_terms as $tax_term ) {
?>
<div class="news">
<img src="./wp-content/themes/wp_theme/img/plus.png" class="plus">
<div class="titleNews2"><?php echo $tax_term->name; ?></div>
</div>
<?php
$posts = get_posts(array(
"post_type" => "attachment",
"post_mime_type" => "image",
"taxonomy" => $tax_term->taxonomy,
"term" => $tax_term->slug,
"numberposts" => 100,
"posts_per_page" => 100));
?>
<div class="photoRace">
<?php
$ua = #getenv( HTTP_USER_AGENT );
$touchPadApple = stripos( strtolower( $ua ), "iphone" ) !== false || stripos( strtolower( $ua ), "ipad" ) !== false ? true : false;
foreach($posts as $post){
setup_postdata($post);
$img = get_post_meta($post->ID, "_wp_attachment_metadata", true);
$dir = explode("/", $img['file']);
$link = get_bloginfo('siteurl')."/wp-content/uploads/{$dir[0]}/{$dir[1]}/";
?>
<a <?php echo !$touchPadApple ? "rel=\"photos\" " : "target=_BLANK "; ?>href="<?php echo get_bloginfo('siteurl')."/wp-content/uploads/".$img['file'];?>">
<img src="<?php echo $link.$img['sizes']['thumbnail']['file'];?>" height="<?php echo $img['sizes']['thumbnail']['height']; ?>" width="<?php echo $img['sizes']['thumbnail']['width']; ?>">
</a>
<?php } ?>
</div>
<?php } ?>
Im working on mobile interface, and this script (not via ajax) works well on non-mobile static pages of theme. But when i using it via ajax, im getting only some photos, and if i call var_dump($tax_terms); the result is
object(WP_Error)#4418 (2) { ["errors"]=> array(1) {
["invalid_taxonomy"]=> array(1)
What should i include to use terms?
You should use wp_ajax in the first place, and then you can skip the first require.

Categories