$.post() data to Codeigniter 3 - javascript

I have an $.post() and i want receive the data into my controller, how could i do that?
jQuery
$.post($('#url').val() + "Dashboard/getApi", { name: "John", time: "2pm" })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
vvvvvvvvvvvvvvvvvvv this is my url vvvvvvvvvvvvvv
$('#url').val() + "Dashboard/getApi" = "http://127.0.0.1/M2MWare/Dashboard/getApi"
And this is my controller
function getApi()
{
$valores = $this->input->post();
// print_r($valores);
return json_encode($valores);
}
this returns me an empty array, i tried with different url, data and nothing why?

Codeigniter 3.1.0 running on WampServer.
The Dashboard Controller
<?php
defined('BASEPATH') OR exit( 'No direct script access allowed' );
class Dashboard extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$this->load->view('post_view');
}
function getApi() {
$valores = $this->input->post();
echo json_encode($valores);
}
}
The View post_view.php This is Very Bare Bones for simplicity.
<html lang="en">
<head>
<title>Post Me</title>
</head>
<body>
<form>
<input type="hidden" id="url" value="http://ci310tut.com/">
</form>
<script src="<?= base_url('assets/js/jquery.min.js'); ?>"></script>
<script>
$(document).ready(function () {
console.log('We should be seeing an alert popup');
$.post($('#url').val() + "Dashboard/getApi", {name: "John", time: "2pm"})
.done(function (data) {
alert("Data Loaded: " + data);
});
});
</script>
</body>
</html>
And from the above I get an alert screaming at me each time I perform a page refresh with the provided data being displayed.
So you might want to check the above against what you have.

Related

CAPTCHA invalid-input-response

I'm trying to create a CAPTHCA for my forms on a website, but it always gives back "invalid-input-response".
I have the following front code for my form with captcha:
<script src="https://www.google.com/recaptcha/enterprise.js" async defer></script>
<script>
var onloadCallback = function() {
grecaptcha.enterprise.render('html_element', {
'sitekey' : '<?php echo G_RECAPTCHA_SITE_KEY?>',
'callback' : function(response) {
if(response){
// success
}
},
'theme' : 'dark'
});
};
</script>
<form>
...
<div id="html_element"></div>
</form>
<script src="https://www.google.com/recaptcha/enterprise.js?onload=onloadCallback&render=explicit" async defer></script>
End the backend side:
if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
// error
return false;
}
$secretKey = G_RECAPTCHA_SECRET_KEY;
// post request to server
$url = 'https://www.google.com/recaptcha/api/siteverify'
. '?secret=' . urlencode($secretKey)
. '&response=' . urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response,true);
// should return JSON with success as true
if(!$responseKeys["success"]) {
var_dump($responseKeys);
}
and the output is:
array(2) { ["success"]=> bool(false) ["error-codes"]=> array(1) { [0]=> string(22) "invalid-input-response" } }
G_RECAPTCHA_SITE_KEY and G_RECAPTCHA_SECRET_KEY are defined correctly, i checked them several times.
Do you have any suggestions? Is there something wrong with the code, or is it maybe something wrong with how i set up my reCAPTCHA Enterprise account?
Thanks in advance!

Typeahead JS Autocomplete not working - can't find anything

I want to make a autocomplete function on my input with existing titles from database, but seems that doesn't work. I don't know what's the problem but when I try to write something, notting happens.
Here is my controller
public function search()
{
return view('search-me');
}
public function autocomplete(Request $request)
{
$data = Models::select("email")->where("email", "LIKE","%{$request->input("query")}%")->get();
return response()->json($data);
}
Here is my route
Route::get('search-me', array('as' => 'search', 'uses' => 'AdminNewsController#search'));
Route::get('autocomplete',array('as' => 'autocomplete', 'uses' => 'AdminNewsController#autocomplete'));
Here is my view
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.js"></script>
</head>
<body>
<div class="container">
<h1> test</h1>
<input type="text" class="typeahead form-control">
</div>
</body>
<script type="text/javascript">
var path = "{{ route('autocomplete') }}";
$('input.typeahead').typeahead({
source: function (query, process){
return $.get(path, { query: query}, function (data) {
return process(data);
});
}
});
</script>
</html>
I'm using Laravel 5.2 but I guess is working on mine too. Here is the tutorial : https://www.youtube.com/watch?v=3AiMsvobceY

Reuse Vue.js stored into the DB

I'm trying to build a simple website builder that allow users to save their generated html created with Vue component and see it at a certain URL.
Because of it I have to store and retrieve the html generated but I have some problems with retrieving of the code. Here is my step:
When user click "save" this function is fired, that select the portion of HTML that include the "website" built by the user:
saveBuilders: function () {
let pages = [];
let builders = $('[id*="builder-container-"]');
$.each(builders, function (key, builder) {
let singleElem = $(builder).attr('id');
pages.push(clearElement.html());
});
this.storeInDb(pages);
},
storeInDb: function (pagesList) {
axios.post("/landing-page/store", {
name: this.name,
description: this.description,
html: pagesList
})
.then(function (response) {
console.log('Cool');
})
.catch(function (error) {
console.log('ERROR', error.response);
});
},
The Axios request is handled by this function that store the html portion in DB
public function store(Request $request)
{
$data = $request->all();
$html = $data['html'];
$landingPage = new LandingPage();
$landingPage->name = $data['name'];
$landingPage->description = $data['description'];
$landingPage->user_id = Auth::user()->id;
$landingPage->html = json_encode($html);
try {
$landingPage->save();
return 'true';
} catch (exception $e) {
return $e;
}
}
Now when the user visit a certain URL, for keep thing simple suppose is example.it/website/0, this function is fired:
public function show($landing_id)
{
try {
$landingPage = LandingPage::where([
'id' => $landing_id,
'user_id' => Auth::user()->id
])->first();
} catch (\Exception $e) {
$landingPage = null;
}
if ($landingPage != null) {
//GET THE HTML
$page = json_decode($landingPage->html);
return view('landing_page.show')->with('page', $page)
} else {
abort(404, 'Error');
}
}
And this the blade where I'm trying to re-create the Vue.js environment
<body>
<span id="countdown"></span>
<div id="builder-pagina">
<builder>
{!! $page !!}}
</builder>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="{{asset('js/landing_page/app.js')}}"></script>
</body>
</html>
I thought that having the html generated by vue similar to something like that into the DB...
<div data-v-29b64d26="" >
<h1>This piece of code was stored into my DB</h1>
<div data-v-56f62f0a="">
</div>
</div>
...you could create everything working simply by pasting the code and by using the same js file used for compiling vue.js.
I've tried pass the entire code by props but is not working. Also tried with slot. Any suggestions?

how to disable Cache in a REST Tree in DOJO with a complete code to reproduce it

The following code shows a tree in Dojo using dojox.data.JsonRestStore with one node named Changing0 with children to be lazy loaded. the problem is in updating the tree by renaming the one node (Changing1, Changing2,...) without changing its reference number or id.
The question is the following: if it is a caching problem, how to disable caching.
Please note that on the log file we can see that the REST is functioning well but the name is unchanged on the tree. Even if we use refresh2() instead of refresh1() by deleting the whole tree and its data and recreating it. Maybe it is the $ref that is kept in javascript referencing since we do not change the id.
the code is the following:
reproducing_problem.php:
<?php
if(!isset($_SESSION))
{
session_start();
}
$_SESSION['keyA']=0;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Reproducing Cache Problem</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!--META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE"-->
<script type="text/javascript" src="../external/dojo/dojo.js" djConfig="parseOnLoad: true"></script>
<script type="text/javascript">
dojo.require('dojox.data.JsonRestStore');
dojo.require('dijit.Tree');
dojo.require("dijit.form.Button");
var prod= {
store: null,
model: null,
tree: null,
init: function() {
this.store = new dojox.data.JsonRestStore({
target: 'reproducing-REST.php',
labelAttribute: "name"
});
this.model = new dijit.tree.ForestStoreModel({
store: this.store,
deferItemLoadingUntilExpand: true,
rootId: "products",
rootLabel: "Products",
query: {queryOptions:{cache:false}},
childrenAttrs: ['children']
});
}
};
function refresh1() {
tree=prod.tree
tree._itemNodesMap = {};
tree.rootNode.state = "UNCHECKED";
tree.model.root.children = null;
if (tree.rootNode) {
tree.rootNode.destroyRecursive();
}
tree._load();
}
function refresh2() {
delete prod.tree;
delete prod.model;
delete prod.store;
dijit.byId('products_tree').destroy(true);
prod.init();
prod.tree = new dijit.Tree({
model: prod.model,
query: {queryOptions:{preventCache:true}},
persist: false
}, 'products_tree');
prod.tree.startup();
}
dojo.addOnLoad(function() {
prod.init();
//prod.store.fetch({queryOptions:{cache:false}});
prod.tree = new dijit.Tree({
model: prod.model,
//query: {queryOptions:{cache:false}},
persist: false
}, 'products_tree');
prod.tree.startup();
});
</script>
<style type="text/css">
#import "../external/dijit/themes/soria/soria.css";
#import "../external/dojo/resources/dojo.css";
</style>
</head>
<body class="soria">
<div dojoType="dijit.form.Button">
Change name and refresh
<script type="dojo/event" event="onClick">
refresh1();
</script>
</div>
<div id="products_tree"></div>
<div id="notes">notes</div>
</body>
</html>
reproducing-REST.php:
<?php
if(!isset($_SESSION))
{
session_start();
}
$keyA=$_SESSION['keyA'];
$_SESSION['keyA']=$keyA+1;
if (array_key_exists('PATH_INFO', $_SERVER)) {
$arr = null;
$resource = $_SERVER['PATH_INFO'];
$method = $_SERVER['REQUEST_METHOD'];
error_log(" resource: ".$resource." \n",3,"mylogfile.txt");
if ($method == 'GET') {
if ($resource=='/'){
$arr=array();
$sameref='1234';
$name="Changing".$keyA;
error_log(" name: ".$name." \n",3,"mylogfile.txt");
array_push($arr,array('$ref' => $sameref, 'name' => $name, 'children' => true));
}
else{
$aProduct = ltrim($resource, '/');
$arr=array();
$name="exploding";
$child='2345';
array_push($arr,array('name' => $name,'idq' => $child));
$arr=array('idp' => $aProduct, 'name' => $name, 'children' => $arr);
}
$status = 'HTTP/1.1 200 OK';
}
header($status);
echo json_encode($arr);
}
?>
thank you

Can we get data in aspx.cs page from Angular controller?

I have a project which contains all plain html pages with angularJS and one .aspx page. I need some data in list/json format in my aspx page's code behind from angular controller. Can this be done ? If yes, please guide.
I'm new to angular, please be kind.
Scenario is I want to download the current html page as pdf. I found jspdf but for some reason it is not working in IE, works in chrome.
So, I am putting a workaround where I can do this with aspx page, I just need data there.
//Download PDF
$scope.PDFDownload = function () {
window.open('ReportPage.aspx');
//need to send list/json data to aspx code behind here.
}
I need some data in list/json format in my aspx page's code behind
from angular controller.
If you want to send/receive data to/from ASPX Web Form, you want to use WebMethod.
using System.Web.Script.Serialization;
namespace DemoWebForm
{
public partial class Default : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static string PostJson(string firstName, string lastName)
{
return new JavaScriptSerializer().Serialize(
"Hello, " + lastName + ", " + firstName + "!");
}
}
}
Usage
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DemoWebForm.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body ng-app="demoApp">
<form id="form1" runat="server" ng-controller="DemoController">
<pre>{{user}}</pre>
<button type="button" onclick="ajaxPostData();">Post Data Ajax</button>
<button type="button" ng-click="ngPostData()">Post Data Angular</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script type="text/javascript">
function ajaxPostData() {
var user = { firstName: "John", lastName: "Doe" };
$.ajax({
type: "POST",
url: '<%= ResolveUrl("~/default.aspx/postjson") %>',
data: JSON.stringify(user),
contentType: "application/json",
success: function (msg) {
console.log(msg.d);
}
});
}
var demoApp = angular.module('demoApp', [])
.controller('DemoController', function DemoController($scope, $http) {
$scope.user = { "firstName": "John", "lastName": "Doe" };
$scope.ngPostData = function () {
$http.post('<%= ResolveUrl("~/default.aspx/postjson") %>', $scope.user)
.then(function (result) {
console.log(result.data.d);
});
}
});
</script>
</form>
</body>
</html>
Screen shot

Categories