concat the two id came from database in ajax and codeigniter - php

i am having trouble in concating the value of my two ID's from database to generate a new ID and use it to save again in Database. I am using codeigniter and i want something a good technique/way to concat for better result or maybe faster.
Also i am having a problem, whenever there is a value in my database, i cannot increment my ID by having +1. I got an output of 1-undefine-1
Here is my ajax:
function getcheckupID() {
var init = 0;
var value = $('#clinicID').html();
$.ajax ({
url: siteurl+"myclinic/getcheckID",
type: "GET",
dataType: "JSON",
success: function(data) {
if(data.length>0) {
$('#checkID').text(value+"-"+data[0]['clinic_id']+1);
$("#checkID").css('visibility','visible');
}
else {
$('#checkID').text(value+"-"+init);
$("#checkID").css('visibility','visible');
}
}
})
}
function get_clinicID() {
$("#clinicID").empty();
$.ajax({
url: siteurl+"myclinic/get_clinicID",
type: "GET",
dataType: "JSON",
success: function(data) {
$('#clinicID').text(data[0]['clinic_id']);
}
});
}
i check the records in my DB using this if(data.length>0) then if i got record, i go get the data and +1 it. I got a value of undefined, but if it goes to else, it outputs bad, because whenever i refresh it. sometimes it only outputs - 0, where i want is 1-0. Then refresh it again. How can i concat safely ? Is it an issue in ajax ?. making slow ?
Here is my controller for it :
public function getcheckID() {
$checkID = $this->clinic_model->checkupID();
echo json_encode($checkID);
}
My Model :
public function checkupID() {
$query = $this->db->query('SELECT tbl_check_up.check_up_id FROM tbl_check_up');
return $query->result();
}

Related

How to correctly select and show (or insert) data from (in) MySQL database with AJAX call to PHP function?

So far I have something like this:
//HTML
<body onload=getRoomTemp();>
//JS
function getRoomTemp() {
$.ajax({
type: "POST",
url: "getRoomTemp.php",
datatype: "text";
data: {
temp: temp
}
}).done(function () { $('#getRoomTemp').append(text); });
}
//PHP
<?php
if (isset($_POST['temp'])) {
require('database.php');
$query = ("SELECT temp FROM tempWHERE tempID=1");
$res = mysql_query($query) or die("ERROR ".__LINE__.": ".mysql_error());
while ($ar = mysql_fetch_array($res)) {
$temperatureIn = $ar['temp'];
echo $temperatureIn;
}
}
?>
So, when my HTML body loads, I would like to make query and show query result in div called "getRoomTemp" with AJAX. Later, I will need the same technique to insert data in MySQL (single number value) on button click.
I can't find the problem with my current code, tried different dataType for ajax but no success. Please help..
You have 2 undefined identifiers temp and text, try
function getRoomTemp() {
$.ajax({
type: "POST",
url: "getRoomTemp.php",
dataType: "text",
data: {
temp: 'temp'
}
}).done(function (text) { $('#getRoomTemp').append(text); });
}

ajax like/unlike button not switching back

I am trying to make a like button on a page and cant seem to get it to work right. Basically there are three function that use ajax to send the data to a php page that updates the database. Ive checked the db and all three update correctly. If the user doesnt originally like and clicks, it correctly shows the unlike button but then, if you click unlike it doesnt switch back (although it does update the database).
Is this the correct way to set this up? Im pretty new to ajax and am not sure if this is the right approach. THanks in advance
Steve
public function likesScript($p){?>
<script>
//display list of people who like this
function getLikes(){
$.ajax({
type: "POST",
url: "likelist.php",
data: { p: "<?php echo $_GET['p']?>"}
}).success(function(res) {
//check to see if current user likes this
if($('li#<?PHP echo $_SESSION['userId']; ?>').length){
$(".Like").addClass('hidden');
$(".UnLike").removeClass('hidden');
}
else{
$(".UnLike").addClass('hidden');
$(".Like").removeClass('hidden');
}
$("#likedBy").append(res);
console.log(res);
});
}
function removeLike() {
$.ajax({
type: "POST",
url: "likedata.php",
data: { arg1: "<?php echo $_SESSION['userId']?>", arg2: "<?php echo $p;?>", arg3: "0" }
})
getLikes();
return false;
}
function addLike() {
$.ajax({
type: "POST",
url: "likedata.php",
data: { arg1: "<?php echo $_SESSION['userId']?>", arg2: "<?php echo $p;?>", arg3: "1" }
})
getLikes();
return false;
}
$(document).ready(function() { getLikes();
$(".UnLike").live('click',removeLike);
$(".Like").live('click',addLike);
});
</script>
likelist.php:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/view.class.php';
$view = new view();
include $_SERVER['DOCUMENT_ROOT'].'/profile.class.php';
include $_SERVER['DOCUMENT_ROOT'].'/init.php';
$profile = new profile($dbh);
if(isset($_POST)){
$p = $_POST['p'];
$view->printLikes($profile->getLikes($p));
}
likedata.php:
<?php
include $_SERVER['DOCUMENT_ROOT'].'/profile.class.php';
include $_SERVER['DOCUMENT_ROOT'].'/init.php';
$profile = new profile($dbh);
if(isset($_POST)){
$liker = $_POST['arg1'];
$likee = $_POST['arg2'];
$likeYesNo = $_POST['arg3'];
$profile->insertLikes($liker, $likee, $likeYesNo);
}
?>
AJAX is ayshcronous so the getLikes functions will fire before the AJAX is completed in both addLike and removeLike. You definitely need to put getLikes into the success callback of $.ajax so it doesn't retrieve data that may not have been updated
function addLike() {
$.ajax({
type: "POST",
url: "likedata.php",
data: { arg1: "<?php echo $_SESSION['userId']?>", arg2: "<?php echo $p;?>", arg3: "1" },
success: getLikes
})
}
Ok... this is what I have learned from using ajax repeat calls...
IE hates them and sometimes they just don't work the way they should.
Try this
function addLike() {
var randnum = Math.floor(Math.random()*1001); //Add This Here on all Ajax Calls
$.ajax({
type: "POST",
url: "likedata.php",
cache: false, //Add This Here - Assists in helping Browsers not to cache the Ajax call
data: yourdata + '&random=' + randnum, // Add this to the end of your data you are passing along *'&random=' + randnum,*
success: function() {
getLikes();
}
})
}
Adding a random piece of data causes the browsers to think its a new call.
Also, the random=randnum wont effect anything on the php side.

Access php function data via ajax

I have this php function inside a class the returns json data
function getPhotoDetails( $photoId ) {
$url = $this::APP_URL . 'media/' . $photoId . $this::APP_ID;
return $this->connectToApi($url);
}
and this ajax request
function getPhotoDetails( photoId ) {
$.ajax({
type: "GET",
cache: false,
url: 'index.php',
success: function (data) {
console.log(data);
}
});
}
The question is how I can call the php function to get the json data.
Solution:
A big thanks to all of you guys and thanks to Poonam
The right code
PHP:
I created a new object instance in php file
$photoDetail = new MyClass;
if(isset($_REQUEST['image_id'])){
$id = $_REQUEST['image_id'];
echo (($photoDetail->getPhotoDetails($id)));
}
JavaScript
function getPhotoDetails( photoId ) {
$.ajax({
type: "GET",
cache: false,
url: './instagram.php?image_id=' + photoId,
success: function (data) {
var data = $.parseJSON(data);
console.log(data);
}
});
}
Try with setting some parameter to identify that details needs to send for e.g assuming photoid params needed for function
function getPhotoDetails( photoId ) {
$.ajax({
type: "GET",
cache: false,
url: 'index.php?sendPhoto=1&photoid=23',
success: function (data) {
console.log(data);
}
});
}
and then on index.php check (You can make check for photoid whatever you need as per requirement)
if(isset($_REQUEST['sendPhoto'])){
$id = $_REQUEST['photoid'];
return getPhotoDetails($id);
}
setup a switch-case. Pass the function name as GET or POST variable such that it calls the php function
You need a file which calls the PHP function. You can't just call PHP functions from Ajax. And as pointed out by Tim G, it needs to use the proper header, format the code as JSON, and echo the return value (if the function is not already doing these things).

JQuery + Json - first steps with an example

I need (recently) to get an array from the server after an ajax call created by jquery. I know that i can do it using JSON. But i don't know how to implement it with JQuery (im new with JSON). I try to search in internet some example, but i didnt find it.
This is the code :
// js-jquery function
function changeSponsor() {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'id=changespon',
success: function(msg) {
// here i need to manage the JSON object i think
}
});
return false;
}
// php-server function
if((isset($_POST['id'])) && ($_POST['id']=="changespon")) {
$linkspon[0]="my ";
$linkspon[1]="name ";
$linkspon[2]="is ";
$linkspon[3]="marco!";
echo $linkspon;
}
in fact, i need to get the array $linkspon after the ajax call and manage it. How can do it? I hope this question is clear. Thanks
EDIT
ok. this is now my jquery function. I add the $.getJSON function, but i think in a wrong place :)
function changeSponsor() {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'id=changespon',
dataType: 'json',
success: function(data) {
$.getJSON(url, function(data) { alert(data[0]) } );
}
});
return false;
}
Two things you need to do.
You need to convert your array to JSON before outputting it in PHP. This can easily be done using json_encode, assuming you have a recent version of PHP (5.2+). It also is best practice for JSON to use named key/value pairs, rather than a numeric index.
In your jQuery .ajax call, set dataType to 'json' so it know what type of data to expect.
// JS/jQuery
function changeSponsor() {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'id=changespon',
dataType: 'json',
success: function(data) {
console.log(data.key); // Outputs "value"
console.log(data.key2); // Outputs "value2"
}
});
return false;
}
// PHP
if((isset($_POST['id'])) && ($_POST['id']=="changespon")) {
$linkspon["key"]= "value";
$linkspon["key2"]= "value2";
echo json_encode($linkspon);
}
1) PHP: You need to use json_encode on your array.
e.g.
// php-server function
if((isset($_POST['id'])) && ($_POST['id']=="changespon")) {
$linkspon[0]="my ";
$linkspon[1]="name ";
$linkspon[2]="is ";
$linkspon[3]="marco!";
echo json_encode($linkspon);
}
2) JQUERY:
use $.getJSON(url, function(data) { whatever.... } );
Data will be passed back in JSON format. IN your case, you can access data[0] which is "my";

Am i passing the value correctly to my controller from jquery?

I am doing a delete on a table using jquery,
$('table#chkbox td a.delete').click(function()
{
if (confirm("Are you sure you want to delete this row?"))
{
var id = $(this).parent().attr('id');
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: "<?php echo base_url().'index.php/libraryController/librarydelete' ?>",
data: { 'id': id },
cache: false,
success: function()
{
parent.fadeOut('slow', function() {$(this).remove();});
}
});
}
});
I am getting the id value correctly but my data parameter doesn't get passed to my controller,
function librarydelete($id)
{
$del = $id;
echo $del;
$this->librarymodel->deletebook_issue($id);
$this->session->set_flashdata('response','Deleted successfully');
redirect('libraryController/loadmagazinedetails');
}
Any suggestion...
I am getting the error,
Missing argument 1 for libraryController::librarydelete() and Undefined variable: id
Your are posting the data, so you can get the id like this:
function librarydelete()
{
$del = $_POST['id'];
echo $del;
$this->librarymodel->deletebook_issue($_POST['id']);
$this->session->set_flashdata('response','Deleted successfully');
redirect('libraryController/loadmagazinedetails');
}
Looks like you are using codeigniter, so this would be even better:
$del = $this->input->post('id');
Change id to $id in controller function parameter
means, your function should be
function librarydelete($id)
{
$del = $id;
echo $del;
$this->librarymodel->deletebook_issue($id);
$this->session->set_flashdata('response','Deleted successfully');
redirect('libraryController/loadmagazinedetails');
}
Perhaps it is because you are using the variable name 'data' twice. Try renaming var data to var mydata.
The way you are passing data is wrong. This is the way you should be setting data.
var data= {id: id };
in your case let me not use the variable in the post action and show you how its done.
$.ajax(
{
type: "POST",
url: "<?php echo base_url().'index.php/libraryController/librarydelete' ?>",
data: {id:id},
cache: false,
success: function()
{
parent.fadeOut('slow', function() {$(this).remove();});
}
});
Edit: After you modified your code to pass data the right way.
Hey I have not followed MVC framwework in php. but since you are doing a post on the action you can always get the data the following way:
$id=$_POST['id']
and then you can use this id.
Also if you still want to use the function:
function librarydelete($id)
{
$del = $id;
echo $del;
$this->librarymodel->deletebook_issue($id);
$this->session->set_flashdata('response','Deleted successfully');
redirect('libraryController/loadmagazinedetails');
}
just modify the uri action to existingurl+/ i.e append the id to the end and in your route map (if there exists something like this in php in .nets implementation there is 1) just add that route.

Categories