Modify request object in Symfony 2 - ajax

i have the following code on my controller:
/**
*
* #Route("/{discountLevelItemId}/manage-product/update", name="discountlevel_manage_product_update", defaults={"_format"="json"} )
* #Method("POST")
*/
public function manageProductUpdateAction($discountLevelItemId, Request $request)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('CIInventoryBundle:DiscountLevelItem')->find($discountLevelItemId);
$form = $this->createForm(new DiscountLevelItemCollectionType(), $entity);
$form->bindRequest($request);
if ($form->isValid()) {
//remove items without discount type
foreach ($entity->getDiscountLevelItemProducts() as $item) {
if (!$item->getDiscountType()) {
$entity->getDiscountLevelItemProducts()->removeElement($item);
$em->remove($item);
}
}
$em->persist($entity);
$em->flush();
$responseData = array(
'status' => 'success',
'message' => 'Supplier product discounts successfully saved.'
);
} else {
$responseData = array(
'status' => 'error',
'form' => $this->renderView('CIInventoryBundle:DiscountLevel:manageProducts.html.twig', array(
'entity' => $entity,
'form' => $form->createView()
))
);
}
return new Response(json_encode($responseData), 200, array('Content-Type'=>'application/json'));
}
This action is called via ajax. Before calling this controller i filtered some data out like so:
initForm: function() {
//submit form function
var options = {
delegation: true,
dataType: "json",
beforeSubmit: function(arr, $form, options) {
//holds objects every four looping
var tempArray = new Array();
//holds changed objects that will only be submitted in the server.
var changedArray = new Array();
var found = false;
var idx = 1;
//get the token then remove from arr.
changedArray.push(arr.splice(arr.length-1,1)[0]);
for (var j = arr.length-1; j >= 0; j--) {
var obj = arr[j];
if ( viewCtrl.dliProductsChanged.indexOf(obj.value) != -1 ) {
found = true;
}
tempArray.push(arr[j]);
if(idx % 4 == 0) {
if (found == true) {
for(var i = 0; i < tempArray.length; i++){
changedArray.push(tempArray[i]);
}
found = false;
}
tempArray.length = 0;
}
idx++;
}
arr.length = 0;
for(var i = 0; i < changedArray.length; i++){
arr.push(changedArray[i]);
}
viewCtrl.dliProductsChanged.length = 0;
$form.find( ".submit-button" ).button( "loading" );
$form.find( ".discount-value, .trucking" ).addClass( "uneditable-input" );
$form.find( ".discount-type" ).attr( "readonly", true );
},
success: function(responseText, statusText, xhr, $form) {
if ( responseText.status == "success" ) {
viewCtrl.modal.modal( "hide" );
$.growl.notice({ title: "<strong>Saved</strong>", message: responseText.message, size: "large", duration: 5000, location: "br" });
viewCtrl.dliProductsChanged.length = 0;
} else {
viewCtrl.modal.find( ".modal-content" ).html( responseText.form );
}
$form.find( ".submit-button" ).button( "reset" );
}
};
$( "#manage-products-form" ).ajaxForm( options );
},
My question is, how can i repopulate the form with data i filtered out when the form gets invalid? The first thing came out of my mind is modifying the request object and then rebinding it again but i dont know how to implement that...
Any insights?
PS: I user JQUERY Form Plugin on form submission.
Thanks!

Related

Call to undefined function GuzzleHttp\\Psr7\\build_query()

I have searched online but could not get a solution. I know I have done some small mistakes. I generated my code with openapi-generator. I had a directory at nova-components root named as RegistroImprese I made another directory SevenData and moved all RegistroImprese into this new directory. I have gone through quite a lot of problems but fixed them. Until then my code was working fine. But now it's throwing an exception that query_build is undefined but this same function was working fine earlier. Nothing has helped me. Any help would be appreciated.
public function apiRegistroImpresePostRequest($request = null)
{
$resourcePath = '/api/RegistroImprese';
$formParams = [];
$queryParams = [];
$headerParams = [];
$httpBody = '';
$multipart = false;
if ($multipart) {
$headers = $this->headerSelector->selectHeadersForMultipart(
['application/json']
);
} else {
$headers = $this->headerSelector->selectHeaders(
['application/json'],
['application/json-patch+json', 'application/json', 'text/json', 'application/_*+json']
);
}
// for model (json/xml)
if (isset($request)) {
if ($headers['Content-Type'] === 'application/json') {
$httpBody = \GuzzleHttp\json_encode(ObjectSerializer::sanitizeForSerialization($request));
} else {
$httpBody = $request;
}
} elseif (count($formParams) > 0) {
if ($multipart) {
$multipartContents = [];
foreach ($formParams as $formParamName => $formParamValue) {
$formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
foreach ($formParamValueItems as $formParamValueItem) {
$multipartContents[] = [
'name' => $formParamName,
'contents' => $formParamValueItem
];
}
}
// for HTTP post (form)
$httpBody = new MultipartStream($multipartContents);
} elseif ($headers['Content-Type'] === 'application/json') {
$httpBody = \GuzzleHttp\json_encode($formParams);
} else {
// for HTTP post (form)
$httpBody = \GuzzleHttp\Psr7\build_query($formParams);
}
}
$defaultHeaders = [];
if ($this->config->getUserAgent()) {
$defaultHeaders['User-Agent'] = $this->config->getUserAgent();
}
$headers = array_merge(
$defaultHeaders,
$headerParams,
$headers
);
$query = \GuzzleHttp\Psr7\build_query($queryParams);
return new Request(
'POST',
$this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
$headers,
$httpBody
);
}
This problem was solved by using Query::build. After Guzzle 7.2 build_query()was deprecated.

Request input null in Laravel Controller

Hi I have a problem with getting the value of input using request in Controller, it's always return null. This is my code in jquery I am using Ajax to pass value to controller.
$('.generate').click(function(){
var dstart = $("#datepickerstart").val();
var dend = $("#datepickerend").val();
//var empid = $('#empid').val();
if($('#empid').val().length == 0)
{
empid = 0;
}
else{
empid = $('#empid').val();
}
var dStart = 0;
var dEnd = 0;
//alert(empid);
$.ajax({
type: "GET",
url: "{{route('manageattendance', '')}}"+"/"+empid,
data:$('#attendanceform').serialize(),
success: function(response)
{
console.log(response);
// alert("data caught");
$('.content').load('manageattendance/'+empid);
},
error: function(error)
{
console.log(error);
//alert("not caught ");
// alert($('#editForm').serialize());
}
});
//alert(dstart);
//alert(dend);
});
And this is my code in controller. I am trying to get the data using request but it returns null when I checked it. What would be the cause? Please help me. Thanks
public function index($id = 0,Request $request)
{
if($id == 0){
$current_date = date('Y-m-d');
$attendances = Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')-
>where('Date','=',$current_date)->get();
//$start = '2021-02-10';
//$end = '2021-02-11';
//$attendances =
Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')->whereBetween('Date',
[$start,$end])->get();
return view('manage.index',compact('attendances'));
}
else
{
$start = $request->input('datepickerstart');
$end = $request->input('datepickerend');
$newS = date('Y-m-d', strtotime($start));
$newE = date('Y-m-d', strtotime($end));
$sUser = User::select('name')->where('id','=',$id)->get();
//$attendances =
Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')->where('user_id','=',$id)-
>get();
$attendances =
Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')->whereBetween('Date',
[$start,$end])->get();
return view('manage.index',compact('attendances','sUser'));
// dd($start);
}
// return view('manage.index');
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
}
don't forget {{csrf_field }} in form and put id in input name is id
$('.generate').click(function(){
var dstart = $("#datepickerstart").val();
var dend = $("#datepickerend").val();
//var empid = $('#empid').val();
if($('#empid').val().length == 0)
{
empid = 0;
}
else{
empid = $('#empid').val();
}
var dStart = 0;
var dEnd = 0;
//alert(empid);
$.ajax({
type: "GET",
url: "{{route('manageattendance.update')}}"+"/"+empid,
data:$('#attendanceform').serialize(),
success: function(response)
{
console.log(response);
// alert("data caught");
$('.content').load('manageattendance/'+empid);
},
error: function(error)
{
console.log(error);
//alert("not caught ");
// alert($('#editForm').serialize());
}
});
//alert(dstart);
//alert(dend);
});
public function index(Request $request)
{
if(request->id == 0){
$current_date = date('Y-m-d');
$attendances = Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')-
>where('Date','=',$current_date)->get();
//$start = '2021-02-10';
//$end = '2021-02-11';
//$attendances =
Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')->whereBetween('Date',
[$start,$end])->get();
return view('manage.index',compact('attendances'));
}
else
{
$start = $request->input('datepickerstart');
$end = $request->input('datepickerend');
$newS = date('Y-m-d', strtotime($start));
$newE = date('Y-m-d', strtotime($end));
$sUser = User::select('name')->where('id','=',$request->id)->get();
$attendances =
Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')->where('user_id','=',$request->id)->whereBetween('Date',
[$start,$end])-
>get();
return view('manage.index',compact(['attendances'=>$attendances,'sUser'=>$sUser]));
// dd($start);
}
}

Doing live search in codeigniter via ajax , mongodb

This is my ajax code which fetches all data from data and display in the table, but when I input an alphabet in search-box, it again fetches complete data inside the table
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "<?php echo base_url() ?>Appconfig/get_masteradmin_data?query="+query,true);
xhttp.onload= function()
{
if (xhttp.status >=200 && xhttp.status <400)
{
var data= JSON.parse(xhttp.responseText);
var html = '';
var i;
for(i=0; i<data.length; i++){
html +='<tr>'+
'<td>'+data[i].full_name+'</td>'+
'<td>'+data[i].username+'</td>'+
'<td>'+data[i].designation+'</td>'+
'<td>'+data[i].department+'</td>'+
'<td>'+data[i].official_mobile_no+'</td>'+
'<td>'+data[i].official_email_id+'</td>'+
'<td>'+data[i].select_user_type+'</td>'+
'<td>'+data[i].permission+'</td>'+
'</tr>';
}
showdata.insertAdjacentHTML('beforeend',html);
}
else
{
console.log("Try again after some time");
}
};
xhttp.send();
}
$('#search').keyup(function(){
var search = $(this).val();
//console.log(search);
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
This is my model for fetching data from my mongodb collection.
public function get_masteradmin_data($query)
{
$mongo = new \MongoDB\Driver\Manager('mongodb://localhost:27017');
$query= '';
//$filter = ['full_name' => 'www'];
$regex = new MongoDB\BSON\Regex ($query);
$filter = ['full_name'=>$regex,];
$options =[
'projection' => [
'_id' => 0,
'full_name' => 1,
'username' => 1,
'designation'=> 1,
'department'=> 1,
'official_mobile_no'=> 1,
'official_email_id'=> 1,
'select_user_type'=> 1,
'permission'=> 1,
],
'sort' => [
'_id' => -1
],
];
$query = new MongoDB\Driver\Query($filter, $options);
//$readPreference = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
$result = $mongo->executeQuery('justrack_db.master_admin', $query);
$res = array();
foreach($result as $r)
{
$res[] = $r;
}
return json_encode($res,true);
//return $res;
}
This is my controller for displaying data. I am not sure, but I think there is some issue in my controller, as I tried to echo $query but it shows nothing. I am not able to understand how to fix this.
public function get_masteradmin_data()
{
$query = '';
$this->load->model('AppconfigModel');
$this->master_admin();
if($this->input->post('query'))
{
$query = $this->input->post('query');
}
$result= $this->AppconfigModel->get_masteradmin_data($query);
echo ($result);
}

Ajax with laravel Post returning

I am working with laravel and ajax. But when I register I see this error 302.
I know this may be a trivial question but I am just not able to get this ajax call to work.
Auth/RegisterController.php
protected function create(array $data, Request $request)
{
if ($request->hasFile('image')) {
$fileNameWithExt = $request->file('image')->getClientOriginalName();
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extention = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extention;
$path = $request->file('image')->storeAs('public/images', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
return User::create([
'firstname' => $data['firstـname'],
'lastname' => $data['lastـname'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'mobile' => $data['mobile'],
'nasional_code' => $data['national_code'],
'birthdate' => $data['birthـdate'],
'document' => $data['document'],
'educational' => $data['educational'],
'gender' => $data['gender'],
'side' => $data['side'],
$fileNameToStore => $data['image']
]);
}
My ajax is register.js file
How do I pass the "Accept'=>'application/json" in request when testing:
I want to add 'accept'=>'application/json' to my request header.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function scroll_to_class(element_class, removed_height) {
var scroll_to = $(element_class).offset().top - removed_height;
if($(window).scrollTop() != scroll_to) {
$('html, body').stop().animate({scrollTop: scroll_to}, 0);
}
}
function bar_progress(progress_line_object, direction) {
var number_of_steps = progress_line_object.data('number-of-steps');
var now_value = progress_line_object.data('now-value');
var new_value = 0;
if(direction == 'right') {
new_value = now_value + ( 100 / number_of_steps );
}
else if(direction == 'left') {
new_value = now_value - ( 100 / number_of_steps );
}
progress_line_object.attr('style', 'width: ' + new_value + '%;').data('now-value', new_value);
}
jQuery(document).ready(function() {
$('form fieldset:first').fadeIn('slow');
$('form input[type="text"], form input[type="password"], form textarea').on('focus', function() {
$(this).removeClass('input-error');
});
$('form .btn-next').on('click', function() {
var parent_fieldset = $(this).parents('fieldset');
var next_step = true;
var current_active_step = $(this).parents('form').find('.form-wizard.active');
var progress_line = $(this).parents('form').find('.progress-line');
parent_fieldset.find('input[type="text"], input[type="password"], input[type="email"], input[type="radio"]').each(function() {
if( $(this).val() == "" ) {
$(this).addClass('input-error');
next_step = false;
}
else {
$(this).removeClass('input-error');
}
});
parent_fieldset.find('input[type="checkbox"]').each(function() {
if( $(this).prop("checked") == false ) {
$('.form-check-label').css("color","red");
next_step = false;
}
else {
$('.form-check-label').css("color","black");
}
});
if( next_step ) {
parent_fieldset.fadeOut(400, function() {
current_active_step.removeClass('active').addClass('activated').next().addClass('active');
bar_progress(progress_line, 'right');
$(this).next().fadeIn();
scroll_to_class( $('form'), 20 );
});
}
});
// previous step
$('form .btn-previous').on('click', function() {
var current_active_step = $(this).parents('form').find('.form-wizard.active');
var progress_line = $(this).parents('form').find('.progress-line');
$(this).parents('fieldset').fadeOut(400, function() {
current_active_step.removeClass('active').prev().removeClass('activated').addClass('active');
bar_progress(progress_line, 'left');
$(this).prev().fadeIn();
scroll_to_class( $('form'), 20 );
});
});
$('form').on('submit', function(e) {
$(this).find('input[type="text"], input[type="password"], input[type="username"], input[type="email"], input[type="tel"], input[type="url"], textarea').each(function() {
if( $(this).val() == "" ) {
e.preventDefault();
$(this).addClass('input-error');
}
else {
$(this).removeClass('input-error');
}
});
});
});
Update your ajax header, according to this:
$.ajaxSetup({
headers: {
accepts: "application/json; charset=utf-8",
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
The possibilities of this issue is CSRF token and missing route.

How to change error 302 in laravel with ajax

I am working with laravel and ajax. But when I register I see this error 302.
I know this may be a trivial question but I am just not able to get this ajax call to work.
Auth/RegisterController.php
protected function create(array $data, Request $request)
{
if ($request->hasFile('image')) {
$fileNameWithExt = $request->file('image')->getClientOriginalName();
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extention = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extention;
$path = $request->file('image')->storeAs('public/images', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
return User::create([
'firstname' => $data['firstـname'],
'lastname' => $data['lastـname'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'mobile' => $data['mobile'],
'nasional_code' => $data['national_code'],
'birthdate' => $data['birthـdate'],
'document' => $data['document'],
'educational' => $data['educational'],
'gender' => $data['gender'],
'side' => $data['side'],
$fileNameToStore => $data['image']
]);
}
My ajax is register.js file
How do I pass the "Accept'=>'application/json" in request when testing:
I want to add 'accept'=>'application/json' to my request header.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function scroll_to_class(element_class, removed_height) {
var scroll_to = $(element_class).offset().top - removed_height;
if($(window).scrollTop() != scroll_to) {
$('html, body').stop().animate({scrollTop: scroll_to}, 0);
}
}
function bar_progress(progress_line_object, direction) {
var number_of_steps = progress_line_object.data('number-of-steps');
var now_value = progress_line_object.data('now-value');
var new_value = 0;
if(direction == 'right') {
new_value = now_value + ( 100 / number_of_steps );
}
else if(direction == 'left') {
new_value = now_value - ( 100 / number_of_steps );
}
progress_line_object.attr('style', 'width: ' + new_value + '%;').data('now-value', new_value);
}
jQuery(document).ready(function() {
$('form fieldset:first').fadeIn('slow');
$('form input[type="text"], form input[type="password"], form textarea').on('focus', function() {
$(this).removeClass('input-error');
});
$('form .btn-next').on('click', function() {
var parent_fieldset = $(this).parents('fieldset');
var next_step = true;
var current_active_step = $(this).parents('form').find('.form-wizard.active');
var progress_line = $(this).parents('form').find('.progress-line');
parent_fieldset.find('input[type="text"], input[type="password"], input[type="email"], input[type="radio"]').each(function() {
if( $(this).val() == "" ) {
$(this).addClass('input-error');
next_step = false;
}
else {
$(this).removeClass('input-error');
}
});
parent_fieldset.find('input[type="checkbox"]').each(function() {
if( $(this).prop("checked") == false ) {
$('.form-check-label').css("color","red");
next_step = false;
}
else {
$('.form-check-label').css("color","black");
}
});
if( next_step ) {
parent_fieldset.fadeOut(400, function() {
current_active_step.removeClass('active').addClass('activated').next().addClass('active');
bar_progress(progress_line, 'right');
$(this).next().fadeIn();
scroll_to_class( $('form'), 20 );
});
}
});
// previous step
$('form .btn-previous').on('click', function() {
var current_active_step = $(this).parents('form').find('.form-wizard.active');
var progress_line = $(this).parents('form').find('.progress-line');
$(this).parents('fieldset').fadeOut(400, function() {
current_active_step.removeClass('active').prev().removeClass('activated').addClass('active');
bar_progress(progress_line, 'left');
$(this).prev().fadeIn();
scroll_to_class( $('form'), 20 );
});
});
$('form').on('submit', function(e) {
$(this).find('input[type="text"], input[type="password"], input[type="username"], input[type="email"], input[type="tel"], input[type="url"], textarea').each(function() {
if( $(this).val() == "" ) {
e.preventDefault();
$(this).addClass('input-error');
}
else {
$(this).removeClass('input-error');
}
});
});
});

Resources