I'm trying to send the form data to a php script using axios.
Is the syntax of axios correct?
How can I view the data sent via the post method?
I just started programming in vuetify and php, so I need a little help
methods: {
formSubmit(e) {
e.preventDefault();
let currentObj = this;
this.axios.post('http://localhost/index.php/',{
name : this.name, user : this.username
})
.then(function (response) {
currentObj.output = response.data;
})
.catch(function (error) {
currentObj.output = error;
});
},
}
in the php file there's :
<?php
require_once 'limonade.php';
$data = $_POST;
dispatch('/api/', 'test1');
function test1()
{
return 'Hello';
}
run();
Your php only acts when it's a GET Call, limonade's dispatch() is for GET only.
In your php you are creating a GET endpoint on the /api/ url that will execute the test1 function. Meaning when you call /api via get, you will get Hello as answer.
if you want that to be POST (without touching your javascript) the php should be something like:
# '/' because you are calling to http://localhost/index.php/ it could be '/whatever' if you call http://localhost/whatever (assuming you have configured everythign as limonade recomends)
function test2()
dispatch_post('/', 'test2');
{
return 'Hello via post';
}
Related
I'm trying to create an app in AngularJS that aggregates data from multiple APIs. With some public APIs there are request limits and much of the data I want to pull is not updated very frequently, so only one request a month for a particular ID is necessary. To get past this, I've set up a Factory that first checks for a local file on the server, if it is not present, it then goes to the API and performs a GET request.
From there, once the request is complete, I want to save that file to the server with a name set by a field in the response.
I've found some examples using PHP with AngularJS but I'm not sure on how to save the JSON file with the dynamic name...or if this is even the best thing to do in order to avoid the request limits.
var apiUrl = 'https://example.com/api?userID=';
$http.get(apiUrl + $stateParams.userID).
success(function(data) {
$scope.content = data;
$scope.userID = data.userID
function(){
$http.post('saveJson.php', $scope.content).then(function() {
// log success
});
};
}).
error(function() {
// log error
});
PHP
<?php
$json = file_get_contents("php://input");
$file = fopen('/var/www/USERID.json','w+');
fwrite($file, $json);
fclose($file);
?>
If you do this in a service, and just call a method from a view button click, it would be more like this:
angular.module('app.services', [
])
.service('MyService', function ($http) {
var MyService = this;
this.aggregatedData = { content: [], filename: null };
this.apiUrl = 'https://example.com/api?userID=';
this.saveUrl = 'saveJson.php';
this.getData = function (url) {
return $http.get(url + $stateParams.userID).then(function (response) {
MyService.aggregatedData.content.push(response.data);
});
};
this.saveData = function (url, fileName) {
this.aggregatedData.filename = fileName;
return $http.post('saveJson.php', this.aggregatedData).then(function () {
// do something with the post response if desired
});
};
})
Then wire up buttons in your view to fetch and save by having the controller call the service methods.
This is on Internet Explorer only.
I have a factory that provides notifications for my app.
The input for those notifications is a file (qc.sta) that is created automatically by a third party software and is dropped in a specific folder.
Whenever that file exists, a new notification is added to the app.
My mechanism would be to get the data from that qc.sta file and then delete it after collecting the data.
To delete a file I need to execute a PHP that deletes the file, but this seems to have to be done inside a $http.get, so I end up with an $http.get inside another $http.get.
What happens is that the notifications (triggered on a $interval inside the controller) keep popping up continuously, despite the file being deleted.
My factory is as below:
myApp.factory("qcSTA", function ($http, $q) {
return {
apiPath: "data/qc.sta?rnd=" + new Date().getTime(), //randomizing request to prevent caching
getNotifications: function () {
//Creating a deferred object
var deferred = $q.defer();
//Calling Web API to fetch notifications
$http.get(this.apiPath, { headers: { 'Cache-Control': 'no-cache'} })
.success(function (response) {
//Passing data to deferred's resolve function on successful completion
//Does whatever needs to be done to the response before passing it on
function deleteFile() {
$http.get("deleteFile.php");
return false
};
deleteFile();
deferred.resolve(JSON.parse('{"item" : "' + response.itemNumber + '", "description" : "' + response.desc + '"}'));
})
.error(function () {
//Sending a friendly error message in case of failure
deferred.reject("An error occured while fetching items");
});
//Returning the promise object
return deferred.promise;
}
}
});
And my controller:
myApp.controller("notificationController", function ($scope, $location, $interval, $q, qcSTA) {
function getNotifications() {
qcSTA.getNotifications()
.then(function (data) {
$scope.notifications.push(data);
},
function (errorMessage) {
$scope.error = errorMessage
});
}
}
How can I ensure the notification only pops up once rather than going in circles?
Could this be cache related?
If I refresh the browser, it won't get more notifications, it's like it finally detects the qc.sta file isn't there anymore.
I use resource make crud, and in the create page, I have to add a preview page
I tried to use ajax post data to admin/article/previewform then in route action controller method previewform catch data and store in variable with redirect to new page preview show it ...
I have problem
1. Why it doesn't redirect to new page ?
2. Why in js console.log get Faild to load resource … statu?s of 500
3. I also try return Redirect::to('admin/article/previewshow'); in previewform then still not redirect to.
But get js console.log with template show.blade.phpthat is in resource show method call.. ??
How to solve it?
js
$.ajax({
url: 'previewform',
type: 'POST',
data: {data: data},
})
.done(function(response) {
console.log(response);
});
route
//.. prefix=>admin
Route::resource('article','AdminArticleController');
Route::post('admin/article/previewform', 'AdminArticlePreviewController#previewform');
Route::get('admin/article/preview', 'AdminArticlePreviewController#preview');
AdminArticlePreviewController
class AdminArticlePreviewController extends AdminController
{
public function preview()
{
$input = Input::get('data');
return Redirect::route('admin/article/previewshow');
}
public function previewshow()
{
// return View::make('admin.article.preview')->with('data', $data)
}
}
It is not possible to make redirection in this way. For ajax requests you need to catch "redirection command" from the server side script (PHP) and execute it in the JS.
Instead:
return Redirect::route('admin/article/previewshow');
you can use:
return Response::make('/redirect/url', 301)
then JS code:
.done(function(response) {
console.log(response);
});
can be replaced by something like:
.done(function(data, statusText, xhr) {
if(xhr.status == 301) {
window.location = data;
}
});
I have question about call to my module action via ajax.
I'd like call to class in my module via ajax. But best solution for me is call to clean class. Not extends Module.
I don't know hot can I make url without add article to database and add module to him.
I use JQuery instead mooTools but js framework is not important. Most important is call to php class by ajax.
I have ajax module. But if I call to ajax.php required is module id from tl_module table. I don't want use this table. (Ajax will be very often calling, I prefer to don't load all contao mechanism. It should be very fast).
Thanks in advance for answers.
I found the answer for Contao >3.x in a GitHub issuse(german)
At first do in your Front-end Template:
<script type="text/javascript">
var data = {};
data["REQUEST_TOKEN"] = "<?php echo REQUEST_TOKEN ?>";
$(document).ready(function(){
$("#trigger").click(function(event){
$.post(
'<?php echo \Contao\Environment::get('requestUri')?>',
data,
function(responseText) {
alert(responseText);
}
).fail(function( jqXhr, textStatus, errorThrown ){ console.log( errorThrown )});
event.preventDefault();
});
});</script>
Important is the
- data["REQUEST_TOKEN"] -> if you do not add it, the POST-request will not reach your module:
public function generate()
{
if ($_SERVER['REQUEST_METHOD']=="POST" && \Environment::get('isAjaxRequest')) {
$this->myGenerateAjax();
exit;
}
return parent::generate();
}
//do in frontend
protected function compile()
{
...
}
public function myGenerateAjax()
{
// Ajax Requests verarbeiten
if(\Environment::get('isAjaxRequest')) {
header('Content-Type: application/json; charset=UTF-8');
echo json_encode(array(1, 2, 3));
exit;
}
}
If you want to do the ajax via GET you do not need the reqest token but the jquery funktion $get();
I would suggest you to use Simple_Ajax extension.
In this case you dont need to use Database and you can do pretty much anything you can do normally with Jquery ajax calls.
It works with Contao 2.11 and you can call your php class with it.
I find it much easier to use than ajax.php .
You can get it from : https://contao.org/de/extension-list/view/simple_ajax.de.html
Copy SimpleAjax.php to Contao's root folder.
Go to [CONTAO ROOT FOLDER]/system/modules and create a php file like following :
class AjaxRequestClass extends System
{
public function AjaxRequestMethod()
{
if ($this->Input->post('type') == 'ajaxsimple' )
{
// DO YOUR STUFF HERE
exit; // YOU SHOULD exit; OTHERWISE YOU GET ERRORS
}
}
}
Create a folder called config with a php file like following ( You can hook you class to TL_HOOKS with class name - class method, simple_ajax will execute you method whenever a ajax call is made ):
$GLOBALS['TL_HOOKS']['simpleAjax'][] = array('AjaxRequestClass','AjaxRequestMethod'); // Klassenname - Methodenname
Now you can easily make ajax calls with simply posting data to SimpleAjax.php:
$.ajax({
type: "POST",
url: "SimpleAjax.php",
data: { type: "ajaxsimple" },
success: function(result)
{
//DO YOUR STUFF HERE
}
I have a loader in user panel which is waiting for a response from user's mobile device. Unfortunately i'm compeletly blank on how to get the request from mobile device, and update the page content real time.
right now the problem i have is i am sending data from view page to my Controller function through ajax .... then in Controller function i am sending some data which i get from the ajax function to the other function which is in utility class and then returning the result to the ajax function.... and whenever the i receive the response from the controller function then i am starting the loader/preloader/ajax spinner ... now after the i am sending a variable from android ... so after the android response comes i want to stop the loader ... so i dont know how to i call the ajax function specifically and the response from controller
there can be two ways to acheive this
1st either i call directly the javascript function from android and then grab the value .
2nd or i call the javascript function from controller and send the value in ajax function ..dont know if it is possible ...
my js function
function openPrompt()
{
var cancelled = true;
var lock='lock';
$.modal.prompt('Enter message :', function(value)
{
$.ajax({
type:"POST",
data:{value:value,lock:lock},
url:"/allsecure/api/lock/",
success : function(data) {
//start spinner
},
error : function() {
alert("error");
}
});
}, function()
{
});
};
Controller function
public function lock(){
if( $this->request->is('ajax') ) {
$message = $this->request->data('value');
$lock = $this->request->data('lock');
$this->loadModel('Userinfo');
$userid = $this->Auth->User('idUser');
$key = $this->Userinfo->getKey($userid);
$apiKey = "1234567890";
$resp = AllSecure::sendNotification($apiKey, array($key), array('message' => $lock, 'tickerText' =>$message));
echo $resp; //after this response i am starting the loader
}
}
function android(){
// here i am getting the variable from android
$json = $this->request->data('json');
$data = json_decode($json, TRUE);
openPrompt()//here i want to call the javascript function and want to send the value of android to the javascript
}
or there is any better approach to do this ???
If you want to execute client javascript from the server you can do similar thing as JSONP does. Where the response is JSON data wrap in javascript function that is executed in client.