It seems to be an easy one but I am not able to manage an ajax post vor validation.
Via Ajax post I am sending data to an validation-action. so far so far so good.
the next step is returning a single value. Here is the problem. My action doesn't return the value.
Here is the action
public function solveEquationAction(){
$riddle = new Question();
$request = $this->getRequest()->getPost()->get('equation');
return $riddle->solveEquation($request);
}
Here is my ajax post
function validateAnswer(answer){
var equation = jQuery('#riddleAnswer').text();
$.ajax({
url : '/riddle/solveequation',
type: 'POST',
data: {'equation': equation},
success:function(data, textStatus, jqXHR)
{
console.log(data);
},
//...
});
}
I need the action to return only the solved equation so I can check it in the succes-part in my ajax post
Thanks in advance
You'd better use ViewJsonStrategy here.
public function indexAction()
{
$riddle = new Question();
$request = $this->getRequest()->getPost()->get('equation');
return new \Zend\View\Model\JsonModel(array(
'result' => $riddle->solveEquation($request),
'success' => true
));
}
Read more.
Related
I have this simple AJAX code to get the User Timezone whenever he is successfully login to the dashboard.
JS
<script type="text/javascript">
$(document).ready(function(){
'use strict';
/**
* Getting user current timezone offset
*/
var timezone_offset = new Date().getTimezoneOffset();
timezone_offset = timezone_offset == 0 ? 0 : -timezone_offset;
$.ajax({
type: "POST",
url: "<?php echo base_url('dashboard'); ?>",
data: {"timezone": timezone_offset},
cache: false,
success: function(data){
alert(data);
},
error: function(){
console.log('error');
}
});
});
</script>
Controller
public function index()
{
$data = $this->global_data->logged_user();
$data['page_title'] = 'Dashboard';
$data['page_directory'] = 'pages/dashboard';
$data['greeting'] = $this->global_helpers->greeting() . ' !';
$chart_data = array();
$order_history = $this->trade_history->chart_data();
foreach($order_history AS $d)
{
$chart_data[] = array(
'y' => $this->global_helpers->month_name($d->month) ."' ". $d->year,
'a' => $d->profit,
'b' => $d->loss
);
}
echo $_POST['timezone'];
$data['chart_data'] = json_encode($chart_data);
$this->load->view('template', $data);
}
But the problem is, when it's success why it's return the HTML header? not the data I wish to get?
What do I do wrong here? And I put this AJAX code in footer.php file. Sorry for this silly question but I just got stuck here.
I appreciated any kind of helps, Thanks!
Edited
Sorry for this silly post, I can't use that way, i just need to create another controller for handling any kind of AJAX value, so the problem will be fixed.
Well, you can't render HTML inside an alert anyway.
I see that you ended up solving this issue, but, FYI, if you ever need a controller to return HTML as data, use the third parameter on view method:
echo $this->load->view('template', $data, TRUE);
See more at Codeigniter docs :)
(1/1) ErrorException
Argument 2 passed to App\Http\Controllers\priceDetails::finalSubmit() must be an instance of Illuminate\Http\Request, none given
Error I'm getting while passing multiple parameters with controller function.
Ajax code:
<script type="text/javascript">
$(document).ready(function () {
$('#finalSubmit').click(function() {
var form1 = $('#priceform').serialize();
var form2 = $('#formdescription').serialize();
var form3 = $('#additionaldescription').serialize();
$.ajax({
url:"{{url('dbvalue')}}",
type: 'GET',
data: {form1: form1, form2: form2, form3: form3},
dataType:'json',
success:function(data){
alert(data);
}
});
});
});
</script>
Laravel route:
Route::get('dbvalue','priceDetails#finalSubmit');
Controller:
public function finalSubmit(Request $priceform,Request $formdescription)
{
$var1 = $this->addPriceDetails($priceform);
$var2 = $this->addProductDetails($formdescription);
$var3 = $this->addAdditionalInformation($additionaldescription);
$var4 = $this->addImages($imagesform);
echo("success");
}
This what I'm trying to give multiple form parameters in laravel controller function.
addPriceDetails fn:
public function addPriceDetails(Request $priceform)
{
$priceInfo = new priceInfo ;
$priceInfo->id=$this->getpriceDetailsId();
$priceInfo->SKUID=$priceform->input('skuid');
$priceInfo->deviceCategoryId=$priceform->input('dataId');
$id=$priceInfo->id;
$priceInfo->save();
return response()->json([
'SKUID' => $priceInfo->SKUID,
'sellingPrice' => $priceInfo->sellingPrice,
'id' =>$this->getpriceDetailsId()
]);
}
What you are attempting to do simply does not work. Just because you sent data of two form in your 1 ajax request does not mean laravel will interepret it as two request. That is simply not possible.
What you have done in your code is get get data from 3 forms and make a json object from them and sent that json object in 1 get request. You cannot send multiple request in 1 request. This is as fundamental as it gets.
The best way to get the result you want is to accept 1 request object in you controller and parse it to get data from multiple forms that you sent.
You need to make your function as
public function finalSubmit(Request $request)
{
$var1 = $this->addPriceDetails($request->form1);
$var2 = $this->addProductDetails($request->form2);
$var3 = $this->addAdditionalInformation($request->form3);
//$var4 = $this->addImages($imagesform);//you dont't have $imagesform
return response()->json(["response"=>"success"]);
}
Also change http verb from GET to POST
type: 'POST', //in ajax, it is good send bulk data in post not in get
In route
Route::post('/dbvalue','priceDetails#finalSubmit');
I have problem with processing the data on a form in two tables with Ajax for not updating screen. Sumfony2 redirects to process the data to a url in the end, as you can see in the following code:
public function createAction(Request $request)
{
$entity = new Users();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('users_new'));
}
return $this->render('BackendBundle:Userss:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
ajax call:
$('.form_student').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: Routing.generate('student_create'),
data: $(this).serialize(),
success: function(response) {
alert(response.result);
},
error: function (xhr, desc, err){
alert("error");
}
})
return false;
});
Is there any way that does not forward it to any URL and can use Ajax to load anything in that window?
You can check on the $request if is an ajax call with the isXmlHttpRequest method.
So you can do something like:
use Symfony\Component\HttpFoundation\JsonResponse;
....
if ($form->isValid()) {
// do something
if ($request->isXmlHttpRequest()) {
// generate a response for tour client, as example:
return new JsonResponse(array("result" => 1);
}
return $this->redirect($this->generateUrl('users_new'));
}
Hope this help
replace
return $this->redirect($this->generateUrl('users_new'));
by
return new JsonResponse($this->generateUrl('users_new'));
this will return the url instead of redirecting to it, you can then use javascript to load it.
I have an Ajax call that calls an action in the controller.
The Ajax call looks like this
$(document).on('click', '.editQuestionButton', function() {
var question_id = $(this).data('question');
console.log(question_id);
$.ajax({
type: "POST",
url: "/dashboard/form/AjaxEditQuestionForm/" + question_id + "",
success: function(data) {
$('#form-modal').html(data);
}
});
});
$(document).on('click', '.modal .fn-submit', function() {
$(this).closest('.modal').find('form').submit();
});
And this is the action.
/**
* #Route("/AjaxEditQuestionForm/{question}")
* #Template
* #ParamConverter("question", class="AppBundle:Question")
*/
public function ajaxEditQuestionFormAction(Request $request, $question)
{
$edit_question_form = $this->createForm(new AddQuestionType(), $question);
$edit_question_form->handleRequest($request);
if ($edit_question_form->isValid()) {
$em->flush();
return $this->redirectToRoute('app_form_create');
}
else{
die();
}
return array(
'question' => $question,
'editAjaxQuestionForm' => $edit_question_form->createView(),
);
}
The problem is that the action never returns the form but goes straight into checking if the form is valid.
I figure this has something to do with the $request but I'm not sure how to change this.
The action should first get the data from the Ajax call, return the form and if the form is submitted, check if the form is valid and flush the Question entity.
Any idea on how I should do this?
I need to pass json data to my Symfony Controller. My ajax function looks like this:
var data = '{"firstname":"John"}';
$.ajax({
type: "POST",
url: save_url, //path to controller action
data: {json:data},
success: function(response) {
// Do something
}
});
In my controller, I try to get my data through:
public function createAction(Request $request) {
$data = $this->getRequest()->get('firstname');
return $this->render('MyBundle:Counter:test.html.twig', array(
'data' => $data
));
Just to see if this works, I send $data to be echoed in a template. In Firebug I can see the data being sent and everything seems to work, but $data is empty and nothing is echoed. Where am I doing this wrong?
EDIT: When I check the response in Fireburg console, I see my data there, in place, but it never appears in the template. var_dump($data) tells that $data is null. So, it seems data is being sent but the controller ignores it.
As Marek noticed:
$this->getRequest()
already returns the request object, you're accessing the request property of the request, that doesn't add up. Either try:
$data = $this->request->get('json');
Or use:
$data = $this->getRequest()->get('json');
You can, of course assign the return value of $this->getRequest() to a variable, and call the get method on that var from there on end... anyway, here's my initial answer, it does contain some more tips, and considerations you may find useful:
You should be able to get the data this way, though AJAX requests + echoing in a template? That does sound a bit strange. I don't see you passing the $data variable to a $this->render call anywhere.
This is a copy-paste bit from a controller action in one of my projects. It works just fine there:
public function indexAction()
{
if (!$this->getRequest()->isXmlHttpRequest())
{//check if request is AJAX request, if not redirect
return $this->redirect(
$this->generateUrl('foo_bar_homepage')//changed this, of course
);
}
$id = $this->getRequest()->get('id',false);//works fine
However, I can't begin to grasp why you're doing this:
var data = '{"firstname":"John"}';
Why not simply go for:
$.ajax({
type: "POST",
url: url,//post how you get this URL please...
data: {firstname: 'John'},//jQ will sort this out for you
success: function(response)
{
console.log(response);
}
error: function()
{
console.log('an error occured');
console.log(arguments);//get debugging!
}
});
Then, in your controller you're able to:
$this->getRequest()->get('firstname');//it should be John
You could even pass {json:{firstname: 'john'}} as the data param to $.ajax, the only difference in your controller will be, that you have to do this:
$data = $this->getRequest()->get('json');
$firstName = $data['firstname'];
That should work just fine, unless there's somthing you're not telling us :)
RECAP:
This is what I'd write:
public function createAction()
{//no Request param in controller
if (!$this->getRequest()->isXmlHttpRequest())
{//no ajax request, no play...
$this->redirect(
$this->generateUrl('homepage_route')
);
}
$data = $this->getRequest()->get('firstname');
//return json response:
return new Response(json_encode(array('dataReceived' => $data));
//return rendered HTML page:
return $this->render('MyBundle:Counter:test.html.twig', array(
'data' => $data
));
}
Of course, then the JS code should read:
$.ajax({
type: "POST",
url: 'route/to/create'
data: {firstname:'John'},
success: function(response)
{
console.log(response);
}
});
I have tested this, and I see no reason why this shouldn't work. It works just fine for me...
Please note this was #EliasVanOotegem original example but there are some obvious steps missing
in the controller i'm reading a few replies as in "I cannot see how this works as i'm getting null" this is because your not correctly keying your object.
i.e.
var data = { name : 'john' };
$.ajax({
type: "POST",
url: url,//post how you get this URL please...
data: {json : data},//jQ will sort this out for you
success: function(response)
{
console.log(response);
}
error: function()
{
console.log('an error occured');
console.log(arguments);//get debugging!
}
});
as you can now see accessing the requerst object like
$request->get('json');
refers to the post key for the json data
Is the content what you're trying to retrieve, neither params nor headers.
Try:
$request->getContent();
In your case $request->request->get('json') should do.