Performing CRUD Operations in MongoDB Using PHP Application - javascript

I am a rookie PHP and MongoDB developer.
I have created a PHP web project with an HTML page that contains an 'Add' button. The name of the page is awards.html. The awards.html file contains its counterpart JavaScript file, awards.js. A code is executed in this js file when the Add button is clicked. This code sends an AJAX call to a PHP class elsewhere in the project named, example.php which contains code to execute a function called, connect() that is in an Awards.php file.
The source-code of my files is given as follows:
Awards.html
<div class = "divbottom">
<div id="divAddAward">
<button class="btn" onclick="onrequest();">Add</button>
</div>
</div>
awards.js
function onrequest() {
$("#divAddAward").load('example.php');
alert('Test');
$.post(
'example.php'
).success(function(resp) {
json = $.parseJSON(resp);
alert(json);
});
}
example.php
<?php
include 'Awards.php';
$class = new Awards();
$method = $class->connect();
echo json_encode($method);
Awards.php
<?php
require_once 'mongodb-library/libraries/Mongo_db.php';
include 'mongodb-library/libraries/Mongo_db.php';
class Awards extends Mongo_db
{
//put your code here
public function __construct()
{
parent::__construct();
}
public function connect()
{
$this->load();
//The following code is used for confirmation
$array = array(
$this->message => '1'
);
return $array;
}
public function create()
{
//Code to read
}
public function read()
{
//Code to read
}
public function update()
{
//Code to update
}
public function delete()
{
//Code to delete
}
}
The purpose of my project is to perform CRUD operations on my MongoDB database called, test. I am using the Codeigniter-MongoDB-Library to connect to this database. I have edited the mongodb.php library file accordingly to connect to my database. The config settings for this file are given as follows:
mongodb.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config['default']['mongo_hostbase'] = 'localhost:27017';
$config['default']['mongo_database'] = 'test';
$config['default']['mongo_username'] = '';
$config['default']['mongo_password'] = '';
$config['default']['mongo_persist'] = TRUE;
$config['default']['mongo_persist_key'] = 'ci_persist';
$config['default']['mongo_replica_set'] = FALSE;
$config['default']['mongo_query_safety'] = 'safe';
$config['default']['mongo_suppress_connect_error'] = TRUE;
$config['default']['mongo_host_db_flag'] = FALSE;
The problem here is that the connect function is not getting executed; in other words, I am not able to connect to my database successfully. How do I know this? Because on the awards.html page I am getting an output which reads, No direct script access allowed, which is coming from the mongo_db.php file (mind you not the mongodb.php file I have mentioned above).
Can anyone please tell me where exactly am I going wrong? Replies at the earliest will be highly appreciated. Thank you in advance.

Related

Pass data between two HTML pages (Google Apps Script)

I'm trying to pass var 'id' from the page 'a.html' to 'b.html'. The var content comes from 'code.gs' as below:
code.gs
function data(){
var id = 1;
return id;
}
Next, I get this var and I show it in 'a.html':
a.html
<?
var id = data();
?>
<h1><?= id ?></h1>
Go to B.html
By clicking 'Go to B.html', the system directs the user to there. I need to bring the same value of var 'id' from the page 'a.html' to 'b.html'.
Ps: searching for a little, I saw that there's a kind to send this var by the command 'localStorage', but it's not working for me. :(
Can anybody help me?
Use localstorage
a.html
localStorage.setItem('id',1)
b.html
var id = localStorage.getItem('id')
the other way is to put it in a js file and import it in both html
Storing & Retrieving html data on the server
Client Side JavaScript:
<script>
function saveId(v) {
google.script.run.saveKeyValue({key:'id',value:v});
}
function getId() {
google.script.run
.withSuccessHandler(function(v){
alert('The value is ' + v );
})
.getKeyValue('id');
}
</script>
Server Side Google Apps Script:
function saveKeyValue(obj) {
PropertiesService.getScriptProperties().setProperty(obj.key,obj.value);
}
function getKeyValue(key) {
return PropertiesService.getScriptProperties().getProperty(key);
}
You could also replace PropertiesService with CacheService.
Client To Server Communications
Properties Service

set session in codeigniter using javascript

So I want to store the session in jquery. export_type is storing all the ids which is checked via checkbox I want to store all those ids in the session. Following is my code , But I have Uncaught SyntaxError: Invalid or unexpected token error. Any help will be appreciated. thanks in advance.
$("#export").click(function () {
var id = [];
$(':checkbox:checked').each(function (i) {
id[i] = $(this).val();
});
var export_type = id;
var set_session = "<?php $this->session->set_userdata('export_type', export_type); ?>";
export_php();
});
Javascript cannot read PHP. What you will have to do is to have your script make a separate request to a CodeIgniter controller.
Javascript:
$.get("export/set_session/" + export_type, function (result) {
console.log(result);
})
PHP (application/controllers/Export.php):
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Export extends CI_Controller {
public function set_session($export_type)
{
$this->session->set_userdata('export_type', $export_type);
echo 'Session set!';
return;
}
}
if your above javascript code lies in the view file as inline javascript inside a script tag then it is should be fine but, if this code is inside in a different javascript file then it will not work.

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.

How to call javascript function in the index of a controller in codeigniter?

I'm trying to call a javascript function inside my controller to display a warning message in page if a verification I do in the index function of this controller is false.
Here is my code:
<?php
public function index() {
$this->load->model('uploads_m');
$this->load->helper('form');
$template_vars = Array();
$this->load->vars($template_vars);
$data = Array();
$data['currentUploadId'] = $this->uploads_m->get_lastUploadId();
$data['fileTypes'] = $this->uploads_m->getAllFileTypes();
$data['existingFiles'] = Array();
if (isset($data['currentUploadId'])) {
$data['existingFiles'] = $this->uploads_m->get_UploadedFilesFromUploadId($data['currentUploadId']);
}else {
// TODO create warning message to tell that uploadid was not generated
}
$this->load->view('include/header');
$this->load->view('upload_files', $data);
$this->load->view('include/footer');
}
?>
I have a JS function stored in an extern js file that I wanted to call in this TODO.
It should be called this way :
show_msg_xajax("warning", "System was unable to find an Upload ID");
Since the check condition is being done in the index() of the controller, I don't know how to call this js function.
if it was being invoked by an event in the view, I'd create an ajax method to execute this function. but how can I call the javascript function it in the index()?
I already checked this answer: Calling javascript function from controller codeigniter but it didn't help me.
The solution I found was to send the function directly to the footer of that page... so I added a new variable to a footer template I have (where I call my javascripts).
in the index function in the controller I did:
if (isset($data['currentUploadId'])) {
$data['existingFiles'] = $this->uploads_m->get_UploadedFilesFromUploadId($data['currentUploadId']);
} else {
// TODO criar alerta de erro no sistema que não gerou UPLOADID
$template_vars['foot_javascripts_inline'] = 'show_msg_xajax("error", "System was unable to find an Upload ID");';
}
and in my footer template I added:
if (isset($foot_javascripts_inline)) { ?>
<script> <?php echo $foot_javascripts_inline ?> </script>
}
Thanks anyway for the help
You need to add your file with JS function as a view:
$this->load->view('path-to-js-message');

Zend_Form Jquery & fileUploadErrorIniSize

Edit, I fixed it by changing my JS to:
$('.zend_form input:not([type="file"]), .zend_form textarea').each(function() {
data[$(this).attr('name')] = $(this).val();
});
Hello,
As I posted earlier, I followed a ZendCast that allowed you to use jQuery to detect and display to users problem with their form.
However, file fields always return: fileUploadErrorIniSize (File 'image_front_url' exceeds the defined ini size" even if the file is within size limits.
TPL For Forms:
<?php $this->headScript()->captureStart(); ?>
$(function() {
$('.zend_form input, .zend_form textarea').blur(function() {
var formElementId = ($(this).parent().prev().find('label').attr('for'));
doValidation(formElementId);
});
});
function doValidation(id) {
var url = '/<?php echo MODULE; ?>/json/validateform/form_name/<?php echo get_class($this->form); ?>';
var data = {};
$('.zend_form input, .zend_form textarea').each(function() {
data[$(this).attr('name')] = $(this).val();
});
$.post(url, data, function(resp) {
$('#'+id).parent().find('.errors').remove();
$('#'+id).parent().append(getErrorHtml(resp[id], id));
}, 'json');
};
function getErrorHtml(formErrors, id) {
var o = '';
if (formErrors != null) {
var o = '<ul id="errors-'+id+'" class="errors">';
for (errorKey in formErrors) {
o += '<li>'+formErrors[errorKey]+'</li>';
}
o += '</ul>';
}
return o;
}
<?php $this->headScript()->captureEnd(); ?>
<?php
if (is_object($this->form) && $this->form->getErrorMessages()) {
echo $this->partial('partials/errors.phtml', array('errors' => $this->form->getErrorMessages(), 'translate' => $this->translate));
}
?>
<?php if (isset($this->errorMsg)) { ?>
<p><?php echo $this->errorMsg; ?></p>
<?php } ?>
<?php echo $this->form; ?>
Which is directed to
<?php
class Administration_JsonController extends Zend_Controller_Action {
public function validateformAction() {
$form_name = $this->_getParam('form_name');
$form = new $form_name();
$data = $this->_getAllParams();
$form->isValidPartial($data);
$json = $form->getMessages();
$this->_helper->json($json);
}
}
Example of returned json:
{"name":{"isEmpty":"Value is required and can't be empty"},"name_url":{"isEmpty":"Value is required and can't be empty"},"image_site_url":{"fileUploadErrorIniSize":"File 'image_site_url' exceeds the defined ini size"},"image_url":{"fileUploadErrorIniSize":"File 'image_url' exceeds the defined ini size"},"image_front_url":{"fileUploadErrorIniSize":"File 'image_front_url' exceeds the defined ini size"},"image_back_url":{"fileUploadErrorIniSize":"File 'image_back_url' exceeds the defined ini size"}}
I noticed a few people had this issue and they said that isValidPartial fixes it, so I changed
$form->isValid($data);
to
$form->isValidPartial($data);
but it didn't fix this issue.
Any ideas?
The problem is that you can't treat file fields in the same manner as regular text fields.
When you call $('input').val(), you get an actual text value for the text field, but for the file field you get the file name - and not the file contents.
Then your script tries to validate your file name as a file and, apparently, fails. In order for file validator to succeed you need to pass actual file contents to the script.
So, basically, you need to upload a file asynchronously to the server to perform all the necessary validations.
Unfortunately, uploading files via Ajax is not quite a trivial thing to do. Your basic options are uploading files via iFrame or swfObject. You can take a look at the broad selection of plugins suitable for this purpose here.
My personal choice for asynchronous file upload would be file-uploader jQuery plugin.
Are you putting an Encrypt type on your form?
I have found two different forum posts about this, including a stack post:
odd Zend_Form_Element_File behavior
You need to add enctype="multipart/form-data" to your form tag.
Basically what is happening is the form is using its default "application/x-www-form-urlencoded" method of encryption before it is sent to the server. File uploading is not supported with this method.

Categories

Resources