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?
Related
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;
Hopefully an easy question here. I actually used an example I found on SO but can't figure out why its not working. No errors in console or anything.
I have an ajax Post function I am using to pass data to a php script.
Its passing the data correct, but the response each time is coming back as an error alert. I can confirm that server side is getting the data and processing it correctly, just can't figure out why its never returning a success response.
Here is the Ajax:
$(function () {
$('#pseudoForm').on('click', '#submit', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "psu_output.php",
data: $('#pseudoForm').serialize(),
datatype: 'json',
success: function (response) {
if(response.type == 'success') {
$('#messages').addClass('alert alert-success').text(response.message);
} else {
$('#messages').addClass('alert alert-danger').text(response.message);
}
}
});
return false;
});
});
</script>
And in my php script I used this:
<?php
$success = true;
if($success == true) {
$output = json_encode(array('type'=>'success', 'message' => 'YAY'));
} else {
$output = json_encode(array('type'=>'error', 'message' => 'WHOOPS'));
}
die($output);
?>
The problem is that datatype: 'json' should be dataType: 'json'. Javascript is case-sensitive.
The error is because you received the returned data as json but the content type is a simple string (text/html) so you need to JSON.parse() the received data first like so:
$(function () {
$('#pseudoForm').on('click', '#submit', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "psu_output.php",
data: $('#pseudoForm').serialize(),
datatype: 'json',
success: function (response) {
response = JSON.parse(response);
if(response.type == 'success') {
$('#messages').addClass('alert alert-success').text(response.message);
} else {
$('#messages').addClass('alert alert-danger').text(response.message);
}
}
});
return false;
});
});
The second option is to send json headers from php itself thus removing the need of parsing JSON in javascript. You can do that by using the following line of code BEFORE ECHOING OR PRINTING ANYTHING ELSE FROM THE PHP SCRIPT:
header('Content-Type: application/json');
and then
echo $output;
If you are working with JSON responses, you need to set the header so your browser and your JavaScript could interpret it correctly:
<?php
$success = true;
if ($success == true) {
$output = json_encode(array(
'type' => 'success',
'message' => 'YAY'
));
} else {
$output = json_encode(array(
'type' => 'error',
'message' => 'WHOOPS'
));
}
header('Content-Type: application/json');
echo $output;
I would like to achieve something like these below code. just that the code is making a request from the database, i want to send request to the database
$.post( "/trobay/categories/default/lists?parent_id="+$(this).val(), function( data ) {
how to send request adding attribute name and attribute value to be save in DB
below is my code i have already
<?php
$script = <<< JS
$(document).ready(function(){
//setup before functions
var typingTimer;
var doneTypingInterval = 3000;
var \$TitleInput = $('#product-product_title');
//on keyup, start the countdown
\$TitleInput.on('keyup input change paste',function(){
clearTimeout(typingTimer);
if (\$TitleInput.val()) {
typingTimer = setTimeout(doneTyping, doneTypingInterval);
}
});
//user is "finished typing," do something
function doneTyping () {
data = \$TitleInput.val();
$.ajax({
url: '/trobay/draft/create',
type: 'POST',
data: data,
success: function (data) {
alert(data)
},
error: function(jqXHR, errMsg) {
// handle error
alert(errMsg);
}
});
}
});
JS;
$this->registerJs($script);
?>
in my controller i have this
public function actionCreate()
{
$model = new Draft();
if ($model->load(Yii::$app->request->post())) {
$model->created_at = \time();
if($model->save()){
return draftId;
}else{
return '0';
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
and in my view i have this
<?php $form = ActiveForm::begin(['id'=>$model->formName(),
'enableClientValidation'=> true,
'fieldConfig' => ['template' => '{label}{input}{hint}']]); ?>
<div class="row">
<div class="col-md-12">
<?= $form->field($model, 'product_title')->textInput([
'class'=>'title-input',
'placeholder' => 'Give us a title for your items(include size,brand,color,material. e.t.c)',
])->label(false) ?>
</div>
<div class="col-md-12 text-muted">
E.g Men's blue addidas glide running shoes size 11
</div>
</div>
<?= $form->field($model, 'user_id')->textInput() ?>
<?= $form->field($model, 'product_title')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'product_name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'product_description')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'category_id')->textInput() ?>
Now my question is I just want to grab the value of each field input and send it to server side for save in the DB without having to submit the whole form
The about JS code works enough to get the value but how do i send this to the server for save up
//user is "finished typing," do something
function doneTyping () {
data = \$TitleInput.val();
$.ajax({
url: '/trobay/draft/create',
type: 'POST',
data: {title: data}
success: function (data) {
alert(data)
},
error: function(jqXHR, errMsg) {
// handle error
alert(errMsg);
}
});
});
If you need to send more key value just add those as comma seperated value like
data: {title: data, attr:"value"}
and so on...and you can receive this value as post parameter in your controller.
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.
I am working on a chat system which refreshes automatically using AJAX. First I was using the jQuery $.post function, but since i wanted to return JSON data from my PHP script, i want to use the $.ajax function. My script worked well using the $.post function, but i can not return JSON. This is the relevant code:
Javascript:
$.ajax({
url: "pages/loadmessage.php",
type: "POST",
data: {"c": getUrlParameter("c"), "t": messagetime},
dataType: "json",
success: function(pData){
console.log(pData);
},
error: function(xhr, status, error) {
alert(error + status);
}
});
PHP Code:
<?php
require_once("../init.php");
header('Content-Type: application/json');
if (Input::exists() && Input::get("c") && Input::get("t")) {
$chat = new Chat($user->data()->ID, Input::get("c"));
$messages = $chat->getNewMessages(Input::get("t"), $user->data()->ID);
if ($messages) {
$result = array(
'topic' => $chat->getTopic(),
'messages' => array()
);
foreach($messages as $m) {
array_push($result['messages'], array('source' => 'mine', 'Text' => $m->Text));
}
echo json_encode("string!!!");
}
} else {
echo json_encode("string" . Input::get("c") . Input::get("t") . Input::exists());
}
?>
I already tried to set the contentType of the AJAX call to "application/json" and convert the data to JSON using JSON.stringify, but then no input data gets to the PHP script. The code works if just one parameter (data: {"c": getUrlParameter("c")}) is sent to the PHP script...
I already searched StackOverflow, but i could not find a solution...
Thanks
JSON example:
Index.html
<script type="text/javascript">
$.ajax({
url: "out.php",
type: "POST",
data: {"param1": "test 1", "param2": "test2"},
dataType: "json",
success: function(data){
alert("param1:"+data.param1+" | param2:"+data.param2);
},
error: function(xhr, status, error) {
alert(error + status);
}
});
</script>
out.php
<?php
if(isset($_POST["param1"])){ $param1 = $_POST["param1"];}
if(isset($_POST["param2"])){ $param2 = $_POST["param2"];}
$out = array("param1"=>$param1,"param2"=>$param2);
echo(json_encode($out));
?>