Call CodeIgniter method from JQuery - javascript

I want to call codeigniter method using jquery. My ajax call is working but getting an error. I have added my controller, model, ajax call and error.
According to:
$("body").on("click", ".call-ajax", function() {
// obtém o valor do link
console.log("chamada ajax");
var caminho = "http://localhost/xxxxx/public/uploads/anexos/";
data = {
id_rec: $(this).data("id_rec"),
anexo: caminho + $(this).data("anexo")
};
console.log(data);
// AJAX para o controller
$.ajax({
url: "reclamacao/delete_anexo",
data: data,
type: "POST"
}).done(function(resp) {
console.log("deleção OK");
// Display the resposne
//$("#result").append($("<li/>").html(resp));
});
});
It correctly calls
Check Image 1
But this error occurs:
Check image 2
My CONTROLLER CODE:
public function delete_anexo($id, $file)
{
try
{
if (!$this->input->is_ajax_request())
{
$this->output->set_status_header(404);
return;
}
if (!$this->anexo_model_reclamacao->delete_anexo($id, $file))
throw new Exception("Erro ao excluir", 1);
$alert = 'Operação Realizada com sucesso.';
}
catch (exception $e)
{
$alert = $e->getMessage();
}
bootbox_alert($alert);
}
MODEL CODE:
public function delete_anexo($id, $file) {
$this->db->delete($this->table, array('id_reclamacao' => $id, 'file' => $file));
return true;
}

This declaration in the controller public function delete_anexo($id, $file) assumes that the $id and $file are in the url e.g. reclamacao/delete_anexo/{$id}/{$file} which is clearly not what you want by your data jquery declaration. Thus you need to capture the post vars like so:
public function delete_anexo()
{
try
{
if (!$this->input->is_ajax_request()) {
$this->output->set_status_header(404);
exit;
}
$id = $this->input->post('id_rec');
$file = $this->input->post('anexo');
if (is_null($id) || is_null($file)) {
throw new Exception('Parameters missing');
}
if (!$this->anexo_model_reclamacao->delete_anexo($id, $file)) {
throw new Exception("Erro ao excluir", 1);
}
$alert = 'Operação Realizada com sucesso.';
}
catch (exception $e)
{
$alert = $e->getMessage();
}
bootbox_alert($alert);
}

The second error image that you have posted is clearly stating that the second argument is missing from your method call, please double check whether both the arguments are getting posted when you are making the ajax call.

Related

Image not being displayed when received via AJAX

I have an image in my mysql DB, in type longblob. I have an ajax call that requests the image and on success, changes my html image src to be the received image. My ajax post response is the image name (114046.png) but it will trigger the ajax error section, not success. Can someone look through my code and tell me where im going wrong?
Saving image in DB
public function UploadImage($imageData) {
global $dbCon;
$imgFile = $imageData['file']['name'];
$imgSize = $imageData['file']['size'];
if(empty($imgFile)){
error_log("image file empty");
}
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension
// valid image extensions
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
if(!in_array($imgExt, $valid_extensions)) {
error_log("Sorry, only JPG, JPEG, PNG & GIF files are allowed.");
}
// Check file size '5MB'
if($imgSize > 5000000) {
error_log("Sorry, your file is too large.");
}
// rename uploading image
$userpic = rand(1000,1000000).".".$imgExt;
$sql = 'UPDATE userinfo SET image=(:image) WHERE username="'.$this->currentUsername.'"';
$stmt = $dbCon->prepare($sql);
$stmt->bindParam(':image', $userpic);
$stmt->execute();
if($stmt == false) {
error_log("Failed to put image info in DB");
} else {
//image uploaded
}
}
Getting the image from the DB
public function GetImage() {
global $dbCon;
$stmt = $dbCon->query("SELECT image FROM userinfo WHERE username='".$this->currentUsername."'");
$fetchResult = $stmt->fetch();
$data = $fetchResult["image"];
if($stmt == false) {
error_log("Failed to put image info in DB");
} else {
$this->LatestUpdate = "Get Image";
$this->image = $data;
}
}
public function GetTheImage() {
return $this->image;
}
Responding to ajax
if($this->model->LatestUpdate() == "Get Image") {
header("Content-type: image/png");
echo $this->model->GetTheImage();
exit();
}
Ajax call (Set the HTML image to the received image)
window.onload = SetImage;
function SetImage() {
data = "action=" + "getImage";
$.ajax({
url: '../index.php', // point to server-side PHP script
dataType: 'image/png', // what to expect back from the PHP script, if anything
data: data,
type: 'post',
success: function(image) {
console.log("success");
$("#profileImage").attr("src", image);
}, error: function(xhr, status, error) {
alert("Error" + xhr.responseText);
}
});
}

Login with facebook in codeigniter

I am using this, for login with Facebook, but i am not getting user response here is the link
http://demos.idiotminds.com/link.php?link=https://www.box.com/s/108pspt0o0oj0fpr6ghf
I have tried this solution also for codeigniter
protected function getCode() {
$server_info = array_merge($_GET, $_POST, $_COOKIE);
if (isset($server_info['code'])) {
if ($this->state !== null &&
isset($server_info['state']) &&
$this->state === $server_info['state']) {
// CSRF state has done its job, so clear it
$this->state = null;
$this->clearPersistentData('state');
return $server_info['code'];
} else {
self::errorLog('CSRF state token does not match one provided.');
return false;
}
}
return false;
}
for log in with Facebook but i am not getting value from this $user = $facebook->getUser(); it returns 0 value even if i have logged into Facebook.
I have used so many codes for this but did not success, kindly help me out.
I am very frustrated
Download PHP SDK for Facebook
Now create the a folder in application\libarires "facebook"
Put the "SRC" folder of PHP SDK
Now create a file with FacebookApp.php in that folder and put this code
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once( APPPATH . 'libraries/facebook/src/facebook.php' );
class FacebookApp extends Facebook {
var $ci;
var $facebook;
var $scope;
public function __construct() {
$this->ci =& get_instance();
$this->facebook = new Facebook(array('appId' => $this->ci->config- >item('app_id'),'secret' => $this->ci->config->item('app_secret'), 'cookie' => true));
$this->scope = 'public_profile';
}
public function login_url() {
$params = array('scope' => $this->scope);
return $this->facebook->getLoginUrl($params);
}
public function logout_url() {
return $this->facebook->getLogoutUrl(array('next' => base_url() .'logout'));
}
public function getFbObj(){
return $this->facebook;
}
public function get_user() {
$data = array();
$data['fb_user'] = $this->facebook->getUser();
if ($data['fb_user']) {
try {
$data['fb_user_profile'] = $this->facebook->api('/me');
return $data;
} catch (FacebookApiException $e) {
$this->facebook->destroySession();
$fb_login_url = $this->facebook->getLoginUrl(array('scope' => $this->scope));
redirect($fb_login_url, 'refresh');
}
}
}
Now in controller load this library
$this->load->library('facebook/FacebookApp)
in Method
$obj_fb = new FacebookApp();
$fb_user_data = $obj_fb->get_user();
$data['fb_login_url'] = $obj_fb->login_url();
put the fb_login_url in href of login button and now the login will done.
Hope it help you.
Rahul, I had a similar issue. You can find a pretty good solution here.
If you still cannot figure the solution, why don't you look into the JavaScript SDK. It is pretty straight forward and then use AJAX to act on the response that you get from Facebook.

AJAX and MYSQL, AJAX too fast for mysql to query?

I am working on a php/mysql application, I am trying to collect javascript errors to the database using window.onerror, where inside that function I make an ajax request to a php script that will log the errors into the database. However, when I tested it there are supposed to be 13 errors logged, but only one get inserted into the database. All the 13 ajax requests return 200 OK, is this happening because ajax is just simply too fast for the mysql query to process anything. I tried using set timeout on the send request but it doesnt seem to work.
Here is my code:
window.onerror = function(msg, url, line)
{
function createXHR()
{
try { return new XMLHttpRequest(); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
return null;
}
function sendRequest(url, payload)
{
var xhr = createXHR();
if (xhr)
{
xhr.open("POST",url,true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 && xhr.status == 200){
console.log(xhr.responseText);
}
};
xhr.send(payload);
}
}
function encodeValue(val)
{
var encodedVal;
if (!encodeURIComponent)
{
encodedVal = escape(val);
/* fix the omissions */
encodedVal = encodedVal.replace(/#/g, '%40');
encodedVal = encodedVal.replace(/\//g, '%2F');
encodedVal = encodedVal.replace(/\+/g, '%2B');
}
else
{
encodedVal = encodeURIComponent(val);
/* fix the omissions */
encodedVal = encodedVal.replace(/~/g, '%7E');
encodedVal = encodedVal.replace(/!/g, '%21');
encodedVal = encodedVal.replace(/\(/g, '%28');
encodedVal = encodedVal.replace(/\)/g, '%29');
encodedVal = encodedVal.replace(/'/g, '%27');
}
/* clean up the spaces and return */
return encodedVal.replace(/\%20/g,'+');
}
if (window.XMLHttpRequest) {
var master = "llesmana#ucsd.edu";
var payload = "msg=" + encodeValue(msg) + '&url=' + encodeValue(url) + "&line=" + encodeValue(line) + "&master=" + encodeValue(master);
var url_req = "http://104.131.199.129:83/php/log_error.php";
sendRequest(url_req, payload);
return true;
}
return false;
}
PHP:
<?php
/**
* Created by PhpStorm.
* User: xxvii27
* Date: 9/2/14
* Time: 12:30 PM
*/
/* Helper functions */
function gpc($name)
{
if (isset($_GET[$name]))
return $_GET[$name];
else if (isset($_POST[$name]))
return $_POST[$name];
else if (isset($_COOKIE[$name]))
return $_COOKIE[$name];
else
return "";
}
//Database Connection
function connectDB (){
define('DB_HOST', 'localhost');
define('DB_NAME', 'userinfo');
define('DB_USER','root');
define('DB_PASSWORD','ohanajumba');
$con=mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD, DB_NAME) or die("Failed to connect to MySQL: " . mysql_error() );
return $con;
}
function logError($occured, $name, $line, $master, $url, $db){
$command="INSERT INTO errors (id, occured, name, url, line, master) VALUES (NULL, '$occured', '$name', '$url','$line', '$master')";
mysqli_query($db, $command) or die(mysql_error());
}
$db = connectDB();
$message = htmlentities(substr(urldecode(gpc("msg")),0,1024));
$url = htmlentities(substr(urldecode(gpc("url")),0,1024));
$line = htmlentities(substr(urldecode(gpc("line")),0,1024));
$master = htmlentities(substr(urldecode(gpc("master")),0,1024));
$date = date('Y-m-d G:i:s', time());
logError($date, $message, $line, $master, $url, $db);
mysqli_close($db);
Also, I have checked all the sent data through the request and all of them have been received properly by the script, any help would be appreciated.
I solved it , apparently I forgot to use mysqli_real_escape_string().

How can I return the path of a screenshot capture to a function and return via JSON to javascript?

I have a PHP script that invokes a casperjs script via exec function and this is working fine.
Is it possible to return the path where I saved a screenshot via exec as JSON?
My scripts are below:
PHP code:
// Execute to CasperJS via asynchronous process
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$target = $_POST['target'];
$filename = $_POST['file'];
$retorno = array()
try {
exec("{$casperjs_run} {$script} {$username} {$password} {$filename} 2>&1", $output);
} catch (Exception $e) {
$retorno['error404'] = "Desculpe! Não foi possivel acessar a página solicitada.";
}
// Return Data if success
// Retorna para front-end
if (empty($output)){
$retorno['success'] = $output;
echo json_encode($retorno);
return false;
} else {
$retorno['error'] = $output;
echo json_encode($retorno);
return false;
}
?>
CasperJS code:
casper.thenOpen(minhaoi, function myaccount() {
this.capture('pic2.png');
this.log('Acessando informações da conta, aguarde...');
if (!this.exists(('div.panel-horizontal'))) {
this.log(JSON.stringify("Não foi encontrado um plano colaborador, aguarde..."));
noDetails = this.captureSelector(filename + '.png', 'div.panel-horizontal', {quality: 100});
} else {
casper.waitForResource("Análise de Conta", function orderDetails(details) {
return details;
}, function onReceive() {
this.log('ScreenShot Begin');
myDetails = this.captureSelector(path_images + filename + '.png', '#content', { quality: 100 } );
this.log(' ScreenShot Done'); });
});
}
});
// Logout & Exit
casper.eachThen(oi_out, function () {
this.capture('pic3.png');
if (noDetails != "") {
return noDetails;
} else {
return myDetails;
}).run();
Here my JS code that receive the information from casperjs via JSON.
Javascript Code:
success: function(data) {
if (data.success) {
$('#retorno').html(data.success);
$('#imagem').attr('src', '/details/' + filename);
$('#resultado').show();
}
},
error: function(data) {
// check error
$('#retorno').attr("class='alert alert-danger' role='alert'");
$('#retorno').html(data.error);
}
In my mind filename should be the whole name of the screenshot like this, pi9rxw2fqlh.png plus the complete path too. And display the image in the browser.
What's wrong in my approach?
For this.log to actually print something, you need to set the logLevel to at least debug as it is the default log level. So either increase the log level casper.options.logLevel = 'debug'; or use this.echo instead of this.log.
It looks like you're using waitForResource wrong. Since there can't be resources with spaces in them, you might want to checkout waitForText under the assumption that the loaded resource adds that string to the DOM:
casper.waitForText("Análise de Conta", function onReceive() {
this.log('ScreenShot Begin');
myDetails = this.captureSelector(path_images + filename + '.png', '#content', { quality: 100 } );
this.log(' ScreenShot Done'); });
});
capture as well as captureSelector return the casper instance and not the image details. So you need to pass the filename.
Since you use php's exec with the output array, you can casper.echo the filename in question with a unique beginning string (here #noDetails#):
this.captureSelector(filename + '.png', 'div.panel-horizontal', {quality: 100});
this.echo("#noDetails#" + filename + ".png");
In the client javascript you can then iterate over the data.success or data.error arrays and extract the filename from the match line:
data.success.forEach(function(line){
if (line.indexOf("#noDetails#") === 0) {
var filename = line.split("#noDetails#")[1];
$('#imagem').attr('src', '/details/' + filename);
}
});
With this, you can completely remove the if block from the eachThen callback.
The other option is to set the specific screenshot variable and write the JSON object in the last line.
this.captureSelector(filename + '.png', 'div.panel-horizontal', {quality: 100});
noDetails = filename + ".png";
and at the end:
casper.eachThen(oi_out, function () {
this.capture('pic3.png');
if (noDetails != "") {
this.echo(JSON.stringify({filename:noDetails}));
} else {
this.echo(JSON.stringify({filename:myDetails}));
}
});
On the client side, you would need to only look in the last line of the array:
var obj = JSON.parse(data.success[data.success.length-1]);
$('#imagem').attr('src', '/details/' + obj.filename);

incorporate asynchronous javascript post requests into php class file

I've inherited a website with an obscure PHP framework called syndrome for which I can't find any documentation, but the problem I'm trying to solve should be fairly simple for a good PHP developer.
I am trying to make ajax requests from javascript to a php file to execute a particular function. The ajax request is simply:
loadNewImage = function(){
$.ajax({ url: '/app/library/Controller/Reel.php',
data: {action: 'test'},
type: 'post',
success: function(output) {
alert(output);
}
});
}
The current PHP file is structured like this:
<?php
class Controller_Reel extends BaseController_Web {
protected function defaultAction() {
parent::getPage($this->template, 'home');
$homepage = Homepage::getInstance()->getHomepage();
$this->template->title = 'Homepage';
$this->template->image = $homepage['asset_image'];
$this->template->center = array('reel');
$this->setResponse($this->template);
}
}
What I want to do is add to the file a check for post data. I'm not good with PHP, but I tried:
<?php
if(isset($_POST['action']) && !empty($_POST['action'])) {
echo 'TEST POST';
}
class Controller_Reel extends BaseController_Web {
protected function defaultAction() {
parent::getPage($this->template, 'home');
$homepage = Homepage::getInstance()->getHomepage();
$this->template->title = 'Homepage';
$this->template->image = $homepage['asset_image'];
$this->template->center = array('reel');
$this->setResponse($this->template);
}
}
I'm assuming that's maybe because the check for post data is not happening within the class itself, but I'm not exactly sure how to structure the code. Can anybody help straighten me out?
UPDATE: I found this inside a file called ControllerSite.php -> (of which baseController_Web is extended:
protected function respond() {
switch($this->response_type) {
case self::RESPONSE_PAGE:
// always try to make ie use the latest rendering engine
case self::RESPONSE_TEXT:
Helper_Request::respond($this->processed_response, Helper_Request::RESPONSE_PRINT, Config::$platform);
break;
case self::RESPONSE_JSON:
Helper_Request::respond($this->processed_response, Helper_Request::RESPONSE_JSON, Config::$platform);
break;
case self::RESPONSE_REDIR:
Helper_Request::respond($this->processed_response, Helper_Request::RESPONSE_REDIR, Config::$platform);
break;
case self::RESPONSE_CONTENT:
// TODO: we'll need to figure the out, but don't need to worry about it for now
break;
}
return $this;
}
and then in Controller.php (of which ControllerSite.php is extended), this:
final private function execute() {
$action = $this->getMethodName();
$is_ajax = Helper_Request::isAjax();
$data_type = strtolower(Helper_Request::setDefault($_SERVER['HTTP_ACCEPT'], ''));
if($is_ajax && preg_match('/\w+\/json|\w+\/javascript/i', $data_type) && method_exists($this, $action . 'JsonAction')) {
// it there was a ajax json request and the ajax json specific method exists, execute it
return $this->{$action . 'JsonAction'}();
}
return $this;
}
Try this:
class Controller_Reel extends BaseController_Web {
protected function defaultAction() {
parent::getPage($this->template, 'home');
$homepage = Homepage::getInstance()->getHomepage();
$this->template->title = 'Homepage';
$this->template->image = $homepage['asset_image'];
$this->template->center = array('reel');
if(isset($_POST['action']) && !empty($_POST['action'])) {
$reponse['success'] = true;
$response['responseVal'] = 'This is a test';
$this->setResponse($response);
} else {
$this->setResponse($this->template);
}
}
}
Try to make a class method named testAction:
protected function testAction() {
parent::getPage($this->template, 'home');
$homepage = Homepage::getInstance()->getHomepage();
$this->template->title = 'Homepage';
$this->template->image = $homepage['asset_image'];
$this->template->center = array('reel');
$this->setResponse($this->template);
}
In ajax request you are trying to send action parameter with test value and i suppose it is the framework's duty to call the related method named with 'test' .
This may hep.

Categories

Resources