I'm looking to make a like counter as like in facebook. I will load various posts from database with message id. i want to make like(here it is "pray") counter and it should do behind the page using jquery and ajax. I cant get specific message id(mid). here the code is
jQuery:
$(document).ready(function () {
$("div.pray").click( function()
{
var mid=$(this).val();
$.ajax(
{
type:"POST",
url:"increment.php",
data:'mid='+mid,
success:function ()
{
$("div.pray").text("Prayed");
}
});
});
PHP:
session_start();
if(isset($_SESSION['usrid']))
{
$usr = $_SESSION['usrid'];
include('dbcon.php');
$cot = "select * from posts where userid=$usr LIMIT 10";// order by eventDate DESC, eventHour DESC" LIMIT0,10";
$ex = mysql_query($cot,$con);
while($cont=mysql_fetch_array($ex))
{
$date = date_create($cont['date']);
$mid=$cont['mid'];
echo "<div id='posts'>";
echo $cont['message'];
echo $photo;
echo "<div class='pray'>";
echo "<input type='hidden' class='mid' value='$mid'>";
echo "<a href='#'>Pray</a></div>";
echo "Prayed(".$cont['prayers'].")    ";
echo date_format($date, 'd-m-Y H:i:s');
echo "<hr>";
echo "</div>";
}
}
else
{
echo "Login to see";
}
?>
i want to replace only the message which i clicked as pray and also it should load current number of prayed.
put your javascript AFTER your php script and check. If that fails, change your .click() handler to,
$(document).on('click', 'div.pray', function(){
var mid=$(this).children('.mid').val();
$.ajax(
{
type:"POST",
url:"increment.php",
data:'mid='+mid,
success:function ()
{
$("div.pray").text("Prayed");
}
});
//rest of your code
})
Notice, I've changed the first line from
var mid=$(this).val();
To
var mid=$(this).children('.mid').val();
As, $(this) will select the div.pray and not the input.mid element.
In the html code try something like this:
echo "<a href='increment.php?mid=$mid'>Pray</a></div>";
In javascript:
$(document).on('click', 'div.pray', function(e){
e.preventDefault();
var $target = $(e.target).closest('a');
$.ajax({
type:"POST",
url: $target.attr('href'),
success:function (data){
$target.closest("div.pray").html(data);
}
});
});
In the ajax response the html code should go into the div.pray
Related
I am trying to fetch events from an external php file onto the full calendar view. I had asked a similar question sometime back but I am still struggling with this thing.
CODE (JS):
<script>
$(document).ready(function() {
$('#ccategory').change(function(){
var id = $(this).val();
var user = $('#current_user').val();
var calendar = $('#calendar').fullCalendar({
events: {
url: '<?php echo get_site_url(); ?>/get_calcat_calendar.php',
data: function() { // a function that returns an object
return {
dynamic_value1: id,
dynamic_value2: user
};
}
error: function() {
alert('There was an error while fetching events.');
}
}
});
});
});
</script>
Also I am going to add the file which is generating the json file below:
PHP CODE:
while($row = mysqli_fetch_assoc($result)){
$title = get_the_title($row['ID']);
$url = get_permalink($row['ID']);
$e = array();
$e['title'] = $title;
$e['url'] = $url;
$e['start'] = $row['start_date'];
$e['end'] = $row['end_date'];
$e['color'] = '#33cc33';
array_push($events, $e);
}
echo json_encode($events);
exit();
This is the code which I am using the fetch the json from the database. Any help will be greatly appreciated. Thank You
REQUIREMENT UPDATE:
[{"title":"Timeout72","url":"http:\/\/www.goawebsites.com\/goacalendar\/event\/timeout72\/","start":"2017-11-29","end":"2017-12-31","color":"#33cc33"}]
<div id='calendar'></div>
OTHER CALENDAR SCRIPT:
<script>
$(document).ready(function() {
var user_id = $('#current_user').val();
$('#calendar').fullCalendar({
displayEventTime: false,
events: [
<?php foreach($result as $r) { ?>
{
<?php $title = get_the_title($r['event_id']); ?>
<?php $url = get_permalink($r['event_id']); ?>
title: '<?php echo html_entity_decode($title); ?>',
start: '<?php echo $r['start_date'] ?>',
end: '<?php echo $r['end_date']." 23:59:59" ?>',
url: '<?php echo $url; ?>',
color: '#33cc33'
},
<?php } ?>
]
});
});
</script>
This should be more like what you need:
1) When you first set up your calendar, define your extra "user" and "category" data parameters dynamically (using a callback function).
2) Inside your category "change" event, all you need to do now is simply tell the calendar to refetch the events. There is no need to completely re-initialise the calendar, as you have been doing.
I can't see all of the code, including where you first initialise the calendar, so this may not be 100% accurate, but this is the general idea:
$(document).ready(function() {
$('#calendar').fullCalendar({
events: {
url: '<?php echo get_site_url(); ?>/get_calcat_calendar.php',
data: function() { //using a callback function here allows fullCalendar to fetch the latest values of these parameters every time it makes a new request to the server, rather than them being supplied statically at initialisation
return {
id: $('#ccategory').val(),
user: $('#current_user').val()
};
},
error: function() {
alert('There was an error while fetching events.');
}
}
});
$('#ccategory').change(function() {
//just tell the calendar re-fetch the events. It will automatically get the latest category ID value and send it to the server as a parameter
$("#calendar").fullCalendar("refetchEvents");
});
});
This is based on the pattern shown in the "Dynamic data parameter" section in the documentation at https://fullcalendar.io/docs/event_data/events_json_feed/
Can some help me to solve this problem
I have a map on my website and i want to refresh map only on clicking on category my this is my product
<?php
/* $message = "in home";
echo "<script type='text/javascript'>alert('$message');</script>";*/
foreach($categories as $category){
echo '<li><img src="'.base_url('uploads/'.$category->image).'" alt="'.$category->cat_name.'" width="30" height="30"/></br><span>'.$category->cat_name.'</span></li>';
}
?>
</ul>
</div>
</div>
<script>
function changeData(category){
var urlCI = '.base_url('main/home/' .$category->adv_category).';
$.ajax({
type: "POST",
url: urlCI,
data:{'categoryReq':category},
success: function(response) {
if(response!=''){
$('map_marker').html(response);
}else{
return false;
}
}
});
}
</script>
my controller code is if you need other code please ask i will give. I give this just for refrence, thank you
public function home($cat=NULL)
{
//$cat=10;
//echo debug_backtrace()[1]['function'];
if($_POST)
{
print_result($_POST);
}
$sql="SELECT * FROM (`ad_category`) WHERE `status`=1 AND `del_status`=0";
$this->data['categories']=$this->db->query($sql)->result();
if($cat)
{
//$message = $cat;
//echo "<script type='text/javascript'>alert('$message');</script>";
//$this->data['middle_view']='home_again';
$this->data['ads']=$this->advt_m->get_advts($cat);
$this->input->post('map_marker',$this->data);
$this->data['subview']='home';
$this->load->view('__layout_main',$this->data);
}
else
{
/*$message = "Here 2";
echo "<script type='text/javascript'>alert('$message');</script>";
*/
$this->data['subview']='home';
//$this->data['middle_view']='home';
$this->data['ads']=NULL;
$this->load->view('__layout_main',$this->data);
}
var urlCI = '.base_url('main/home/' .$category->adv_category).';
probably should be
var urlCI = '<?php echo base_url("main/home/$category->adv_category"); ?>';
Split the Map div and its javascripts into another view.
Create function with all necessary functionalities for map. Add and load the it through Ajax call.
Ajax success:
success:function(response){
$('div').html(response);
//response will be the function which holds the $this->load->view('map');
}
map.php
<div id="map">
YOUR MAP GOES HERE
</div>
<script>
MAP SCRIPT
</script>
main.php (Your frontend)
<div id="map_here">
</div>
<script>
$.ajax({
type:"POST",
//Send some values
data:{
somevalue:'somedata',
category:"mine"
},
url:"<?php echo base_url();?>mycontroller/mapfunc",
success:function(response){
$('#map_here').html(response);
}
})
</script>
myconroller:
function mapfunc(){
//Using this value you can change the script
$data['category'] = $_POST('category');
$data['location'] = $_POST('somevalue');
//Process the works
$this->load->view('map',$data);
//On Ajax call this page can be loaded
}
Each ajax call it will reload the div.
any doubts just comment it...
I am submitting form data via Ajax and would like to display a message above the form on successful submit.
Currently the form does send the data successfully. It should render the feedback message on form submit <?php $this->renderFeedbackMessages(); ?> as defined in my config.php
Where am I going wrong? Possibly doing things in the wrong order due to first time working with mvc?
my config.php file I have the following defined;
define("FEEDBACK_BOOK_ADD_SUCCESSFUL", "Book add successful.");
my model;
public function addIsbn($isbn)
{
// insert query here
$count = $query->rowCount();
if ($count == 1) {
$_SESSION["feedback_positive"][] = FEEDBACK_BOOK_ADD_SUCCESSFUL;
return true;
} else {
$_SESSION["feedback_negative"][] = FEEDBACK_NOTE_CREATION_FAILED;
}
// default return
return false;
}
my controller;
function addIsbn()
{
// $_POST info here
header('location: ' . URL . 'admin/searchIsbn');
}
my searchIsbn.php;
<?php $this->renderFeedbackMessages(); ?>
<div>
//my html form here
</div>
<div id="result"></div>
<script>
$('#form').submit(function() {
event.preventDefault();
var isbn = $('#isbn_search').val();
var url='https://www.googleapis.com/books/v1/volumes?q=isbn:'+isbn;
$.getJSON(url,function(data){
$.each(data.items, function(entryIndex, entry){
$('#result').html('');
var html = '<div class="result">';
html += '<h3>' + entry.volumeInfo.isbn + '</h3>';
html += '<hr><button type="button" id="add" name="add">add to library</button></div>';
$(html).hide().appendTo('#result').fadeIn(1000);
$('#add').click(function(ev) {
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>admin/addIsbn',
data: {
'isbn' : isbn
}
});
});
});
});
});
</script>
No console error messages.
You are redirecting here:
header('location: ' . URL . 'admin/addIsbn');
remove it.
echo the success message here and add it to an HTML element's .html() API.
Your page will not be refreshed.
Your page is making the call to admin/addIsbn which is redirected to admin/searchIsbn. So you already have the output of renderFeedbackMessages() being sent to your function.
Use the success callback to output the results to the page:
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>admin/addIsbn',
data: {
'isbn' : isbn
},
success: function(data) {
$('#result').html(data);
}
});
The only way I could get this to work was to add an auto-refresh to my Ajax success function as follows;
window.location.reload(true);
Working however open to suggestions.
<?php echo auto_link(site_url('guest/view/quote/' . $quote->quote_url_key)); ?>
This is creating for instance the following link:
http://domainname.com/guest/view/quote/d163df9c4d426b3ab5ef6247bc380745
How can I add an target="_blank" to this php code. Or is there another way to achieve the same.
EDIT 1: Added all scripts from the php page.
<script type="text/javascript">
$(function() {
$('#btn_add_item_from_lookup').click(function() {
$('#modal-placeholder').load("<?php echo site_url('item_lookups/ajax/modal_item_lookups'); ?>/" + Math.floor(Math.random()*1000));
});
$('#btn_add_item').click(function() {
$('#new_item').clone().appendTo('#item_table').removeAttr('id').addClass('item').show();
});
<?php if (!$items) { ?>
$('#new_item').clone().appendTo('#item_table').removeAttr('id').addClass('item').show();
<?php } ?>
$('#btn_save_quote').click(function() {
var items = [];
var item_order = 1;
$('table tr.item').each(function() {
var row = {};
$(this).find('input,select,textarea').each(function() {
if ($(this).is(':checkbox')) {
row[$(this).attr('name')] = $(this).is(':checked');
} else {
row[$(this).attr('name')] = $(this).val();
}
});
row['item_order'] = item_order;
item_order++;
items.push(row);
});
$.post("<?php echo site_url('quotes/ajax/save'); ?>", {
quote_id: <?php echo $quote_id; ?>,
quote_number: $('#quote_number').val(),
quote_date_created: $('#quote_date_created').val(),
quote_date_expires: $('#quote_date_expires').val(),
quote_status_id: $('#quote_status_id').val(),
items: JSON.stringify(items),
custom: $('input[name^=custom]').serializeArray()
},
function(data) {
var response = JSON.parse(data);
if (response.success == '1') {
window.location = "<?php echo site_url('quotes/view'); ?>/" + <?php echo $quote_id; ?>;
}
else {
$('.control-group').removeClass('error');
for (var key in response.validation_errors) {
$('#' + key).parent().parent().addClass('error');
}
}
});
});
$('#btn_generate_pdf').click(function() {
window.location = '<?php echo site_url('quotes/generate_pdf/' . $quote_id); ?>';
});
var fixHelper = function(e, tr) {
var $originals = tr.children();
var $helper = tr.clone();
$helper.children().each(function(index) {
$(this).width($originals.eq(index).width())
});
return $helper;
};
$("#item_table tbody").sortable({
helper: fixHelper
});
});
</script>
I have resolved it. Not by using any code but by simple explaining to the users to use ctrl + click. It is probably not the best thing. There should be a way to achieve the same with code. But after the long discussion with Royal Bg I thought it would be wise to stop putting oil on the fire.
I hope that in the future someone else takes up the original question and posts an solution for others to benefit from. In the meantime I will accept this as an answer. I hope others do too.
<?php
session_start();
?>
<?php
$con=mysqli_connect("localhost","root","") or die(mysqli_error());
mysqli_select_db($con, "sada_r_t_m");
$result=mysqli_query($con, "SELECT * FROM products ");
echo "<h2 fontsize = '26' color = 'yellow' align = 'center'>Flipkart</h2>";
echo "<table border = '5' cellpadding = '12' align = 'center' background-color = '#84ed86' color = '#761a9b' >";
echo "<tr>";
echo "<th>SNO</th>";
echo "<th>Product Name</th>";
echo "<th>Price</th>";
echo "<th>Cart</th>";
echo "</tr>";
while($data = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<th>".$data['id']."</th>";
echo "<th>".$data['name']."</th>";
echo "<th>".$data['price']."</th>";
echo "<th><a href='#' Onclick='add(".$data['id'].")'>Add to Cart</a></th>";
echo "</tr>";
}
echo "</table>";
?>
<script type="text/javascript">
function add(id){
alert(id);
$.ajax({
url: '../ajax.php',
type: 'POST',
data: { action: "add",id: id, val:1} ,
//contentType: 'application/json; charset=utf-8',
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});
}
</script>
I passed the values through ajax in php. I wrote only in single php page.
How to pass values through ajax in php. While passing values,i am getting below error
Uncaught ReferenceError: $ is not defined
How to achieved this error i am new to php.
Please add jquery library file for use $. Please put this code in your file at top.
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
OR
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
Your JavaScript Change this type. Error alert show what error Occurred
Add Jquery library file at head tag
<script type="text/javascript">
function add(id){
alert(id);
$.ajax({
url: '../ajax.php',
type: 'POST',
data: { action: "add",id: id, val:1} ,
success: function (response) {
try{
alert(response.status);
}
catch(e){
alert("Error"+e);
}
},
error: function (e) {
alert("error"+e); or alert("error"+JSON.stringify(e));
}
});
}
</script>
You use try and catch . this show where error show
this code useful for you
I cannot comment yet, so I posted here. There's a good example on another answer on how to properly do ajax post requests:
http://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php
Also, this is a good tutorial that will set you on the right track:
https://www.codeofaninja.com/2013/09/jquery-ajax-post-example.html
http://hayageek.com/jquery-ajax-post/
Also, try to change ../ajax.php to the full url.