How to open new HTML.TWIG with ajax post method in symfony - ajax

I'll try to explain the situation, I want by calling AJAX post to be able to open new html.twig template and load all the data that was return to the callback of the ajax method. To be honest I have no idea how that can be achieved.
My controller
/**
* #Route("/Datasheet", name="DatasheetPage")
*
* #return JsonResponse|\Symfony\Component\HttpFoundation\Response
*/
public function QCCAction(Request $request)
{
if ($request->isXmlHttpRequest()) {
$part_family = $request->request->get('Part_Family');
$QCE = $request->request->get('QCE');
if($part_family == "DSUB")
{
$em =$this->getDoctrine()->getManager();
/** #var $repository \Doctrine\ORM\EntityManager */
$query = $em->createQuery(
'
SELECT
qce
FROM
AppBundle:QCE_SUBD qce
WHERE
qce.qCE LIKE :QCE
'
)->setParameters(array(
'QCE' => '%'.$QCE.'%',
));
$QCADS = $query->getArrayResult();
return new JsonResponse(json_encode($QCADS));
}
}
return $this->render('MyIndex/QCC_DATASHEETS.html.twig');
}
Here the found values are return to the post,
function generate_QCEs() {
$.post("/app_dev.php/Datasheet" ,
{
Part_Family: 'DSUB',
QCE : 'DSUB_PWR_5_P_-_CBL_QLH_4X1.0QMMTC'
} ,
function (data)
{
$('#QCE_HEADLINE').append('<h3>QCE:DSUB_PWR_5_P_-_CBL_QLH_4X1.0QMMTC</h3>');
var obj = JSON.parse(data);
// console.log(obj);
var Cable = obj[0].descriptionCables;
var Gender = obj[0].gender;
var partFamily =obj[0].partFamily;
var FamilyType = obj[0].familyType;
var Contacts = obj[0].numOfContacts;
MATING_QCEs(Cable, Gender, partFamily, FamilyType, Contacts);
}
);
}
So basically what I'm seeking is, how I could redirect to another twig and at the same time upload all the values to it.
for Example
$('#QCE_HEADLINE').append('<h3>QCE:DSUB_PWR_5_P_-_CBL_QLH_4X1.0QMMTC</h3>');
The AJAX call needs redirect me and update Datasheet.html.twig while my call is made from another twig template......

Related

Cannot use object of type Illuminate\Http\Response as array (Larravel/October CMS)

i am having this erro clicking in on the menu (Build) so i dont understand. someone can help me please? Why this is happining in this line below?
public function run($url = null)
{
$params = RouterHelper::segmentizeUrl($url);
// Handle NotFoundHttpExceptions in the backend (usually triggered by abort(404))
Event::listen('exception.beforeRender', function ($exception, $httpCode, $request) {
if (!$this->cmsHandling && $exception instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
return View::make('backend::404');
}
}, 1);
/*
* Database check
*/
if (!App::hasDatabase()) {
return Config::get('app.debug', false)
? Response::make(View::make('backend::no_database'), 200)
: $this->passToCmsController($url);
}
the erro start happining at this line---------->
$controllerRequest = $this->getRequestedController($url);
if (!is_null($controllerRequest)) {
return $controllerRequest['controller']->run(
$controllerRequest['action'],
$controllerRequest['params']
);
}
/*
* Fall back on Cms controller
*/
return $this->passToCmsController($url);
}
To make a View you don't need to make Response. Instead of
Response::make(View::make('backend::no_database'), 200)
use
return View::make('backend::no_database');
or this for custom page
return View::make('author.plugin::backend.file'); # htm is on views/backend/file.htm
By the way check above on same file, it has return View::make('backend::404');

Joomla router.php links displayed correctly but doesnt works joomla 3.7

I have a problem with router.php
I cannot found an error in public function parse(&$segments)
The url generated as i want but it doesn't work with sef correct
the parse function gets correctly the view and the id_tsi parameters but id_tsi parameter seems to be not working
Version of joomla 3.7
the url of the component looks like
www.ktopoverit.ru/index.php?option=com_helloworld&view=reestr_si&id_tsi=1
url with switched on sef looks like
www.ktopoverit.ru/poverka/reestr_si/1
$vars looks like
Array (
[view] => reestr_si
[id_tsi] => 1
)
and my router is
class helloworldRouter extends JComponentRouterBase
{
public function build(&$query)
{
$segments = array();
if (isset($query['view']))
{
$segments[] = $query['view'];
unset($query['view']);
}
if (isset($query['id_tsi']))
{
$segments[] = $query['id_tsi'];
unset($query['id_tsi']);
};
return $segments;
}
public function parse(&$segments)
{
$vars = array();
switch($segments[0])
{
case 'reestr_si':
$vars['view'] = 'reestr_si';
$id = explode(':', $segments[0]);
$vars['id_tsi'] = (int) $id[1];
break;
}
return $vars;
}
}
Since your build() method creates the right URLs, it makes sense to take it as the base for some assumptions.
$query contains max. two values, a view (string) and an id (int). One or both of them may be omitted.
So. independent from the actual number of segments, we can just assume that an int represents the id and a string (i.e., everything else) represents the view.
/**
* Parse URL
*
* This method is meant to transform the human readable URL back into
* query parameters. It is only executed when SEF mode is switched on.
*
* #param array &$segments The segments of the URL to parse.
*
* #return array The URL attributes to be used by the application.
*/
public function parse(&$segments)
{
while (!empty($segments))
{
$segment = array_pop($segments);
if (is_numeric($segment))
{
// It's the ID
$vars['id_tsi'] = (int) $segment;
}
else
{
// It's the view
$vars['view'] = $segment;
}
}
return $vars;
}

Angular $http PUT data not being received by Laravel 4 when using 'multipart/form-data'

Hallo :) I'm using a RESTful API built in Laravel 4 combined with Angular for heavy-lifting on the frontend.
The intention is to be able to create a new 'item' in the database by POSTing form data to an API (including a file). A user can also edit an item using PUT/PATCH in the same way.
For whatever reason, I can POST data (using $http) and that works fine, but if I use PUT, no data is received by Laravel. I've also tried PATCH. The data is definitely sent by $http as you can see here: http://paste.laravel.com/1alX/raw
I can tell that Laravel isn't getting/processing any data by echoing out the $input variable.
I'm not sure if this is an issue with Angular not sending data in the right way, or an Issue with Laravel not receiving/processing it correctly.
The Javascript (Somewhat simplified):
var formdata = new FormData();
// Unfortunately we cant just walk through the data with a FOR because the data is an object, not an array – We have to be explicit
// If data exists THEN add data to FormData ELSE do nothing
formdata.append('title', $scope.item.title);
formdata.append('description', $scope.item.description);
formdata.append('image', $scope.item.image);
formdata.append('tags', $scope.item.tags);
formdata.append('priority', $scope.item.priority);
edititem: function(formdata) {
// Edits a particular list
// id: the ID of the list to edit
// data: the edited list object
var promise = $http({
method: 'PUT',
url: 'http://mamp.local/api/v1/items/64',
headers: { 'Content-Type': undefined },
data: formdata,
transformRequest: angular.identity
})
.error(function(data, status, headers, config) {
debug(data, 'API FAIL - edit item');
return data;
})
.success(function(response){
debug(response.data, 'API Success - edit item');
return response.data;
});
return promise;
},
The PHP:
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
// Try and store the new List
$item = $this->itemRepo->updateitem($id, $this->user, Input::all());
// Lets check if we have any validation errors
if (count($item->errors()))
{
return Response::json(['errors' => $item->errors()->all()], 400);
}
// No errors
else
{
return Response::json(['id' => $item->id], 200);
}
}
/**
* Updates the item
*
* #param int $id the item ID
* #param User $user
* #param array $input
*
* #return item the item
*/
public function updateitem($id, User $user, $input)
{
// Grab the item
$item = $this->finditem($id, $user);
// Fill item with new input
$item->fill($input);
// Do we have an image?
if (Input::hasFile('image'))
{
// Handle resizing of the image
$item->image = $this->imageManipulator->resize($this->imageSizes, $this->imageDir, Input::file('image'));
}
// Try and save the item
if ($item->save())
{
// item saved, save the tags
$this->tagRepo->saveTags($input['tags'], $item, $user);
}
// Return the item
return $item;
}
I hope this is enough info, let me know if clarification is needed on anything.
Fankoo! :)
Why are you doing this: headers: { 'Content-Type': undefined } ?
It should be headers: { 'Content-Type': 'application/json' }
If Laravel doesn't see the Content-Type as application/json, it won't properly grab your json post.

how to get user profile from linked in using codeigniter

How do you get the user profile after you have finish verification in linkedin? I've been googling around and found some tutorials but none of them are working, or should I say I can't get them to work. Below is my controller.
function __construct(){
parent::__construct();
$this->config->load('linkedin');
$this->data['consumer_key'] = $this->config->item('api_key');
$this->data['consumer_secret'] = $this->config->item('secret_key');
$this->data['callback_url'] = site_url() . 'main/linkedin_display';
}
function linkedin_request(){
$this->load->library('linkedin', $this -> data);
$token = $this->linkedin->get_request_token();
$oauth_data = array(
'oauth_request_token' => $token['oauth_token'],
'oauth_request_token_secret' => $token['oauth_token_secret']
);
$this->session->set_userdata($oauth_data);
$request_link = $this->linkedin->get_authorize_URL($token);
header("Location: " . $request_link);
}
function linkedin_display{
// get user details(first name, email etc) here
}
Add the following function to your linkedin library, in order to get data
function getData($url, $access_token)
{
$request = OAuthRequest::from_consumer_and_token($this->consumer, $access_token, "GET", $url);
$request->sign_request($this->method, $this->consumer, $access_token);
$auth_header = $request->to_header("https://api.linkedin.com");
$response = $this->httpRequest($shareUrl, $auth_header, "GET");
return $response;
}
Then create a function in your controller as follows:
/**
* Fetch linkedin profile
*/
function myprofile()
{
$auth_data = $this->session->userdata('auth');
$this->load->library('linkedin', $this->data);
$status_response = $this->linkedin->getData('http://api.linkedin.com/v1/people/~', unserialize($auth_data['linked_in']));
print_r($status_response);
}
This should work for you.

Use same function for both 'add' and 'edit' in Codeigniter?

I want both these urls:
/admin/users/add
and
/admin/users/3/edit
to point to edit($user_id = 0) function in my users controller. The number 3 in the second url has to be passed to the $user_id parameter.
How can I do this in a smooth way?
By setting up a route in application/config/routes.php:
$route['admin/users/add'] = "users/edit";
$route['admin/users/(:num)/edit'] = "users/edit/$1";
If you want this to work for other controller too, you can do this:
$route['admin/(:any)/add'] = "$1/edit";
$route['admin/(:any)/(:num)/edit'] = "$1/edit/$2";
Or the same, using regular expressions:
$route['admin/([a-z]+)/add'] = "$1/edit";
$route['admin/([a-z]+)/(\d+)/edit'] = "$1/edit/$2";
As an alternative to separate your logic.
I generally have two controllers that both speak to the same view.
admin/user/add
admin/user/edit/3
Both point to the view
admin/user_form.php
Which then access a save_user() method when the form has been posted.
But as Mischa said, by setting up routes you can point pretty much any url to any method.
Can you do this
public function users ($type, $id = null)
{
if ($type === 'edit')
{
// do edit stuff
}
else
{
// ad add stuff
}
}
Sulotion:
function _remap($method)
{
$param_offset = 2;
// No method, point to...
if (!method_exists($this, $method))
{
if (is_numeric($method) || $method == 'add')
{
// Show single
$param_offset = 1;
$method = 'show';
}
else
{
// Index
$param_offset = 1;
$method = 'index';
}
}
// Since all we get is $method, load up everything else in the URI
$params = array_slice($this->uri->rsegment_array(), $param_offset);
// Call the determined method with all params
call_user_func_array(array($this, $method), $params);
}

Resources