How to pass hidden field value via ajax to codeigniter controller - javascript

I have a view file which contains a button (link):
<a href id="savebutton" class="btn btn-warning">Save</a>
Somewhere else in this view I have also declared some hidden fields in a form that contain my userid and vacancyid.
echo form_input(dataHiddenArray('userid', $this->auth_user_id));
echo form_input(dataHiddenArray('vacancyid', $vacancydetails[0]->vacancy_id));
These hidden fields translate to:
<input type="hidden" value="2" class="userid">
<input type="hidden" value="1" class="vacancyid">
Now I want to be able to send these values to my controller (via AJAX) so that I can insert them in my database.
My JS file looks like this:
$(function() {
var postData = {
"userid" : $("input.userid").val(),
"vacancyid" : $("input.vacancyid").val()
};
btnSave = $('#savebutton'),
ajaxOptions = {
cache: false,
type: 'POST',
url: "<?php echo base_url();?>dashboard/vacancy/saveVacancy",
contentType: 'application/json',
dataType: 'text'
};
btnSave.click(function (ev) {
var options = $.extend({}, ajaxOptions, {
//data : $(this).closest('form').serialize()
data: postData
});
ev.preventDefault();
// ajax done & fail
$.ajax(options).done(function(data) {
alert(data); // plausible [Object object]
//alert(data[0]); // plausible data
console.log(data); // debug as an object
}).fail(function (xhr, status, error) {
console.warn(xhr);
console.warn(status);
console.warn(error);
});
});
And my controller looks like this (it is not doing much because it doesn't return anything):
public function saveVacancy() {
//$this->load->model('user/usersavedvacancies_model');
/*$data = array(
'userid' => $this->input->post('userid'),
'vacancyid'=>$this->input->post('vacancyid')
);*/
echo $this->input->post('userid');
}

Minor changes to javascript
$(function () {
var postData = {
"userid": $("input.userid").val(),
"vacancyid": $("input.vacancyid").val()
};
btnSave = $('#savebutton'),
ajaxOptions = {
type: 'POST',
url: "<?php echo base_url('dashboard/vacancy/saveVacancy);?>",
dataType: 'json'
};
btnSave.click(function (ev) {
var options = $.extend({}, ajaxOptions, {
//data : $(this).closest('form').serialize()
data: postData
});
ev.preventDefault();
// ajax done & fail
$.ajax(options).done(function (data) {
console.log(data); // debug as an object
if (data.result === 'success') {
alert("Yeah, it saved userid " + data.userid + " to vacancy id " + data.vacancyid);
}
}).fail(function (xhr, status, error) {
console.warn(xhr);
console.warn(status);
console.warn(error);
});
});
});
In the controller
public function saveVacancy()
{
//assigning a more useable object name to the model during load
$this->load->model('user/usersavedvacancies_model', 'save_vacancy');
$data = array(
'userid' => $this->input->post('userid'),
'vacancyid' => $this->input->post('vacancyid')
);
//send data to model and model returns true or false for success or failure
$saved = $this->save_vacancy->doSaveId($data); //yes, I made up the method, change it
$result = $saved ? "success" : "failed";
echo json_encode(array('result' => $result, 'userid' => $data['userid'], 'vacancyid' => $data['vacancyid']));
}

You need to understand that $.ajax takes two methods i.e GET and POST and from the documentation you can see that default method is GET so Since you have not defined method as GET/POST probably the method is taken GET so first change define ajax method to POST as well as you need to be clear about dataType of ajax it may be one of JSON/html and default is json.
$.ajax({
method: "POST",
url: url,
data: data,
dataType:'html'
});
I guess this helped you can learn detail from
Learn more.

Related

Laravel 6 Error - Undefined property: App\Http\Controllers\GetContentController::$request

I am trying to send form data including files (if any) without form tag via Ajax request. However, I am getting the following error message
Undefined property: App\Http\Controllers\GetContentController::$request
Here are my codes
Controller
public function GetContentController($params){
$CandidateFullName = $this->request->CandidateFullName;
$CandidateLocation=$this->request->CandidateLocation;
//inserted into database after validation and a json object is sent back
Web.php
Route::match(['get', 'post'], '{controller}/{action?}/{params1?}/{params2?}', function ($controller, $action = 'index', $params1 = '',$params2 = '') {
$params = explode('/', $params1);
$params[1] = $params2;
$app = app();
$controller = $app->make("\App\Http\Controllers\\" . ucwords($controller) . 'Controller');
return $controller->callAction($action, $params);
})->middleware('supadminauth');
Blade
<input type="text" id="CandidateFullName" name="CandidateFullName" class="form-control">
<input type="text" id="CandidateLocation" name="CandidateLocation" class="form-control">
<button id="final_submit">Submit</button>
<script>
$('#final_submit').click(function(e){
e.preventDefault();
var data = {};
data['CandidateFullName']= $('#CandidateFullName').val();
data['CandidateLocation']=$('#CandidateLocation').val();
submitSaveAndNext(data)
});
function submitSaveAndNext(data){
//console.log(data);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': '{{csrf_token()}}'
}
});
$.ajax({
type : "POST",
url : '{{url("GetContent/submitContent")}}', //GetContentController ,but without Controller in the end
dataType : "json",
contentType : "application/json",
data : JSON.stringify(data),
success : function(response){
//console.log("response ",response);
if(response.message=="success"){
swal({
title:"Success",
type: "success",
});
}else{
swal({
title:"Sorry! Unable to save data",
type:"warning"
})
}
},
error:function(xhr, status, error){
swal({
title:"Sorry! Unable to save data",
type:"warning"
})
}
}) //ajax ends
I don't think controller instance in laravel possess the property having request instance, you'll have to type-hint to obtain the object of the request
public function GetContentController($params) {
// $this->request is the issue
$CandidateFullName = $this->request-> CandidateFullName;
$CandidateLocation = $this->request->CandidateLocation;
}
So you can try either of the below-given solutions
// make sure include the Request class into your controller namespace
public function GetContentController($params, Request $request) {
$CandidateFullName = $request->input('CandidateFullName');
$CandidateLocation = $request->input('CandidateLocation');
}
Or use the helper function for request
public function GetContentController($params) {
$CandidateFullName = request('CandidateFullName');
$CandidateLocation = request('CandidateLocation');
}
These links will help you get more details :
https://laravel.com/docs/8.x/requests#accessing-the-request
https://laravel.com/docs/5.2/helpers#method-request

Call Laravel Model Function from Blade Button OnClick Javascript Function and Stay On the Page

Goal:
A user will have a list of games in a table with text boxes for each team's score. I want the user to be able to change the score of a single game, click Save (Model function updates the record), and continue saving more games while never leaving the page.
How:
After a Laravel Blade view has been rendered, I want to execute a Model function from a Javascript function on-button-click, but stay on the same page.
admin.blade.php (Javascript section in Head tag)
/* Save game from inline list on Admin page */
function inlineSaveAdmin(gameId) {
var homeScoreTxt = document.getElementById("homeScoreTxtBox");
var homeScore = homeScoreTxt.value;
var awayScoreTxt = document.getElementById("awayScoreTxtBox");
var awayScore = awayScoreTxt.value;
{{ App\Models\Game::inlineSave(gameId, homeScore, awayScore) }}
}
admin.blade.php (body of view)
<button type="button" onclick="inlineSaveAdmin({{ $game->id }});" class="btn btn-outline-success">Save</button>
So far, the Model function only executes when the page loads, not when I click the button. That is the main problem I wish to solve. Thanks for any help!
(and yes, I believe that I will need to create identical Javascript functions for each gameId that exists to be able to reference the correct homeScoreTxtBox{{ game->id }} since I don't think I could otherwise dynamically pull the text box IDs based on the Javascript function's input parameter)
1.make an ajax function on that blade file
2.call that ajax on click pass the id and updated data
3.define a route for that ajax function in web.php and
4.make a controller function on that route.
Code:
$(document).ready(function() {
$("#button").on('click', function() {
**//get id and score**
var homeScoreTxt = document.getElementById("homeScoreTxtBox");
var homeScore = homeScoreTxt.value;
var awayScoreTxt = document.getElementById("awayScoreTxtBox");
var awayScore = awayScoreTxt.value;
var game_id = gameId;
$.ajax({
type: 'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: '{{ route('update') }}',
//all the data you need to pass to controller function
data: {
'id': gameId,
'homescore': homeScore,
'awayscore' : awayScore
},
// dataType: 'json',
success: function(data) {
//data returned from php
// update the values
if (data) {
homeScoreTxt.value=data.homeScore,
awayScoreTxt.value=data.homeScore
}
},
fail: function() {
alert('NO');
}
});
});
});
web.php
Route::post('update', 'UpdateController#update')->name('update');
Update the values in the controller function by simple model queries.
Send updated data like this:
$response = [
'homeScore' => $homeScore,
'awayScore' => $awayScore
];
return response()->json($response);
I have followed Daniyal Ishaq's answer, and I think I'm getting closer, but I'm getting an error from the Ajax call.
Error:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
(jquery-3.5.1.js:10099) xhr.send( options.hasContent && options.data || null );
Per Google debugger, it appears to be after/inside this call:
(jquery-3.5.1.js:9682) transport.send( requestHeaders, done );
I did some debugging, and a "status" variable is getting set to 500. Then, "isSuccess" is set to False when it gets to this line:
(jquery-3.5.1.js:9723) isSuccess = status >= 200 && status < 300 || status === 304;
That line that sets isSuccess is inside the following function, but I cannot seem to find where it's getting called from to trace where status is getting set exactly.
(jquery-3.5.1.js:9696) function done( status, nativeStatusText, responses, headers ) {
The last line I can find before the error appears is 5233:
(jquery-3.5.1.js:5233) jQuery.event.dispatch.apply( elem, arguments ) : undefined;
Shortly before that line, it is here, where event.rnamespace = undefined, and handleObj.namespace = "" (I don't know if this is relevant):
(jquery-3.5.1.js:5422) if ( !event.rnamespace || handleObj.namespace === false ||
Shortly after that, "ret" is still undefined after this line: (again, I don't know what this does, but it seems important?)
ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle ||
handleObj.handler ).apply( matched.elem, args );
Then on 5446, it returns event.result, which is undefined.
return event.result;
That is where my debugging skills hit a dead end with jQuery. So now I ask for more help.
Ajax function in blade:
$(document).ready(function() {
#foreach($games as $game)
$("#SaveBtn{{ $game->id }}").on('click', function() {
var gameId = "{{ $game->id }}";
var saveBtn = document.getElementById("SaveBtn{{ $game->id }}");
var homeScoreTxt = document.getElementById("homeScoreTxtBox{{ $game->id }}");
var homeScore = homeScoreTxt.value;
var awayScoreTxt = document.getElementById("awayScoreTxtBox{{ $game->id }}");
var awayScore = awayScoreTxt.value;
$.ajax({
url: "{{ route('inlineSave') }}",
type: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
//all the data you need to pass to controller function
data: {
'gameId' : {{ $game-> id }},
'homeScore': homeScore,
'awayScore' : awayScore
},
dataType: "json",
traditional: true,
success: function(data) {
//data returned from php
// update the values
if (data) {
homeScoreTxt.value = data.homeScore;
awayScoreTxt.value = data.awayScore;
saveBtn.innerText = 'Resave';
alert('Success!');
}
},
error: function() {
alert('An error has occurred!');
}
});
});
#endforeach
});
Resulting HTML for Ajax function:
$(document).ready(function() {
$("#SaveBtn11870").on('click', function() {
var gameId = "11870";
var saveBtn = document.getElementById("SaveBtn11870");
var homeScoreTxt = document.getElementById("homeScoreTxtBox11870");
var homeScore = homeScoreTxt.value;
var awayScoreTxt = document.getElementById("awayScoreTxtBox11870");
var awayScore = awayScoreTxt.value;
$.ajax({
url: "http://mbcathletics/admin",
type: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
//all the data you need to pass to controller function
data: {
'gameId' : 11870,
'homeScore': homeScore,
'awayScore' : awayScore
},
dataType: "json",
traditional: true,
success: function(data) {
//data returned from php
// update the values
if (data) {
homeScoreTxt.value = data.homeScore;
awayScoreTxt.value = data.awayScore;
saveBtn.innerText = 'Resave';
alert('Success!');
}
},
error: function() {
alert('An error has occurred!');
}
});
});
... many more of the same function for different button IDs ...
});
Button in blade: (calls its respective function successfully)
<button id="SaveBtn{{ $game->id }}" type="button" class="btn btn-outline-success">Save</button>
Route in web.php: (remember, I do not want to leave the page, I just want it to execute the Controller function... I don't know what to put in the first parameter - the URL)
Route::post('/admin', [App\Http\Controllers\HomeController::class, 'inlineSave'])->name('inlineSave');
Controller function: (it doesn't really do anything right now, I'm just trying to test connectivity before I do the heavy lifting)
public static function inlineSave()
{
$game = Game::find($gameId);
$score = $game->home_score;
$game->home_score = $score;
$response = [
'homeScore' => $homeScore,
'awayScore' => $awayScore
];
return response()->json($response);
}
Thank you! I am sorry for the detail, but it's the only I know how to help.

crud ajax jquery symfony3 wont work

Problem: How do I validate the form and return the validation messages in modal box without refreshing the page.
I just started learning Symfony 3 and I got trouble adding data using AJAX.
I know how to include the template form inside of the modal box but I don't know how to show the error messages of $form->isValid() inside the modal and persist it.
new.html.twig
UPDATE: I can now call the method action in Controller. But when I validate the form I haven't received any validation error inside modal box.
<script>
$(function () {
$('.withdropdown').dropdown();
$('.add-company-launch').modal();
$('#company-form').submit(function(e) {
var formUrl = "{{ path('monteal_backend_company_ajax') }}";
var formData = new FormData(this)
$.ajax({
url: formUrl,
type: 'POST',
data: formData,
contentType: false,
cache: false,
processData: false,
success: function(data, textStatus, jqXHR)
{
if(data['status'] === 'success'){
alert('success');
} else {
$('#add-company').html(data['html']);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
e.preventDefault();
});
})
</script>
{% endblock %}
CompanyController.php
UPDATE: I have create two methods for AJAX,
1. Method to handle a form.
2. AjaxHandler.
public function newAction() {
$company = new Company();
$form = $this->createForm(CompanyForm::class, $company);
return $this->render('Admin/Backend/Company/new.html.twig', array(
'form'=>$form->createView()
));
}
public function ajaxAction(Request $request) {
if (!$request->isXmlHttpRequest()) {
return new JsonResponse(array('message' => 'You can access this only using Ajax!'), 400);
}
$company = new Company();
$form = $this->createForm(CompanyForm::class, $company);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($company);
$em->flush();
return new JsonResponse(array(
'status' => 'success'), 200
);
}
$html = $this->renderView("Admin/Backend/Company/new.html.twig", array(
'form' => $form->createView())
);
return new JsonResponse(['status' => 'error', 'html' => $html]);
}
1 - In your newAction, just create the form and pass the view (createView) to your template.
2 - write a ajaxFormHandlerAction and here create the form, handle it, validate it, render a view in a variable :
$html = $this->renderView('yourTemplate.html.twig', array($form->createView()));
Edit: of course your ajax must post the form to your newly ajax url... END Edit
3 - if it is'nt validated
Return a JsonResponse(array('html' => $html, 'status' => 'error'));
if validated
Return a JsonResponse(array('status' => 'success'));
4 - In your ajax success callback, render the newly form if status error..
if status success, redirect or whatever
Hope this help
Edit :
something like this for your controler :
use Symfony\Component\HttpFoundation\JsonResponse;
public function ajaxFormHandlerAction(Request $request)
{
$company = getYourCompany(); //get it from db?
$form = $this->createForm(CompanyForm::class, $company));
$form ->handleRequest($request);
if($form ->isValid()){
//do whatever you want, maybe persist, flush()
return new JsonResponse(array(
'status' => 'success'));
}
$html = $this->renderView("yourModalTemplate.html.twig", array('form' => $form->createView()));
return new JsonResponse(['status' => 'error', 'html' => $html]);
}
And in your success ajax callback:
success: function(data, textStatus, jqXHR)
{
if(data['status'] === 'success'){
alert('success');
// maybe redirect the user ???
}else if(data['status' === 'error']){
$('#idOfYourModal').html(data['html']); //assuming you use jquery, or translate to javascript
}
},
You have to create a twig template with only the modal inside...

Can't send data to the Controller with a POST method Symfony3

I have a POST method Jquery. Ajax and I can't send my data to the controller, I have tried every solution on the net, but no result.......
My JavaScript
$(document).ready(function(){
$('#submitForm').click(function(){
var data1 = {request : $('#request').val()};
$.ajax({
type: "POST",
url: "/Manufacturer",
data: data1,
success: function(dataBack) {
console.log(dataBack);
},
contentType: "application/json",
dataType: 'json'
});
});
});
MY controller
public function indexAction(Request $request)
{
//$name = $request->request->get('data');
//return new Response($name);//or do whatever you want with the sent value
if($request->isXmlHttpRequest()){
$name = $request->request->get('data1');
If($name == 1)
{
return new Response('Yeap');
}
else
{
return new Response(';(');
}
}
return $this->render('MyIndex/Manufacturer_LIST.html.twig' );
}
HEre is my Console ::
And my response is as it's obvious ";("
First you need to install FOSJsRoutingBundle to be able to "expose" your Symfony routes into the javascript code. Follow the steps in the official documentation.
Then, in your twig template if you have a form like:
<form>
<input type="text" id="name"> <br>
<button type="submit" id="submitForm">Submit</button>
</form>
your js code could look liks this:
$('#submitForm').click(function(e){
e.preventDefault();
var name = $('#name').val();
$.ajax({
method: 'POST',
url: Routing.generate('Manufacturer_LIST');
// OR: url: "/Manufacturer", if you don't want to install FOSJsRoutingBundle
data: { name:name }
}).done(function(msg){
console.log(msg);
}).fail(function(XMLHttpRequest, textStatus, errorThrown){
console.log(textStatus + ' ' + errorThrown);
});
});
And in your controller:
/**
* #Route("/Manufacturer", name="Manufacturer_LIST", options={"expose"=true})
*/
public function indexAction(Request $request){
if($request->isXmlHttpRequest()){
$name = $request->request->get('name');
return new Response($name);//or do whatever you want with the sent value
}
return $this->redirectToRoute('homepage');
}

Serialzing form and posting ajax to function

I am trying to pass the form field values to a php function located into a file. The problem is that I can't understand how to pass that serialized form data to the function from this ajax to a function in php.
$('#insert_news').submit(function(event) {
event.preventDefault();
var form = $('#insert_news').serialize();
$.ajax({
type: 'POST',
url: 'includes/ajax.php',
data: {
action: 'insert_news',
$('#insert_news').serialize(); // how do I add this data here?
},
success: function(datas) {
$('#message').html(datas).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
});
This ajax passed the values to the file ajax.php right beyond. And from ajax.php is called the function located in functions.php.
ajax.php
if (isset($_POST['action']) && $_POST['action'] == 'insert_news') {
$cp->insert_into_table('newss', array(
'NewsTitle' => $_POST['title'],
'NewsDescrption' => $_POST['description'],
'Date' => date('Y-m-d H:i:s'),
'status' => '1'
)
);
}
function.php
public function insert_into_table($table_name, array $data){
foreach($data as $col=>$value) {
$cols[] = $col;
$values[] = '\''.$value.'\'';
}
$cols = implode(', ', $cols);
$values = implode(', ', $values);
$this->db->query("INSERT INTO $table_name ($cols) VALUES ($values)");
echo "INSERT INTO $table_name ($cols) VALUES ($values)";
}
The issue is serialize() produces a URL encoded key value paired string, so you can't mix that with your data object.
You can use serializeArray() to get an array of objects, representing the form elements, then iterate over them and add them to a data object:
var data = { action: 'insert_news' };
$.each($('#insert_news').serializeArray(), function(){
data[this.name] = this.value;
});
$.ajax({
type: 'POST',
url: 'includes/ajax.php',
data: data,
success: function(datas) {
$('#message').html(datas).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
Side note: your PHP code is vulnerable to SQL Injection. Consider using a Prepared Statement instead of concatenating user input into the SQL.
You can pass serialized data via ajax to a function the way you are doing but your code needs slight modification.
$('#insert_news').submit(function(event) {
event.preventDefault();
var form = $('#insert_news').serialize();
$.ajax({
type: 'POST',
url: 'includes/ajax.php',
data: {
action: 'insert_news',
serializedData: form // use variable to assign data here
},
success: function(datas) {
$('#message').html(datas).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
});
I think you can use alternate like this
First : add hidden input for action on your form
<input type="hidden" name="action" value="insert_news"/>
Then your ajax post like this
$('#insert_news').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'includes/ajax.php',
data: $(this).serialize(), // $(this) is from <form id="insert_news">
success: function(datas) {
$('#message').html(datas).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
});
And then use print_r on your ajax.php
print_r($_POST);
$('#insert_news').submit(function(event) {
var name = $("#t1").val();
var pass = $("#t2").val(); //add more var as u need
var key = 0;
var formName = new FormData();
formName.append(key++,name)
formName.append(key++,pass) //append the the var to formdata
$.ajax({
url : 'includes/ajax.php',
dataType : 'text',
cache : false,
contentType : false,
processData : false,
data : formName,
type : 'post',
success : function(data){
$('#message').html(data).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
});
this works fine for me :-)

Categories

Resources