Yii2 how to access POST data that's been sent using AJAX - php

I want to create a variable within my controller function that equals the POST value however I am unsure on how to access the POST value.
An answer would be great but any tips for debugging would be great too.
I have tried $_POST['save_id'] as well as $_POST[0]['save_id']
$('#save-file').click(function() {
var fileid = $(this).data('fileid');
$.ajax({
type: "POST",
url: "/files/save",
data: { 'save_id' : fileid },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//do something
console.log(fileid);
alert("working");
},
error: function (errormessage) {
//do something else
alert("not working");
}
});
});

for your url if the code is inside a PHP file i suggest you a proper path eg :
url: <?=Url::to(['/files/save']) ?>,
(Remenber of add use use yii\helpers\Url;)
If not a php refer to the absolute path properly
inside your FilesController in save Action
public function actionSave()
{
if (Yii::$app->request->isAjax) {
$data = Yii::$app->request->post();
//data: { 'save_id' : fileid },
$mySaveId = $data['save_id']
// your logic;
......
}
}

Related

Encapsulated the Ajax calls into a class and works odd when I'm using it to upload files

I've recently used lots of Ajax methods in one of my projects, since in every $.ajax call you have to write many of the same codes, like:
{
type:'POST', // Default value is 'GET'
beforeSend: function(xhr){
// Usually do some Page Loading Animation stuff here
},
error:function(){
// Handling the Exceptions here
}
}
So I've encapsulated the Ajax call into a class, called JAjax, like this :
(function ($) {
// More details, see: http://api.jquery.com/jquery.ajax/
var defaults = {
data: {},
url: '',
type: 'POST',
dataType: 'JSON',
isOverlay: true,
async: true,
cache: true,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
processData: true,
overlayTarget: $(document.body),
dealyClean: 500,
f_before: function () {},
f_done: function () { },
f_always: function () { },
f_fail: function (xhr) {
if (xhr.status !== 200) {
// Handling the Exceptions
}
}
};
function JAjax(_options) {
this.options = $.extend({}, defaults, _options);
this.execute();
}
function createOverLayer(options) {
// Create a page loading animation layer
}
JAjax.prototype = {
execute: function () {
var parent = this;
var response = $.ajax({
data: parent.options.data,
url: parent.options.url,
type: parent.options.type,
dataType: parent.options.dataType,
contentType: parent.options.contentType,
async: parent.options.async,
cache: parent.options.cache,
processData: parent.options.processData,
beforeSend: function (xhr) {
parent.options.f_before();
if (parent.options.isOverlay) {
createOverLayer(parent.options);
}
}
});
response.done(parent.options.f_done);
response.always(parent.options.f_always);
response.fail(parent.options.f_fail);
}
};
jQuery.extend({
jajax: function (_options) {
_options = _options || {};
if (typeof _options === 'object') {
return new JAjax(_options);
}
}
});
})(jQuery);
For most Ajax requests (GET, POST), it works fine. But when I use it to upload some files, The file will successfully upload to the server and back to me a filename(string) as an execution result. But somehow, it doesn't trigger the f_done function, below is how I use it to upload the files:
var url = '/ajax_common_file_upload';
var file_data = new FormData();
for (var i = 0; i < _files.length; i++) {
var file = _files[i];
file_data.append('input_files[]', file);
}
$.jajax({
url: url,
data: file_data,
cache: false,
contentType: false,
processData: false,
f_done: function (result) {
// Never to be executed :-(
alert('show me something, please!');
}
});
I spend days to try to figure it out why it doesn't 'SHOW ME SOMETHING' but all failed, will be very appreciated that someone can help me out and explain why the f_done() method cannot be triggered when I use it to upload files.
Update:
I made some screenshots for both JAjax and original $.ajax on Request Headers and merge them together like below:
I used the same parameters to make the request for both JAjax and $.ajax, but I don't know why they have a different Accept value!
ANYONE?
Still can not trigger the f_done() function!!! but since I can do the same thing at f_always(), I'm gonna skip this and moving on. I will keep this post open and always appreciate for any suggestions!

Reading a very simple ajax request in Laravel

I lately managed to get a simple ajax post to work but can't get any of the data in the controller :
Ajax :
function verify(event) {
var title = event.title;
var start = event.start.format("h:m");
$.ajax({
url: "/admin/timetable/verify",
headers: {
'X-CSRF-TOKEN': $('#crsf').val()
},
type: "post",
contentType: "application/json; charset=utf-8",
data: {type : 'hi',titles : title},
dataType: "json",
success: function(response){
if (response['state']==='0')
toastr.error('Are you the 6 fingered man?'+response['msg']);
if (response['state']==='1')
toastr.info('Are you the 6 fingered man?');
},
error : function(e){
console.log(e.responseText);
}
});
}
Controller :
$d = Request::all();
dd($d);
return response()->json(['state'=>'0','msg'=>$d['titles']],200);
I tried Request all, Input all, Input::json()->all() .. nothing works always null or empty array [] ! I'm just trying to read the data sent from the ajax form !
I faced this lately. The problem (I don't know why) was about Get and POST.
Just transform route to a GET, make the ajax type as GET, and try with a very simple Input::all.
public function verifyClassroom(){
$Data = Input::all();
dd($Data);
}
This is my tested code and it works
function verify(event) {
$.ajax({
url: "/test",
headers: {
'X-CSRF-TOKEN': $('#crsf').val()
},
type: "post",
data: {type : 'hi',titles : "title"},
success: function(data){
alert(data);
},
error : function(e){
console.log(e.responseText);
}
});
}
and in my route closure
Route::post('test', function(\Illuminate\Http\Request $request){
$type = ($request->input('type'));
return $type;//returns type->hi
});
in the php controller you need to have something like this.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class YourcontrollernameController extends Controller {
public function test(Request $request) {
echo $request->input('type');
echo '/';
echo $request->input('titles');
die;
}
}
you can access the type and title by $request->input('type') and $request->input('titles')
ALso try using get method and
in yourproject/routes/web.phpweb.php
Route::get('/test', 'YourcontrollernameController#test');

Pass input value to ajax get Laravel

I am fairly new to Laravel and ajax in general, what I am trying to implement is to pass the value of an input field through an ajax get request.
My request looks like this:
function getInfo() {
$.ajax({
url: "info",
dataType: "json"
}).success(function(data){
$('#result').append(JSON.stringify(data));
}).fail(function(){alert('Unable to fetch data!');;
});
}
$('#infoSubmit').click(getInfo);
I have setup a route for my function in laravel that works like this
public/info/Variable <--
When I add a variable after info/
I get the data for that variable (e.g profile name)
I need to pass this variable from an inputfield to ajax request to something like this:
url: "info/+$inputfieldVariable"
Change:
url: "info",
TO:
url: "info/" + $('input-field-selector').val(),
Not sure about the correctness of your JS code: Shouldn't you be using done instead of success?
JavaScript:
function getInfo() {
var myFieldsValue = {};
var $inputs = $("#myForm :input");
$inputs.each(function() {
myFieldsValue[this.name] = $(this).val();
});
$.ajax({
url: "info",
dataType: "json",
data: myFieldsValue,
type: "GET" // Even if its the default value... looks clearer
success: function(data){
$('#result').append(JSON.stringify(data));
},
error: function(){
alert('Unable to fetch data!');
}
});
return false;
}
$('#infoSubmit').click(getInfo);
Untested but should be something like that

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";

Categories