Symfony2 Passing ajax request data to a form rendering controller - javascript

I have a problem with a Symfony Form which I want to prefill based on which record is viewed beforehand. The intention is to create a means for changing the record data.
I navigate to the form page via javascript and send an ajax request to the same controller the form is rendered by.
This is part of the page used for viewing records:
<input type="button" id="changeRecord" value="change"/>
record id: <div id="recordID"> {{ record_id }} </div>
I access the record id through javascript/jQuery like this:
var CssSelectors = new Array(
"recordID"
);
function getCurrentRecordID() {
return parseInt($.trim($("#" + CssSelectors[0]).text()));
};
The button-code in javascript is the following:
$('#changeRecord').click(function () {
window.location.replace(Routing.generate(recordChangeRoute));
$.ajax({
url: Routing.generate(recordChangeAjaxRoute),
type: "POST",
data: {'recordID': getCurrentRecordID()}
});
// both Routes point to the same controller
// problem located here ???
The Symfony Controller Action is the following:
public function changePlasmidRecordAction(Request $request) {
$em = $this->getDoctrine()->getManager();
$recordHandle = $em->getRepository('DataBundle:RecordClass');
$AjaxRequest = Request::createFromGlobals();
$RecordID = $AjaxRequest->request->get('recordID');
$recordToUpdate = $recordHandle->findOneBy(array('id' => $RecordID));
$updateForm = $this->createForm(new RecordClassType(), $recordToUpdate);
$updateForm->handleRequest($request);
if ($updateForm->isValid()) {
$em->flush();
return this->redirect($this->generateUrl('route_showRecord'));
} else {
return $this->render('DataBundle:RecordClass:updateRecord.html. twig',
array(
'RecordID' => $RecordID,
'form' => $updateForm->createView()
));
}
}
What I am trying to achieve is:
view a record
go to prefilled form
make changes and save
Viewing records, creating the form, persisting the changes to the database - all work. What does not work is accessing the needed ID inside the controller.
I can access the ajax request data the way I try in an other controller action without problems.
How is the "Form Request" interfering? Or is it?
Do I have to use an Event Listener?
Any help is greatly appreciated, thanks in advance!

I fixed it by leaving the ajax stuff away and submitting the required data via GET. Like so:
$('#changeRecord').click(function () {
window.location.replace(Routing.generate(recordChangeRoute, {'recordID': getCurrentRecordID()}));
});
Thank you for your input, all the best.

Related

Last chance at jQuery AJAX Toggle

I posted this question ealier today, however I recieved a fix (thank you) that works great against my RequestBin endpoint for testing, however when submitting to my AJAX script, its a different story.
Problem: I cant submit my jQuery toggle values to my PHP AJAX script because there is no form name associated with the POST request (so db never updates). I proven this by making a HTML form with the field names and the database updated right away. However this is not the case with this JS toggle method.
jQuery code
$(document).ready(function() {
$('.switch').click(function() {
var $this = $(this).toggleClass("switchOn");
$.ajax({
type: "POST",
url: "https://--------.x.pipedream.net/",
data: {
value: $this.hasClass("switchOn") ? 'pagination' : 'infinite'
},
success: function(data) {
console.log(data);
}
});
});
});
HTML
<div class="wrapper-toggle" align="center">
<label>
<div class="switch"></div>
<div class="switch-label">Use <b>Paged</b> results instead (Current: <b>Infinite</b>)</div>
</label>
</div>
PHP AJAX script
if (array_key_exists('pagination', $_POST)) {
$stmt = $conn->prepare("UPDATE users SET browse_mode = 'pagination' WHERE user_id = 1");
//$stmt->bindParam(":user_id", $account->getId(), PDO::PARAM_INT);
$stmt->execute();
} else if (array_key_exists('infinite', $_POST)) {
$stmt = $conn->prepare("UPDATE users SET browse_mode = 'infinite' WHERE user_id = 1");
//$stmt->bindParam(":user_id", $account->getId(), PDO::PARAM_INT);
$stmt->execute();
}
I cant figure out how to assign a field name to this, as it is not a traditional post form. This is driving me nuts. So the previous solution was applying hasClass() and calling var $this outside of $ajax(), great (and RequestBin receives both requests), but when submitting to PHP its a dead end (no form names).
Given the code above fixed and revised twice, where do I even start without a form ??
We need:
name="pagination"
name="infinite"
But this toggle JS doesn't allow for this. prop() has been removed to get toggle submitting values over (just not my AJAX script).
Any solution appreciated. Thank you again.
You can set your values as Form Data. So the PHP Function will get it just like a traditional form submission:
$(document).ready(function() {
$('.switch').click(function() {
var $this = $(this).toggleClass("switchOn");
var formdata = new FormData();
$this.hasClass("switchOn") ? formdata.append('pagination', 'name') : formdata.append('infinite', 'name');
$.ajax({
type: "POST",
url: "https://--------.x.pipedream.net/",
data: formdata,
success: function(data) {
console.log(data);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
More info on JS Form Data: https://developer.mozilla.org/en-US/docs/Web/API/FormData

How to render view only after selection in yii2

I am rendering two views in my single view.
<?= $form->field($model, 't_type')->dropDownList([
'' => 'Please Select', 'Slab Based' => 'Slab Based',
'TOU Based' => 'TOU Based']) ?>
<div class="showSlab" id="slab" style="display: none">
<?php echo $this->render('_slabBased', [
'modelsTariffSlabs' => $modelsTariffSlabs,
]); ?>
</div>
<div class="showTou" id="tou" style="display: none">
<?php echo $this->render('_touBased', [
'modelsTouSlabs' => $modelsTouSlabs,
]); ?>
</div>
By default both div's are hidden but both of them are rendering. But I want to render the form only when I select option 'Slab Based' or TOU Based
JS
$('#mdctariff-t_type').on('change', function () {
if (this.value === 'Slab Based') {
$("#slab").show();
$("#tou").hide();
} else if (this.value === 'TOU Based') {
$("#tou").show();
$("#slab").hide();
} else {
$("#slab").hide();
$("#tou").hide();
}
});
Note: After rendering the form I am also saving it
Update 1
I have tried to render it via ajax
$url = Url::toRoute(['/mdctariff/_slabBased','modelsTariffSlabs'=>$modelsTariffSlabs]);
doGet('$url')
function doGet(url, params) {
params = params || {};
$.get(url, params, function(response) { // requesting url which in form
$('#slab').html(response); // getting response and pushing to element with id #response
});
}
Reference: How to render partial using AJAX? Laravel 5.2
When I selects an option I am not able to view the form. In my Network tab I am getting error Not Found (#404): Page not found.. The URL generated is http://localhost/mdc/backend/web/mdctariff/_slabBased
While pasting this URL at my browser I am getting the same error. I must be missing something that I don't know
How can render my view only when I select an option?
Any help would be highly appreciated.
In your URL
$url = Url::toRoute(['/mdctariff/_slabBased','modelsTariffSlabs'=>$modelsTariffSlabs]);
The first argument should be the proper existing route. But you have written it in the form of a directory, i.e. mdctafiff folder then _slabBased file.
What you need to do here is, you need to create an action method in the controller so that you can access it through route. Like MdctariffController and partialAction and then in the body of partialAction method you need to call the _slabBased view file. Futher you can also take reference here for Url::toRoute().

How to post a tweet using Codebird PHP from pop-up window

I am trying to allow visitors to my site to post a tweet with an image directly from the site. I am using Codebird PHP library to accomplish this. So far everything is working correctly, however there is no preview of the post before it gets posted to the user's account. Currently, it just posts directly to their account as soon as they click the button.
What I would like is to have it pop-up a small window where it will ask them to log in if they aren't logged in yet, or it will show a preview of the tweet and allow them to click the "Tweet" button if they are logged in like in this image:
Here's my PHP:
function tweet($message,$image) {
require_once('codebird.php');
\Codebird\Codebird::setConsumerKey("MYCONSUMERKEY", "MYCONSUMERSECRET");
$cb = \Codebird\Codebird::getInstance();
session_start();
if (! isset($_SESSION['oauth_token'])) {
// get the request token
$reply = $cb->oauth_requestToken([
'oauth_callback' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
]);
// store the token
$cb->setToken($reply->oauth_token, $reply->oauth_token_secret);
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
$_SESSION['oauth_verify'] = true;
// redirect to auth website
$auth_url = $cb->oauth_authorize();
header('Location: ' . $auth_url);
die();
} elseif (isset($_GET['oauth_verifier']) && isset($_SESSION['oauth_verify'])) {
// verify the token
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
unset($_SESSION['oauth_verify']);
// get the access token
$reply = $cb->oauth_accessToken([
'oauth_verifier' => $_GET['oauth_verifier']
]);
// store the token (which is different from the request token!)
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
// send to same URL, without oauth GET parameters
header('Location: ' . basename(__FILE__));
die();
}
// assign access token on each page load
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$reply = $cb->media_upload(array(
'media' => $image
));
$mediaID = $reply->media_id_string;
$params = array(
'status' => $message,
'media_ids' => $mediaID
);
$reply = $cb->statuses_update($params);
}
tweet("Tweet tweet","assets/tweet.jpg");
And here's my Javascript/HTML:
function postTweet() {
$.ajax({
type: "POST",
url: 'tweet.php',
data:{action:'call_this'},
success:function(html) {
alert('Success!');
}
});
}
<button class="download-share" onclick="postTweet()">Download and Share</button>
In the button click, you need another function that open the popup along with a tweet button.
Add the click event listener as postTweet to the new tweet button.
I created a sample snippet. Check it below.
To show the real time preview, you need to add the keyup event listener to the textarea which should copy it's value and add it as the innerHTML of the preview pane.
function openTweet(){
document.getElementsByClassName("preview")[0].style.display="";
document.getElementById("tweetPr").innerHTML = document.getElementById("tweet").value;
document.getElementById("tweet").addEventListener("keyup",
function(){
document.getElementById("tweetPr").innerHTML = document.getElementById("tweet").value;
});
document.getElementsByClassName("download-share")[0].style.display="none";
}
function postTweet() {
$.ajax({
type: "POST",
url: 'tweet.php',
data:{action:'call_this'},
success:function(html) {
alert('Success!');
}
});
}
<div style="display:none;" class="preview"><textarea id="tweet"> </textarea><div id="tweetPr"></div><button onclick="postTweet();">Tweet</button></div>
<button class="download-share" onclick="openTweet()">Download and Share</button>
First things first, you(codebird) are using the twitter API to post to twitter, which makes use of the statuses/update endpoint in the API. This call is a server to server call, ie from the server where your files are hosted to the twitter server.
https://dev.twitter.com/rest/reference/post/statuses/update
There are 2 possibilities i see for you to accomplish what you have in mind
-first would be to use twitters web intent system with which you can send the tweet as a query string which would bring up the popup provided you have included the twitter js files
https://dev.twitter.com/web/tweet-button/web-intent
-second if thats not really your style then you could try something like what #ceejayoz mentioned making a new window created by you recreating the necessary inputs as shown in the picture and follow the same procedure you have now
Now to your question, Since you have an image the web intent option will not work, but if its a link with an image( twitter cards ) then i think the twitter bots should be able to read through the page and show you a preview in the popup provided you have the right meta tags on the linked page
Try use the function window.open
https://www.w3schools.com/jsref/met_win_open.asp
function postTweet() {
$.ajax({
type: "POST",
url: 'tweet.php',
data:{action:'call_this'},
success:function() {
success = true
}
});
if(success)
{
window.open('tweet.php', "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400")
}
}

Update/Create ng-submit and service

I´m trying to use ng-submit to update/create new posts in database. I use this HTML.
<form ng-submit="savePost()">
<input ng-model="post.TASK">
<input ng-model="post.STATUS"">
<button type="submit"></button>
</form>
When submit, he return to controller who has this function. I use console.log(scope.post.task) to show if value update works, and it works but don´t know how insert multiples values in service.
$scope.savePost = function() {
console.log($scope.post.TASK);
//I send here ID but not sure if I can send multiples values
PostAPI.update($routeParams.id).success(function(data, status, headers, config) {
$scope.post = data;
});
}
})
I only get a ID to update.
this.update = function(data) {
return $http.put("ajax/updatePost.php?postID=" + data);
}
And this is is php file.
$conexion = new PDO("mysql:host=localhost;dbname=angularcode_task;charset=utf8", "root", "");
$postID = $_GET['postID'];
//WE NEED TASK AND STATUS HERE
$sql=$conexion->query("UPDATE tasks SET task='Buuu', status=2 WHERE id='$postID'");
$json = json_encode($sql->execute());
echo $json;
In a put request you must especify the data to update your resource, if you need to send the resource id, it could be sent by url or in the same recipe you send the data.
According to Angularjs docs for $http.put, you should be able to do such thing by sending an adition parameter to be the data sent for the PUT request like the below code:
$http.put(url, data, [config]); // config is optional
For Example, PostAPI should receive the post as parameter too:
// controller
PostAPI.update($routeParams.id, $scope.post).then ...
// PostApiService
this.update = function (postId, data) {
return $http.put("ajax/updatePost.php?postID=" + postId, data);
Also, if you had the post id inside the post object, you wouldn't need the postId param, only the post object and then you catch it inside the update method to build your url.

Saving changes to a dropdown box into a database in CakePHP

I am new to cake and mysql, and am trying to create a simple job tracking app. I want to have a dropdown box for each job with a list of the status' a job can be at. When a user changes the active item in the box I want to save this into the database.
Any help in how to handle this would be very much appreciated. Below is what I have tried so far:
How I create the set of forms in the view with the options taken from the enums in my database table:
<?php $id = count($jobs)-1; ?>
<?php for ($job = count($jobs)-1; $job >= 0; --$job): ?>
<tr>
<td>
<?php echo $this->Form->input('status'.(string)$id, array('type'=>'select', 'class' => 'statusSelect','label'=>'', 'options'=>$states, 'default'=>$jobs[$job]['Job']['Status'])); ?>
</td>
I am using a jquery script to set an on change listener for each dropdown and call an action in my controller:
$(".statusSelect").change(function(){
//Grab job number from the id of select box
var jobNo = parseInt($(this).attr('id').substring(6));
var value = $(this).val();
$.ajax({
type:"POST",
url:'http://localhost/projectManager/jobs',
data:{ 'id': jobNo,
'status':value},
success : function(data) {
alert(jobNo);// this alert works
},
error : function() {
//alert("false");
}
});
});
And I have this function in my controller:
public function changeState($id = null, $status = null) {
//I don't think the id and status are actually
//being placed as arguments to this function
//from my js script
}
Thank you!!!
You are POSTing to /projectManager/jobs, which corresponds to ProjectManagerController::jobs().
Your function is declared as public function changeState($id = null, $status = null). Assuming changeState(..) is a function within ProjectManagerController, this corresponds to /projectManager/changeState/$id/$status.
You need to switch the URL the AJAX is POSTing to. You can either do something like:
url:'http://localhost/projectManager/changeState/'+jobNo+'/'+value', remove the data {} and leave your function as is, or you can do
url:'http://localhost/projectManager/changeState', leave the data {}, change your function to changeState() and then use $this->request->data within changeState() to access the data.
I am guessing you have another function, jobs(), and that is why the AJAX is working properly and the alert is generating.

Categories