What I'm trying to do, is to simply display 5 posts returned from WordPress.
What jQuery does is that it displays me this 5 posts, 7 times.
Inside my_response.posts looks like:
Maybe my function is wrong, or I should remember about something, when doing ajax request to WordPress.
Any idea why this happens?
jQuery('span.main-nav-text').click(function(ev) {
ev.preventDefault();
//var slug = '';
//var trimmed = jQuery.trim(jQuery(this).parent().children()[0].innerHTML);
//slug = trimmed.replace(/[^a-z0-9-]/gi, '-').
// replace(/-+/g, '-').
// replace(/^-|-$/g, '');
// Information of our Request
var data = {
type:"POST",
'action': 'fyc_qet_menu_option',
'post_type': 'blog',
'qty': -1
};
jQuery.post( callajax.ajaxurl,data).done(
function (response){
var cipka=[];
jQuery('div.blog-entry').empty();
console.log(response);
var my_response =jQuery.parseJSON(response);
console.log(my_response.posts);
for(var i=0;i<my_response.posts.length;i++)
{
jQuery('div.blog-entry').html(my_response.posts[i]["post_date"]);
jQuery('div.blog-entry').html(my_response.posts[i]["post_title"]);
jQuery('div.blog-entry').html(my_response.posts[i]["post_content"]);
}
// jQuery.each(my_response.posts,function(index,element){
//// console.log(element["post_title"]);
// cipka.push("<a href="+element["guid"]+">");
// cipka.push(element["post_title"]+"<br />");
// cipka.push(element["post_content"].substring(0,220)+"...<br />");
// cipka.push("</a>");
// });
}
);
});
Here ho i have change the index.php template
<?php get_template_part('inc/content'); ?>
<?php endwhile; else : ?>
<div class="margint30"><h4><?php echo __('Not Post Found!','2035Themes-fm') ?></h4></div>
<?php endif; ?>
<?php Theme2035_pagination(); ?>
</div>
and here how i have changed jQuery function:
jQuery('span.main-nav-text').click(function(ev) {
ev.preventDefault();
//var slug = '';
//var trimmed = jQuery.trim(jQuery(this).parent().children()[0].innerHTML);
//slug = trimmed.replace(/[^a-z0-9-]/gi, '-').
// replace(/-+/g, '-').
// replace(/^-|-$/g, '');
// Information of our Request
var data = {
type:"POST",
'action': 'fyc_qet_menu_option',
'post_type': 'blog',
'qty': -1
};
jQuery.post( callajax.ajaxurl,data).done(
function (response){
var cipka=[];
jQuery('div.dynamic-blog-posts').empty();
console.log(response);
var my_response =jQuery.parseJSON(response);
console.log(my_response.posts);
for(var i=0;i<my_response.posts.length;i++)
{
jQuery('div.dynamic-blog-posts').html(my_response.posts[i]["post_date"]);
jQuery('div.dynamic-blog-posts').html(my_response.posts[i]["post_title"]);
jQuery('div.dynamic-blog-posts').html(my_response.posts[i]["post_content"]);
}
// jQuery.each(my_response.posts,function(index,element){
//// console.log(element["post_title"]);
// cipka.push("<a href="+element["guid"]+">");
// cipka.push(element["post_title"]+"<br />");
// cipka.push(element["post_content"].substring(0,220)+"...<br />");
// cipka.push("</a>");
// });
}
);
});
Related
I am trying to use Ajax that will keep
the inputs that the user has entered but for some reason, it isn't working.
In case of an error, my controller redirects the view with the data of errors,
however, after the page is uploading the form is empty.
I am using the MVC model of Codeigniter.
$("#save").click(function () {
var tnum1 = $("#tnum1").val();
var tnum2 = $("#tnum2").val();
var tnum3 = $("#tnum3").val();
var loc = $("#loc").val();
var dine = $("#dine").val();
var date = $("#date").val();
var time = $("#time").val();
var phone = $("#phone").val();
var fullname = $("#fullname").val();
$.ajax({
type: 'POST',
url: "<?php echo site_url(); ?>" + "/hosting/create",
data: {tnum1:tnum1, tnum2:tnum2, tnum3:tnum3, loc:loc, dine:dine,
date:date, time:time, phone:phone, fullname: fullname},
error: function () {
alert( "Load was performed.");
},
success: function (data) {
if (data === "") {
window.location.href = "<?php echo site_url('hosting/tableMap'); ?>";
}
else {
$("#error").html(data);
}
}
});
});
Controller
public function create() {
$newDate = date("Y-m-d",strtotime($this->input->post('re_date')));
$newTime = date("H:i", strtotime($this->input->post('re_time')));
$data = array(
'num' => $this->input->post('num'),
'location' => $this->input->post('location'),
'diners' => $this->input->post('diners'),
're_date' => $newDate,
're_time' => $newTime,
'phonenumber' => $this->input->post('phonenumber'),
);
$dataclient = array(
'fullname' => $this->input->post('fullname'),
'phonenumber' => $this->input->post('phonenumber'),
);
$error = $this->validation($data,$dataclient);
if ($error) {
$data['error'] = $this->session->set_flashdata('error','<b><u>Failed! </u></b>'.$error.'');
redirect(base_url("/hosting/tableMap"));
} else {
$this->Hosting_model->form_insert($data, $dataclient);
}
}
If you redirect the controller then it will not retain the previous values. Instead save the error in a variable and return it to ajax function.
That is the whole point of ajax - to not redirect or reload a page ie do the task asynchronously.
remove this line-
redirect(base_url("/hosting/tableMap")); // redirecting on error
then in your controller
if ($error) {
// data['error'] = $this->session->set_flashdata('error','<b><u>Failed! </u></b>'.$error.''); // remove this as page will not reload, flashdata wouldn't work
// redirect(base_url("/hosting/tableMap"));
$ajax_data['error'] = 1; // if error exists then value
$ajax_data['validation_error'] = $error;
} else {
$this->Hosting_model->form_insert($data, $dataclient);
$ajax_data['error'] = 0; // if error doesn't exist then value
}
return json_encode($ajax_data); // or echo json_encode($ajax_data);
Now, to prevent default action of form submission that is to redirect page use
$("#save").click(function (e) {
e.preventDefault();
// rest of your code
then in your ajax success:
if (data.error == 0) { // no error
window.location.href = "<?php echo site_url('hosting/tableMap'); ?>";
}
else { // error
$("#error").html(data); // do whatever you want to do with error
// errors can be retrieved from "data.validation_error" -- it will be an array probably sp you'll have to loop through each element
}
This is my php file:
add_action( 'wp_ajax_mon_action', 'mon_action' );
add_action( 'wp_ajax_nopriv_mon_action', 'mon_action' );
function mon_action() {
if (isset($_POST["form_data"])) {
$field1=$_POST["form_data"];
}else{
$field1='heye';
}
var_dump($_POST);
die();
}
And this is js file:
function sayHelloWorld() {
window.alert('hey');
var div = document.getElementById('alt_textarea');
var div_tmp = document.createElement('div');
div_tmp.innerHTML = div.innerHTML;
var images = Array.prototype.slice.call(div_tmp.getElementsByTagName('img'));
var form_data = new FormData();
for (var i = 0; i < images.length; i++) {
var altImage = document.createTextNode("articleImage_" + i);
images[i].parentNode.insertBefore(altImage,images[i]);
images[i].parentNode.removeChild(images[i]);
form_data.append('eyecatch[]',images[i].src);
};
form_data.append('body',div_tmp.innerHTML);
jQuery.ajax({
url: 'admin-ajax.php',//I wrote absolute path here.
type:'POST',
data: {
'action': "mon_action",
'form_data': form_data
},
timeout:10000
}).done(function(data) {
window.alert(data);
}).fail(function(XMLHttpRequest, textStatus, errorThrown) {
window.alert("error");
});
}
But var_dump($_POST) did not work.
My window.alert stops only with 'hey'.
When I change to "formdata: 'some strings'" in data in js file, I can use var_dump($_POST).
So my question is why I cannot use $_POST when I use these files.
Please tell me.
I have following code to execute a query on the Database. it returns a list of objects, one for each row result from the query:
function getcontent()
{
var data = {
"id": "<?php echo $stournid; ?>"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php",
data: data,
success: function(response) {
//**************************** HERE!!!!
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
return false;
}
The response.php file contains this:
<?php
$id = "";
if (is_ajax()) {
if (isset($_POST["id"]) && !empty($_POST["id"])) { //Checks if action value exists
$id = $_POST["id"];
querydata($id);
}
}
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function querydata($id){
require_once('dbconfig.php');
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($mysqli->connect_error) {
die('Errore di connessione (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$myArray = array();
if ($games = $mysqli->query("my query is here.. pretty long but working correctly.")){
while($row = $games->fetch_array(MYSQL_ASSOC)) {
$myArray[] = $row;
}
echo json_encode($myArray);
}
}
?>
here is the returned data:
[{"id":"1435","location":"Merano","date":"2017-01-26","eventname":"Collaudo","machines":"|6|","id_tournament":"2","allowedcat":"|A||B||C||D|","category":"test 1","chartsize":"8","exclusive":"0","subscriptionsactive":"0","maxsubscriptions":"512","autoplay":"3","machinespergame":"1","id_subtournament":"14","id_gamer1":"57","id_gamer2":"55","called":"2","callreadytime":"13:08:07","starttime":"22:12:19","endtime":"22:20:03","id_winner":"57","id_loser":"55","playsequence":"00001","tabsequence":"A00010001","dest_winner":"B00010001-1","dest_loser":"C00010001-1","connectionname":"","p1name":"Calamante Lorenzo","p2name":"Badiali Maurizio"},
{"id":"1436","location":"Merano","date":"2017-01-26","eventname":"Collaudo","machines":"|4|","id_tournament":"2","allowedcat":"|A||B||C||D|","category":"test 1","chartsize":"8","exclusive":"0","subscriptionsactive":"0","maxsubscriptions":"512","autoplay":"3","machinespergame":"1","id_subtournament":"14","id_gamer1":null,"id_gamer2":null,"called":"0","callreadytime":"00:00:00","starttime":"00:00:00","endtime":"00:00:00","id_winner":"0","id_loser":"0","playsequence":"00015","tabsequence":"W00010001","dest_winner":"","dest_loser":"1","connectionname":"","p1name":null,"p2name":null}]
What I would like to do, is in the Javascript, go through all the returned lines one by one and updated some div's accordingly. I am having difficulties on how to iterate the returned lines.
Any help appreciated.
Thanks
success: function(response) {
// redponse is an array of objects (so lets loop through it using forEach)
response.forEach(function(row) {
// row is a row (object) from the array
var id = row.id;
var location = row.location;
var date = row.date;
// ... you get the idea
// do something with the current row (maybe create a div or table row ...)
});
},
Note: Array.prototype.forEach is like a loop but better. Check the docs.
Don't want to use forEach?
If you don't want to use forEach, you can use an old for like this:
success: function(response) {
// using for is not very pretty, hein?
for(var i = 0; i < response.length; i++) {
// response[i] is the i-th row of the array
var id = response[i].id;
var location = response[i].location;
var date = response[i].date;
// ... you get the idea
// do something with the current row (maybe create a div or table row ...)
});
},
I'm trying to get the proper information out of this ajax function (thumbnail image, the owner of the image). I dont think it knows what data.images[i].imgurl and data.images[i].username is.
ajax.php
require_once 'instagram.class.php';
// Initialize class for public requests
$instagram = new Instagram('123456');
// Receive AJAX request and create call object
$tag = $_GET['tag'];
$maxID = $_GET['max_id'];
$clientID = $instagram->getApiKey();
$call = new stdClass;
$call->pagination->next_max_id = $maxID;
$call->pagination->next_url = "https://api.instagram.com/v1/tags/{$tag}/media/recent?client_id={$clientID}&max_tag_id={$maxID}";
// Receive new data
$media = $instagram->getTagMedia($tag,$auth=false,array('max_tag_id'=>$maxID));
// Collect everything for json output
$images = array();
foreach ($media->data as $data) {
$images[] = array(
"imgurl"=>$data->images->thumbnail->url,
"username"=>$data->user->username;
);
}
echo json_encode(array(
'next_id' => $media->pagination->next_max_id,
'images' => $images,
));
search.php
<script>
$(document).ready(function() {
$('#more').click(function() {
var tag = $(this).data('tag'),
maxid = $(this).data('maxid'),
$.ajax({
type: 'GET',
url: 'ajax.php',
data: {
tag: tag,
max_id: maxid
},
dataType: 'json',
cache: false,
success: function(data) {
// Output data
$.each(data.images, function(i, src) {
$('#photos').append('<div id=box><div class=mainimg><img src="'+ data.images[i].imgurl +'"></div><div class=\"pfooter\">'+ data.images[i].username +'</div></div>');
});
// Store new maxid
$('#more').data('maxid', data.next_id);
}
});
});
});
..
In your search.php file you have to close the variable statement with a semicolon.
Change this line:
var tag = $(this).data('tag'),
maxid = $(this).data('maxid'),
to this:
var tag = $(this).data('tag'),
maxid = $(this).data('maxid'); // <-- added semicolon
I'm trying to send data from an html data attribute on a span element and receive it with Ajax and then process it with php and mysql and return the new value to my data attribute in html, but I'm getting a error that says "$.parseJSON unexpected character", can someone please look over my code to see if I'm processing the data correctly as I'm new to working with JSON.
HTML / PHP
<span data-object=
'{"art_id":"<?php echo $row['art_id'];?>",
"art_featured":"<?php echo $row['art_featured'];?>"}'
class="icon-small star-color"></span>
<!-- art_id and art_featured are both int and art_featured will be either 1 or 0 -->
jQuery / Ajax
$("span[class*='star']").on('click', function () {
var data = $.parseJSON($(this).data('object'));
var $this = $(this);
$.ajax({
type: "POST",
url : "ajax-feature.php",
data: {art_id: data.art_id,art_featured: data.art_featured}
}).done(function(result) {
data.art_featured = result;
$this.data('object', JSON.stringify( data ));
});
});
PHP / mySQL
if($_POST['art_featured']==1) {
$sql_articles = "UPDATE `app_articles` SET `art_featured` = 0 WHERE `art_id` =".$_POST['art_id'];
$result = array('art_id' => $_POST['art_id'], 'art_featured' => 0);
echo json_encode($result);
}
else if($_POST['art_featured']==0){
$sql_articles = "UPDATE `app_articles` SET `art_featured` = 1 WHERE `art_id` =".$_POST['art_id'];
$result = array('art_id' => $_POST['art_id'], 'art_featured' => 1);
echo json_encode($result);
}
if(query($sql_articles)) {
}
else {
}
You don't need to use $.parseJSON, jQuery does that for you.
$("span[class*='star']").on('click', function () {
var data = $(this).data('object');
var $this = $(this);
$.ajax({
type: "POST",
url : "ajax-feature.php",
data: {art_id: data.art_id,art_featured: data.art_featured}
}).done(function(result) {
data.art_featured = result;
$this.data('object', data);
});
});
You also don't need to stringify it later.