Laravel form select onChange value save to databse via AJAX - javascript

I have a dropdown list generated by the following code in controller (FocalController.php):
$focalData = DB::table('role_users')->orderBy('users.id','DESC')
->leftJoin('users', function($join){
$join->on('role_users.user_id', '=', 'users.id');
$join->on('role_users.role_id', '=', DB::raw("'1'"));
})
->select('users.id',DB::raw('CONCAT(users.name) AS focal'))
->groupBy('users.id')
->get();
foreach($focalData as $data):
$focals[$data->id] = $data->focal;
endforeach;
in the view, I have the following block generating the drop-down list:
{!! Form::select('focal', [''=>'select focal']+ collect($focals)->toArray() , $project_focal, array('class' => 'form-control','onchange'=>'changeFocal(this, '.$project->id.')' ))!!}
I want to submit the drop-down value onChange and save the value using AJAX.
My ajax for the form submission is following:
function changeFocal(e,project_id) {
var focal_id = $("#e").val();
var project_id = $("#project_id").val();
$.ajax({
type: "PUT",
data: "focal_id=" + e + "&project_id=" + project_id,
url: "{{ URL::to('admin/focal') }}",
success:function(data){
console.log(data);$("#msg").html("New Focal Assigned.");
}
});
}
My route is:
Route::post('admin/focal/','FocalController#saveFocal');
the saveFocal function in my FocalController is:
public function saveFocal(Request $request){
$focal_id = $request->focal_id;
$project_id = $request->project_id;
$project = Project::find('idea_id', $project_id)
->update([
'focal' => $focal_id,
'updated_at' => \Carbon\Carbon::now()->toDateTimeString(),
]);
#\App\Common::createAccessLog($project->focal, "Update Project Focal for Project#" . $project->idea_id . "(" . $project->name . ")");
return view('admin/focal');
}
I am getting the following error in console:
Can anyone please tell me what am I doing wrong and how can I save the select data to database with ajax along with a success message.

Use POST instead of PUT
Also make sure the route you are sending your request to is valid and exists
Below are few corrections:
function changeFocal(e,project_id) {
var focal_id = $(e).val(); //correction
var project_id = $("#project_id").val();
$.ajax({
type: "PUT",
data: "focal_id=" + focal_id + "&project_id=" + project_id, //correction
url: "{{ URL::to('admin/focal') }}",
success:function(data){
console.log(data);$("#msg").html("New Focal Assigned.");
}
});
}

Ude where Clause instead find
Project::where(
find works on primary key

Related

Pass variable string from javascript to php using ajax

How to pass a variable value from html page using javascript to php?
i created this code in my index.php
$amount = $_GET['pricenumb'];
echo $amount;
and this is my javascript code to call on click of button and send the data to the PHP file.
<script type="text/javascript">
$(".cell").on("click", "input:checkbox", function () {
var thiss = $(this);
var total = $("#price");
var target = $("label[for='" + thiss.attr("id") + "']");
var item_value = +(target.html().replace(/[^0-9\.]/g, "") || 0);
var cur_total = +(total.html().replace("$", "") || 0);
if (thiss.prop("checked") === true) {
cur_total += item_value;
} else {
cur_total -= item_value;
};
total.text("$" + cur_total);
});
</script>
<script type="text/javascript">
$("#pay_btn").on("click", function () {
var price = $("#price").text();
var pricenumb = price.replace(/[^0-9\.]/g, "");
$.ajax({
type: "POST",
url: "forumdisplay.php?fid=2",
data: "price=" + price + "pricenumb="+ pricenumb,
cache:false,
success: function(){
}
});
});
</script>
and this is the checkbox,
<div class="cell">
<div class="form-check"><label for="check-a" class="form-check-label"><input id="check-a" class="form-check-input" type="checkbox">$166<span class="form-check-sign"></span></label>
<div class="mask visible-on-sidebar-regular">Buy Product</div>
</div>
</div>
the work code is, when I check the checkbox, it will update the div content, and I want when I click on pay button, get the div value via javascript and send the value to my index.php
You are using POST in your ajax and GET in php, chage your ajax to GET. Also, In your ajax change
type: "POST",
url: "forumdisplay.php?fid=2",
data: "price=" + price + "pricenumb="+ pricenumb,
to
type: "GET",
url: "forumdisplay.php",
data: {
price: price,
pricenumb: pricenumb,
fid: 2
}
That's not how you pass data in ajax. The correct format is to use curly braces and define props name and then value
data:{propName1: value1,propsName2: value2,propsName3: "Some string value"}
Which can be used in the file like this in case of POST request.
$_POST['propName1'] which will give value1 variable data as a result
$_POST['propName3'] which will give output as Some string value string
The value can be in quotes if it's a string or not in quotes if it's a variable. So you need to redefine your ajax data props to
$.ajax({
type: "POST",
url: "forumdisplay.php?fid=2",
data: {price: price ,pricenumb: pricenumb},
cache:false,
success: function(response){
// Things to do on success
},
error: function(error){
// Error handling in case of error
}
});
These values you passed can be used in the file forumdisplay.php with $_POST['price'] and $_POST['pricenumb']. The name inside the $_POST is the propsName inside data props in ajax function.

Using ajax to pass javascript array to a controller in codeigniter to use with a function

I have a form with a submit button. When clicked, it adds listed elements to an array.
$("#submitButton").click(function(){
var selection = $("#selectedList li");
var families_selection = [];
selection.each(function() {
families_selection.push($(this).text().replace(/Remove/,''));
});
});
I want to use the array "families_selection" in the controller "Provider", so I can use the following function and instert the values in a database.
$this->Proveedormodel->add_uk_proveedor_familia($idProveedor, $families_selection);
EDIT: I get the value for $idProveedor in the controller, not in the view, using another function in the same "Proveedor" model.
$idProveedor = $this->Proveedormodel->get_idConsecutivo();
This is how I insert the values in the database in my model.
function add_uk_proveedor_familia($id, $params){
foreach($params as $clave){
$this->db->select('id')->from('familia')->where('clave', $clave);
$valor = $this->db->get();
$vl = $valor->row_array();
$familia = $vl['id'];
$this->db->insert('relacionproveedorfamilia', array(
'idProveedor' => $id,
'idFamilia' => $familia
));
}
}
How can I use ajax to pass this array to the controller and use the function I need?
Edited code using Dragan Valjak's response. Now it works!
View add.php
$("#botonGuardar").click(function(){
var seleccion = $("#listaSeleccion li");
var familias_seleccion = [];
seleccion.each(function() {
familias_seleccion.push($(this).text().replace(/Quitar/,''));
});
$.ajax({
url: 'Proveedor/crearRelacion',
method: 'POST',
data: {familias_seleccion: familias_seleccion}
});
});
Controller Proveedor.php
function crearRelacion(){
$this->load->model('Proveedormodel');
$familias_seleccion = $this->input->post($data);
$idProveedor = $this->Proveedormodel->get_idConsecutivo();
$this->Proveedormodel->add_uk_proveedor_familia($idProveedor, $familias_seleccion);
}
Model Proveedormodel.php
function add_uk_proveedor_familia($id, $params){
foreach($params as $clave){
$this->db->select('id')->from('familia')->where('clave', $clave);
$valor = $this->db->get();
$vl = $valor->row_array();
$familia = $vl['id'];
$this->db->insert('relacionproveedorfamilia', array(
'idProveedor' => $id,
'idFamilia' => $familia
));
}
}
$.ajax({
url: 'Provider/functionName',
method: 'POST',
data:
{
families_selection: families_selection
}
});
In Controller
function functionName($data){
$families_selection = $this->input->post($data);
$idProveedor = $this->Proveedormodel->get_idConsecutivo();
$this->Proveedormodel->
add_uk_proveedor_familia($idProveedor,$families_selection);
}
You create your route to handle the ajax, something like '/family_selection' then you can pass your data that you have stored in a post method such as:
$.ajax({
url: '/family_selection',
method: 'POST',
data: {family_data: variable_of_data_you_stored}
});
I'm not familiar with codeigniter but I think you would need to set up a route "something like" $route['family_selection']['post'] = '/family_selection';
In python I would set it up in my controller like so:
Maybe you can use it as an example and implement something similar in codeigniter
#root_resource.route('/family_selection', methods=['POST'])
def family_selection():
family_details = request.form['family_data']
#then I would do whatever it is I want to do with the data...
#then I may or may not want to return an empty response.
return Response(status=http.HTTPStatus.NO_CONTENT)
concentrate on your requirement id and family_data
$.ajax({
url: "Proveedormodel/add_uk_proveedor_familia",
type: 'POST',
data:
{
family_data: variable_of_data_you_stored, //the data that you want to pass..
},
success: function(response)
{
console.log(response);
}
});
In model file: Proveedormodel and function add_uk_proveedor_familia() this changed ur params with family_data
function add_uk_proveedor_familia($id, $params){
$params=$_POST['family_data'];
foreach($params as $clave){
$this->db->select('id')->from('familia')->where('clave', $clave);
$valor = $this->db->get();
$vl = $valor->row_array();
$familia = $vl['id'];
$this->db->insert('relacionproveedorfamilia', array(
'idProveedor' => $id,
'idFamilia' => $familia
));
}
}
here in family_data your passing with large data if your params is the same as family_data then use use post value of family_Data into it.

Joomla & JS; Sending data from form to Controller

I am having trouble with a form I created and trying to redirect the data someplace else by a JavaScript method that I call whenever the submit button is clicked.
The first thing that is happening, is that the form is created and filled in, then the user will click on the HTML generated button with this action in it:
onclick="javascript:saveEssayScore(<?php echo $key . "," . $pid; ?>);"
Secondly the script file is read and performed. The code is below:
<script type="text/javascript" language="javascript">
document.body.className = document.body.className.replace("modal", "");
function saveEssayScore(key, pid){
var user_id = document.getElementById("user-"+key).value;
console.log("user " + user_id);
var grade = document.getElementById("grade-"+key).value;
console.log("grade " + grade);
var teacher_answer = document.getElementById("feedback-"+key).value;
console.log("teacher_answer " + teacher_answer);
var question_id = document.getElementById("question-"+key).value;
console.log("question_id " + question_id);
var quiz_id = document.getElementById("quiz-"+key).value;
console.log("quiz_id " + quiz_id);
var req = new Request.HTML({
method: 'post',
url: "<?php echo JURI::base();?>index.php?option=com_guru&controller=guruAuthor&task=saveFeedback&tmpl=component&format=raw",
data: { 'pid' : pid, 'user_id' : user_id, 'grade' : grade, 'teacher_answer' : teacher_answer, 'question_id' : question_id, 'quiz_id' : quiz_id},
onSuccess: function(response, responseElements, responseHTML){
alert('yeyy');
}
}).send();
}
Now in the URL, it is read to run the method (task) saveFeedback() in the controller guruAuthor which is in the component com_guru.
The problem I am having is, how do I read the data that I just send through the HTML request? I am trying stuff like $user_id = JRequest::getVar("user_id"); But whenever I'm trying to echo or dump, it is returned to me but empty. Not the values that I am dumping in JavaScript console.log(user_id);
JRequest is deprecated
Use JInput instead. Read - Retrieving request data using JInput
In your mentioned code - if the controller function is being called, try this code-
$jinput = JFactory::getApplication()->input;
$user_id = $jinput->get('user_id', '', 'INT');
I hope this helps.

Passing JavaScript array from view to Laravel controller

I am trying to pass objs array to a function in Laravel controller using ajax. I am not recieving any data after the post.
<script>
var itemCount = 0;
var objs=[];
$(document).ready(function(){
var temp_objs=[];
$( "#add_button" ).click(function() {
var html = "";
var obj = {
"ROW_ID": itemCount,
"STREET_ADDRESS": $("#street_address").val(),
"CITY": $("#city").val(),
"ZIP": $("#zip").val()
}
// add object
objs.push(JSON.stringify(obj));
itemCount++;
// dynamically create rows in the table
html = "<tr id='tr" + itemCount + "'><td>" + obj['STREET_ADDRESS'] + "</td> <td>" + obj['CITY'] + " </td> <td>" + obj['ZIP'] + " </td><td><input type='button' id='" + itemCount + "' value='remove'></td> </tr>";
//add to the table
$("#multiple_table").append(html)
// The remove button click
$("#" + itemCount).click(function () {
var buttonId = $(this).attr("id");
//write the logic for removing from the array
$("#tr" + buttonId).remove();
});
});
$("#submit").click(function() {
$.ajax({
url:'/app/Http/Controllers/Search/search_address',
type: 'POST',
dataType:'json',
contentType: 'application/json',
data: objs
});
});
});
</script>
In my controller function is like this
public function search_address(){
$data = json_decode($_POST['data'], true);
print_r($data);
}
I guess that I am having a problem with the url in ajax and I am not sure how a controller's url is obtained.
Thank you
Can you change:
$data = json_decode($_POST['data'], true);
to:
$data = json_decode(Input::get('data'));
and make sure you have: use Input; above your class extends Controller
See if that works.
Edit: Also make sure your routes (in the Controllers folder) are correct.
You should console.log() your javascript by placing the following in you ajax post:
error : function(e){
console.log(e);
}
You can then see what errors you are getting in your browsers' developers tools panel.
You should also be aware that that Laravel posts require a csrf token unless you have explicitly turned them off, which means you will need to add this token in to your post as well. So you should end up with:
$("#submit").on('click', function() {
$.ajax({
url:'/app/Http/Controllers/Search/search_address', // Is this what you meant, is this the route you set up?
type: 'POST',
data: {'data': objs, '_token' : '<?=csrf_token()?>'},
success : function(data){
// Do what you want with your data on success
},
error : function(e){
console.log(e);
}
});
});
Notice that I've embedded php inside the javascript, which is just to illustrate the point. Ideally javascript is kept in it's own files, so you would then need to find a way to pass this token through. I personally use knockoutjs for this type of thing (AngularJS is also popular), but you can easily do something like:
<input type="hidden" id="_token" value="{{ csrf_token() }}" />
in your HTML, then pull this value from inside your ajax request:
data: {'data': objs, '_token' : $('#_token').val()}
EDIT
I've just noticed your url, it looks like you are trying to access the controller directly. You need to set up a route in your routes.php file, such as:
Route::post('/searchAddress', 'YourController#search_address');
Then use:
url: /searchAddress
in your ajax request.

AJAX doesn't get data from PHP file with Jquery

I'm trying post data to PHP file but i can't receive any data from PHP file. Let me add codes.
This is my jQuery function:
$(document).ready(function () {
$(function () {
$('a[class="some-class"]').click(function(){
var somedata = $(this).attr("id");
$.ajax({
url: "foo.php",
type: "POST",
data: "id=" + somedata,
success: function(){
$("#someid").html();
},
error:function(){
alert("AJAX request was a failure");
}
});
});
});
});
This is my PHP file:
<?php
$data = $_POST['id'];
$con = mysqli_connect('localhost','root','','somedatabase');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"database");
$sql="SELECT * FROM sometable WHERE id = '".$data."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo $row['info'];
}
mysqli_close($con);
?>
This what i have in HTML file:
<p id="someid"></p>
Data1
Data2
Note: This website is horizontal scrolling and shouldn't be refreshed. When i'm clicking links (like Data1) it's going to another page without getting data from PHP file
You have a few problems:
You are not using the data as mentioned in the other answers:success: function(data){
$("#someid").html(data);
},
You are not cancelling the default click action so your link will be followed:$('a[class="some-class"]').click(function(e){
e.preventDefault();
...;
As the id's are integers, you can use data: "id=" + somedata, although sending an object is safer in case somedata contains characters that need to be escaped:data: {"id": somedata},;
You have an sql injection problem. You should cast the variable to an integer or use a prepared statement:$data = (int) $_POST['id'];;
As also mentioned in another answer, you have two $(document).ready() functions, one wrapping the other. You only need one.
success: function(){
$("#someid").html();
},
should be:
success: function(data){
$("#someid").html(data);
},
You should add parameter in success
success: function(data){ //Added data parameter
console.log(data);
$("#someid").html(data);
},
The data get the values what you echo in PHP end.
This:
success: function(data){
$("#someid").html(data);
},
and you have two document ready, so get rid of:
$(document).ready(function () { ...
});
data: "id=" + somedata,
Change it to:
data: { id : somedata }

Categories