Symfony2 Form Handling - javascript

I am using forms to process my entity data via ajax to an api-method.
My Type Class:
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add(
$builder->create('basicdata', 'form', array('virtual' => true))
->add('firstname', null, array('required' => true))
->add('lastname', null, array('required' => true))
);
$builder->add('contactdetails', new ContactdetailsType());
$builder->add('medialinks', new MedialinksType());
}
As u can see i seperate my form in 3 sections, one with basedata and 2 additional entities to keep contactdetails and medialinks.
In my JavaScript i have the following listener on the create button:
$('#player_form_create').on('click', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: remotePathPlayerCreate,
data: $('.form').serialize()
});
});
According to chromes developer tool the POST data look like following:
player_form[basicdata][firstname]:Harvey
player_form[basicdata][lastname]:Specter
player_form[contactdetails][email]:h.specter#pearson.com
player_form[medialinks][website]: http://
In my API action i wanna handle the request and save a new player record:
public function cpostAction()
{
$player = new Player();
$form = $this->createForm(new PlayersType(), $player);
$form->handleRequest($this->getRequest());
if($form->isValid()){
$em = $this->getDoctrine()->getManager();
$em->persist($player);
$em->persist($player->getContactdetails());
$em->persist($player->getMedialinks());
$em->flush();
return $this->redirectView(
$this->generateUrl(
'get_player',
array('id' => $player->getId())
),
Codes::HTTP_CREATED
);
}
return array(
'processedForm' => $form
);
}
As u might allready know, the problem happens while i want to handle the request. I guess $this->getRequest() does not contain the POST data information in the format needed by the request handler.
When i post data like this, i get a 500 with Expected argument of type \"Symfony\\Component\\HttpFoundation\\Request\", \"array\" given.
How can i achieve that my POST data is submited as an request object?

I ran into the same problem when building an app with Symfony on server side and AngularJS on client side. Handling the form this way worked:
$content = $this->get('request')->getContent();
if (!empty($content)) { $params = json_decode($content, true); }
else { // return an error or whatever }
$defaultOptions = array('csrf_protection' => false);
$form = $this->createFormBuilder(null, $defaultOptions)
->add('email', 'email', array(
'constraints' => new Constraints\Email(array('message' => 'emailError'))
))
->getForm();
$form->submit($params);
if ($form->isValid()) {
...
}
Of course here I'm not using a type to create the form like you but the result is the same. This assumes that the request payload is something like this:
{email: 'test#example.com'}

Ok i have found the solution: According to the page How to use the submit() Function to handle Form Submissions i now use $form->submit to submit my array-data to the form:
$form->submit($this->getRequest()->request->get($form->getName()));

Related

Parsing JSON data in WordPress

I want to get an Instagram user account info (follower, following and account name).
I used this endpoint:
https://www.instagram.com/{username}/?__a=1
When I add the username in the endpoint, it displays a JSON page that includes a lot of data such as follower, following and account name,
I use this code in WordPress for parsing the JSON code in functions.php and used a shortcode to a page.:
function insta_shortcode_func() {
$request = wp_remote_get('https://www.instagram.com/barkobco/?__a=1');
if (is_wp_error($request)) {
return false; // Bail early
}
$body = wp_remote_retrieve_body($request);
$data = json_decode($body);
return $data -> { 'count'};
}
add_shortcode('count_of_followers', 'insta_shortcode_func');
But nothing is displayed, I want to display follower, following and account name data.
You need to return this to get the followers
return $data->graphql->user->edge_followed_by->count;
Here is the full code
function insta_shortcode_func()
{
$request = wp_remote_get('https://www.instagram.com/barkobco/?__a=1');
if (is_wp_error($request)) {
return false; // Bail early
}
$body = wp_remote_retrieve_body($request);
$data = json_decode($body);
return $data->graphql->user->edge_followed_by->count;
}
add_shortcode('count_of_followers', 'insta_shortcode_func');
I think it will help you

Can't show data in javascript console

I have a registration form in my Laravel project. I submit that registration form data to laravel controller using ajax from javascript. After successfully stored those registration data in database I return the insertedID from controller to javascript and use console.log() function to show that id. In my javascript, console.log() shows that id and auto disappear after half mili second. But I don't want it to disappear.
Here is my js code
var name = $('#reg_name').val(); //reg_name is the id of the input field
var email = $('#reg_email').val(); //reg_email is the id of the input field
$.get( 'signup', {'name': name, 'email': email,'_token':$('input[name=_token]').val()}, function( data )
{
//Here 'signup' is my route name
console.log(data);
});
Here is my controller function
public function signup(RegistrationFormValidation $request)
{
$data = new User();
$data->name = $request->name;
$data->email = $request->email;
$data->save();
$lastInsertedId = $data->id;
if($lastInsertedId > 0)
{
return $lastInsertedId;
}
else
{
return 0;
}
}
Here I concise my code.
What's the problem in my javascript ?
If you are loading a new page, the default behaviour of the Chrome Dev Tools is to clear the logs. You can enable the Preserve log checkbox at the top of the console to prevent this behaviour.
In other situations, the data emitted to the console is modified after the logging to reflect subsequent updates. To prevent this, one can log a JSON serialized version of the data:
console.log(JSON.stringify(data))
(but probably this is not your case).

Access $_POST data on a PayPal API returnURL

I have built a cart using localStorage and I'm using the PayPal PHP SDK to process the payment.
On clicking to pay by PayPal, via AJAX, I am posting $_POST the localStorage data (the cart) and form data (the user's details) to a PHP page where I have the PayPal API setup, which then grabs the $_POST data (to create the items, transaction, payment, redirectURLs) and on success it returns the approved URL to redirect to PayPal (using window.location.href, and this all works fine.
var formData = form.serialize();
var cartData = JSON.parse(localStorage.getItem('drfStorage'));
$.ajax({
url: rootURL + 'api/payment__paypal.php',
type: 'POST',
data: { formData: formData, cartData: cartData },
beforeSend: function() {
console.log('processing');
},
success: function(data) {
console.log('success!');
console.log(data);
window.location.href = data;
},
error: function(xhr,err) {
console.log('readyState: '+xhr.readyState+'\nstatus: '+xhr.status);
console.log('responseText: '+xhr.responseText);
}
});
Then my returnURL which is set as redirect__paypal.php?pp_success=true is visited, which if the $_GET request is 'success' then it validates and takes the payment.
This all works well up until this point. The next stage is that I want to send an email receipt to the user containing some of the data from the localStorage HOWEVER the issue is that on this returnURL there's no longer the localStorage stored in the $_POST request. I could obviously pass all this information as a $_GET request but don't really want this information in the URL (?email=&address=&order=) etc.
Is there any way or advice you can see me being able to access the localStorage OR $_POST data before it went off to PayPal on the returnURL?
Below is what is currently contained within my redirect__paypal.php to aid with explanation.
use PayPal\Api\Payment;
use PayPal\Api\PaymentExecution;
// Require relevent libraries
require_once('./sendgrid/sendgrid-php.php');
require_once('./api__paypal.php');
// SendGrid API init
$sgAPIKey = "REMOVED FROM EXAMPLE";
if (isset($_GET['pp_success'])) {
$approved = $_GET['pp_success'] === 'true';
if ($approved) {
$payerID = $_GET['PayerID'];
$paymentID = $_GET['paymentId'];
$payment = Payment::get($paymentID, $api);
$execution = new PaymentExecution();
$execution->setPayerId($payerID);
$payment->execute($execution, $api);
// Set email confirmation settings
$email_admin = 'REMOVED FROM EXAMPLE'; // Client
$email_customer = 'REMOVED FROM EXAMPLE';
$email_admin_subject = 'You have a new order from Testing McTest via PayPal';
$email_admin_customer = 'Your Testing McTest order';
ob_start();
require_once './confirmation__email--admin.php';
$email_admin_body = ob_get_contents();
ob_end_clean();
ob_start();
require_once './confirmation__email--customer.php';
$email_customer_body = ob_get_contents();
ob_end_clean();
// SendGrid init
function send_email($from_email, $to_email, $subject, $body/*, $attachments*/) {
global $sgAPIKey;
$from = new SendGrid\Email(null, $from_email);
$to = new SendGrid\Email(null, $to_email);
$content = new SendGrid\Content("text/html", $body);
$mail = new SendGrid\Mail($from, $subject, $to, $content);
//foreach($attachments as $a) {
// $mail->addAttachment($a);
//}
$sg = new \SendGrid($sgAPIKey);
$response = $sg->client->mail()->send()->post($mail);
}
// Send confirmation to customer first before it clears the attachments
if ($email_customer) {
send_email($email_admin, $email_customer, $email_admin_customer, $email_customer_body/*, $attachments*/);
}
// Send to confirmation to admin
if ($email_admin) {
send_email($email_admin, $email_admin, $email_admin_subject, $email_admin_body/*, $attachments = []*/);
}
} else {
}
}
I think you need to save your data somewhere before your redirct to PayPal.
On a redirect, all $_POST fields are lost.
The easist way is to save all data in your session ($_SESSION)
You can grab it from there when you are back from PayPal ;)

Send with $post parameter in Angulars.js

I try to send a handsontable table data using $http POST with Angulars.js
The code below:
var $container = $("div#table");
var handsontable = $container.data('handsontable');
$scope.saveData = function() {
$http.post('save.php', {'data':handsontable.getData()}).success(function(res,status) {
if (res.result === 'ok') {
console.log('Data saved');
}
else {
console.log('Save error');
}
});
}
But I get a 'Save error' with
Undefined index: data in <b>C:\xampp\htdocs\angular\save.php
I the development tool in Chrome I get Request payload of this form:
{"data":[[fdf,gsgg,gsg,null,null,null],[sgsg,sgg,sgg,ggs,null,null]]}
I changed parameters in $http.post to get it work but no solution,
Thank you to give some advices!!!
I finally found a solution in here : [How to retrieve Request Payload
Instead of retrieving the data in this way
$values=$_POST['data'];
I fetch in this way:
$request_body = file_get_contents('php://input');

Yii Ajax Form submit

I have a problem with my Yii Form-Submission via Ajax:
Everything worked fine on my local machine but on the Webserver I always get the error Alert...
The Ajax Error is thrown every time the function is called...
although the data is properly POST'ED and the function in the URL did what it should..
So basically everything works but the Ajax Error is thrown every time
SO here is my code:
function merge()
{
var productA = $('#Product_selected_product').val();
var productB = $('#product_dd').val();
<?php echo CHtml::ajax(
array(
'url'=>CController::createUrl('product/companyItems'),
'data'=>array('productA' => 'js:$(\'#Product_selected_product\').val()', 'productB' => 'js:$(\'#product_dd\').val()','checker' => 'erwin'),
'type'=>'post',
'dataType'=>'json',
'error'=>"function() { alert('ERROR'); }",
'success'=> "function(){window.location.href = '../product/'+productB+''}"
)
);
?>
return false;
}
The companyItems Action searches for entrys in a table with the ID of ProductA and replaces it with the ID of ProductB.
Controller Action : CompanyItems:
public function actionCompanyItems(){
if(isset($_POST['checker'])) {
$productA = $_POST['productA'];
$productB = $_POST['productB'];
$commandMerge = Yii::app()->db
->createCommand("UPDATE ebay SET product_id = :productB WHERE product_id=:productA")
->bindValues(array(':productB' => $productB ,':productA' => $productA))
->execute();
$commandDelete = Yii::app()->db
->createCommand("UPDATE product SET is_deleted = '1' WHERE id = :productA")
->bindValues(array(':productA' => $productA))
->execute();
}
I hope someone can help me....
Dave

Categories

Resources