I am trying to implement a ajax plus one button with my site in code igniter. I am very new with Ajax and codeigniter so I'm needing some guidance.
Here is the portion of my controller where I'm starting. Please note, this is inside the method that creates my profile view in which I'm trying to create this.
$voteId= $this->input->post('voteId');
$upOrDown= $this->input->post('upOrDown');
$status ="false";
$updateRecords = 0;
if($upOrDown=='upvote'){
$updateRecords = $this->community_model->updateUpVote($voteId);
}else{
$updateRecords = $this->community_model->updateUpVote($voteId);
}
if($updateRecords>0){
$status = "true";
}
echo $status;
// This variable will be accessed from the view
$data['airwave'] = $airwave;
$data['profile_id'] = $profile_id;
$this->load->view('includes/templates/main_page_template', $data);
}
Here is the method in the model:
function updateUpVote($voteId){
$sql = "UPDATE airwaves_comments set thumbsup = thumbsup+1 WHERE thumbsup =?";
$this->db->query($sql, array($voteId));
return $this->db->affected_rows();
}
here is my view:
<div id='thumb_holder'>
<div id='thumb_report'>
<a href='mailto:info#cysticlife.org'>
• report
</a>
</div>
<div class= 'thumb_counter'>
+0
</div>
<div id='thumb_thumb'>
<a class='myButtonLink voteMe' id='1_upvote'<span id="1_upvote_result">+</span>></a>
</div>
</div>
here is the script:
<script>
$(document).ready(function(){
$(".voteMe").click(function() {
var voteId = this.id;
var upOrDown = voteId.split('_');
$.ajax({
type: "post",
url: "account/profile/voteMe",
cache: false,
data:'voteId='+upOrDown[0] + '&upOrDown=' +upOrDown[1],
success: function(response){
try{
if(response=='true'){
var newValue = parseInt($("#"+voteId+'_result').text()) + 1;
$("#"+voteId+'_result').html(newValue);
}else{
alert('Sorry Unable to update..');
}
}catch(e) {
alert('Exception while request..');
}
},
error: function(){
alert('Error while request..');
}
});
});
});
</script>
additionally here is what it looks like to give a better idea of what's going on, but I want there to be the number of votes after the plus sign:
To summarize: Essentially I was taking a tutorial on a demo tutorial that is similar, but it was not exactly what I am trying to do. This is basically me taking the code from the tutorial and trying to splice it with my code and meet my specific needs and learning ajax at the same time. I feel like I'm close as it's updating the specified column in my table (incorrectly),however can't get it to visibly function.
I'm not exactly sure what your saying your problem is. But This I do see.
When trying to fetch a view for ajax you have to return the view as data
http://ellislab.com/codeigniter/user-guide/general/views.html (bottom of the page)
Like this
$view = $this->load->view('includes/templates/main_page_template', $data, true);
echo $view;
This will send the rendered view to the browser
Put this code in view file
<input type="hidden" name="siteurl" id="siteurl" value="<?php echo site_url(); ?>">
<input type="hidden" name="baseurl" id="baseurl" value="<?php echo base_url(); ?>">
Then get hidden value in your script
var site_path = $("#siteurl").val();
var base_path = $("#baseurl").val();
$.ajax({
type: "post",
url: site_path+"account/profile/voteMe",....
Related
I want to show an image in img tag. when ajax is called in CodeIgniter.
this is the code which receives the data from the database and displays it in a bootstrap model. but the main problem is that I want to show an image in img tag but it not showing.
$(".Edit-modal").on("shown.bs.modal", function (e) {
var button = $(e.relatedTarget);
var ID = button.parents("tr").attr("data-id");
var modal = $(this);
$.ajax({
url: "'.base_url().'Employees/master_get_employees",
data: {ID:ID},
type: "POST",
success:function(output){
try{
var outputData = JSON.parse(output);
modal.find("#EditImage").attr("'.base_url().'src",outputData.pic);
}
catch(ex){
var split = output.split("::");
if(split[0] === "FAIL"){
Shafiq.notification(split[1],split[2])
}else{
Shafiq.notification("Could Not Load Data, Please Contact System Administrator For Further Assistance","error");
}
}
}
});
});
And This is the Img tag where I want to display image.
<div class="col-md-3">
<div class="form-group">
<label for="EditcontactNoSelector">Employee Picture</label>
<img src="" id="EditImage" alt="Not Found">
</div>
</div>
And this is the function through which data is fetched from the database
public function master_get_employees()
{
if ($this->input->post()) { //If Any Values Posted
if ($this->input->is_ajax_request()) { //If Request Generated From Ajax
$ID = $this->input->post('ID');
if (!isset($ID) || !is_numeric($ID)) {
echo "FAIL::Something went wrong with POST request, Please contact system administrator for further assistance::error";
return;
}
$table = "employees e";
$selectData = "e.id AS ID,e.Phone,e.Mobile,e.CNIC,e.Perm_Address,e.Picture as pic,d.name as Designation,s.title as Shift, e.Name,e.Father_Name AS FatherName,e.Phone AS Contact,e.JoinDate,e.BasicSalary, e.Pres_Address AS Address,e.IsEnabled";
$where = array(
'e.id' => $ID, 'e.IsActive' => 1
);
$result = $this->Common_model->select_fields_where_like_join($table, $selectData,$where, TRUE);
print json_encode($result,JSON_UNESCAPED_SLASHES);
}
}
}
I guess you have base_url() function in javascript to find base url of you site.
If so then you can use
$("#EditImage").attr("src",base_url()+outputData.pic);
If you don't have base_url() function in javascript you can find it here:
how to get the base url in javascript
instead of this
url: "'.base_url().'Employees/master_get_employees",
You can use below,
url: "<?php echo site_url('Employees/master_get_employees'); ?>",
Also at server side if you need only image url then just create image url from $result, store it in variable like $img_path in "master_get_employees" function and then just
echo json_encode(['img_path'=>$img_path]);
And in ajax success just do below
$("#EditImage").attr('src',outputData.img_path);
So I'm trying to pass a value from my AJAX code to my PHP code which connects to an API to get the weather. It works when just using PHP, but I want ajax to return the results to some div on the same page. My code looks correct when I compare it to other examples but it just doesn't work.
Code may not be written with security in mind, standard practice etc, I'm just trying to play around with API's and get the basics of AJAX.
api.php:
$city = $_POST['city'];
function getCityLat($x) {
$latUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address='. $x .'APIKEY';
$latResponse = file_get_contents($latUrl);
$latArray = json_decode($latResponse, true);
$lat = $latArray['results'][0]['geometry']['location']['lat'];
echo $lat;
return $lat;
}
function getCityLng($y) {
$lngUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address='. $y .'APIKEY';
$lngResponse = file_get_contents($lngUrl);
$lngArray = json_decode($lngResponse, true);
$lng = $lngArray['results'][0]['geometry']['location']['lng'];
echo $lng;
return $lng;
}
function getWeather($x, $y) {
$weatherUrl = 'https://api.darksky.net/forecast/APIKEY/' . $x . ',' . $y;
$weatherResponse = file_get_contents($weatherUrl);
$weatherArray = json_decode($weatherResponse, true);
$timeZone = $weatherArray['timezone'];
$locWeather = $weatherArray['currently']['temperature'];
$locFeelsLike = $weatherArray['currently']['apparentTemperature'];
$windSpeed = $weatherArray['currently']['windSpeed'];
$weatherSummary = $weatherArray['currently']['summary'];
$time = $weatherArray['currently']['time'];
$outputweather = '<p>Temp: '.$locWeather.'</p>';
echo $outputweather;
}
getWeather(getCityLat($city), getCityLng($city));
?>
index.php(html):
<h3 align="center">Weather</h3>
<form align="center" method="POST">
<input type="text" id="city" name="city" placeholder="Enter City">
<button class="btn btn-xs btn-success" name="city_go" id="city_go">Go</button>
</form>
<div id="weather"></div>
JQuery:
function getWeather(city) {
$.ajax({
url: "api.php",
method: "POST",
data: {city:city},
dataType: "text",
success: function(data) {
$('#weather').html(data);
}
});
}
$(document).on('click', '#city_go', function() {
var city = $('#city').val();
getWeather(city);
});
The problem is that you are submitting a form, which forces a page refresh. Everything else is working correctly, just the page is being refreshed. To fix that you need to update your click event to something like
$(document).on('click', '#city_go', function(e) {
e.preventDefault();
var city = $('#city').val();
getWeather(city);
});
the preventDefault() call will cancel the default action of the form (the page refresh) and allow the AJAX call to follow through and display the data.
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 have a problem concerning my code which should change content in a div onclick "More News articles" as the change will happen only once. I see in Chrome Developer mode that it fires every click a request. What goes wrong?
Output.php
<?php
require_once('../pe13f/SSI.php');
require_once ('../PE13/smf_2_api.php');
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function MakeRequest(id)
{
$.ajax({
url : 'display.php',
data:{"id":id},
type: 'GET',
success: function(data){
$('#streaminnern').html(data);
}
});
}
</script>
<div id="stream" class="bg4 roundedcrop shadow">
<div class="ph25 pv20">
<h1>News</h1>
<input id="streamcnt" name="streamcnt" type="hidden" value="" />
</div>
<div id="streamadd"></div>
<div id="streaminnern">
<?php
$num_recent = 5;
echo $num_recent;
?>
</div>
<div onclick="MakeRequest(<?php echo $num_recent; ?>);" id="streammore">More News articles</div>
</div>
backend php display.php
<?php
$num_recent = $_GET['id']+5;
echo $num_recent;
?>
Greetings Emil
Check the source that is produced by output.php. You'll find there onclick="MakeRequest(5);". Basically - on every click you call MakeRequest(5) which always fires call display.php?id=5 (you probably see that in your dev console).
Try something like this:
<script>
var lastId = 0; // var that stores last fetched ID
function MakeRequest(id)
{
if(!lastId) // if there is no last ID use the one from initial onclick
lastId = id;
$.ajax({
url : 'display.php',
data:{"id":lastId}, // note that we are using the lastId var
type: 'GET',
success: function(data){
$('#streaminnern').html(data);
lastId = data; // save fetched ID in our global var
}
});
}
</script>
The request is always the same. Suppose $num_recent is initially set to 5.
Then as per your code MakeRequest(5) will be executed. And your ajax call updates a div with class streaminnern. So the new id has no impact on the next ajax call. For the ajax request to be sent updated value you may set
$.ajax({
url : 'display.php',
data:{"id":$('#streaminnern').html()},
.................
});
I've been looking for a week now for a decent full working example of how to use AJAX with Codeigniter (I'm an AJAX novice). The posts / tuts I've seen are old - all the programming languages have moved on.
I want to have an input form on a page which returns something to the page (e.g. a variable, database query result or html formatted string) without needing to refresh the page. In this simple example is a page with an input field, which inserts the user input into a database. I'd like to load a different view once the input is submitted. If I could understand how to do this I'd be able to adapt it to do whatever I needed (and hopefully it would help others too!)
I have this in my 'test' controller:
function add(){
$name = $this->input->post('name');
if( $name ) {
$this->test_model->put( $name );
}
}
function ajax() {
$this->view_data["page_title"] = "Ajax Test";
$this->view_data["page_heading"] = "Ajax Test";
$data['names'] = $this->test_model->get(); //gets a list of names
if ( $this->input->is_ajax_request() ) {
$this->load->view('test/names_list', $data);
} else {
$this->load->view('test/default', $data);
}
}
Here is my view, named 'ajax' (so I access this through the URL www.mysite.com/test/ajax)
<script type="text/javascript">
jQuery( document ).ready( function() {
jQuery('#submit').click( function( e ) {
e.preventDefault();
var msg = jQuery('#name').val();
jQuery.post("
<?php echo base_url(); ?>
test/add", {name: msg}, function( r ) {
console.log(r);
});
});
});
</script>
<?php echo form_open("test/add"); ?>
<input type="text" name="name" id="name">
<input type="submit" value="submit" name="submit" id="submit">
<?php echo form_close(); ?>
All that happens currently is that I type in an input, updates the database and displays the view "test/default" (it doesn't refresh the page, but doesn't display "test/names_list" as desired. Many thanks in advance for any help, and for putting me out of my misery!
Set unique id to the form:
echo form_open('test/add', array('id'=>'testajax'));
I assume that you want replace a form with a view:
jQuery(document).ready(function(){
var $=jQuery;
$('#testajax').submit(function(e){
var $this=$(this);
var msg = $this.find('#name').val();
$.post($this.attr('action'), {name: msg}, function(data) {
$this.replace($(data));
});
return false;
});
better way if you return url of view in json response:
$.post("<?php echo base_url(); ?>test/add", {name: msg}, function(data) {
$this.load(data.url);
},"json");
from your last comment - I strongly not suggest to replace body, it will be very hard to support such code.
but here is anser:
$.post("<?php echo base_url(); ?>test/add", {name: msg}, function(data) {
$('body').replace(data);
});