Pass Model data to ajax request url for dataTables - javascript

I am trying to pass the #Model.Id from my razor view to the javascript so that I can pass it to the dataTables ajax url but I cant manage to get the value to the javascript file.
Even just a point in the right direction would help at this point
Here is the View:
#model GTravel.Domain.Package
#{
var title = Model.Name;
}
//boring html code
#section Scripts{
<script src="~/js/packageCity.js" data-packageId="#Model.Id"></script>
}
And a snippet of the js:
var dataTable;
var url;
$(document).ready(function () {
url = "/admin/packageCity/GetAll/" + packageId.toString();
loadDataTable();
});
function loadDataTable() {
dataTable = $('#tblData').DataTable({
"ajax": {
"url": url,
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "city", "width": "10%" },
//more code etc

Based on your method, you are missing some key content.
To ensure that the value passed by data-packageId can be accurately obtained in the js file, you need to add an id to the script that references the js file, and then obtain the passed value by obtaining the corresponding id in the js file:
#section Scripts{
<script id="Index.js" src="~/js/packageCity.js" data-packageId="#Model.Id"></script>
}
js file:
$(document).ready(function () {
var $vars = $('#Index\\.js').data();
url = "/admin/packageCity/GetAll/" + $vars.packageid;
loadDataTable();
});
And it should be noted that when obtaining the packageId through $vars, make sure that the packageId are all lowercase letters.
Another method:
You can create a variable in the view directly before referencing the js file, and then accept the value that needs to be passed, so that in the js file, you can directly call the variable to get the value that needs to be passed.
#section Scripts{
<script>
var data = '#Model.Id';
</script>
<script src="~/js/packageCity.js" ></script>
}
js file:
$(document).ready(function () {
url = "/admin/packageCity/GetAll/" + data;
loadDataTable();
});

Related

Console shows 'Incorrect integer value' when I try to post form with laravel. Route parameter is not recognized

I'm trying to post answers to database that user has submited. Questions are same for different subjects so I have a foreign key to subject_id and user_id. But I always get 500 error.
These are my routes:
Route::get('/predmeti/{subject}/analiza', 'AnalizaController#show');
Route::post('predmeti/{subject}/analiza_answers', 'AnalizaAnswerController#store');
AnalizaController that gets the show view:
public function show(Request $request, $subject_id)
{
$analizaquestions=AnalizaQuestion::all();
return view('analiza.show', compact('analizaquestions'));
}
AnalizaAnswerController used for post method:
public function store(Request $request, $subject_id)
{
$validated = $request->validate([
'answer'=>'required',
'analiza_question_id'=>'required',
]);
$validated['user_id']=Auth::id();
$validated['subject_id']=$subject_id;
AnalizaAnswer::create($validated);
return redirect('/predmeti/'.$subject_id);
}
And finally js file used to post it:
window.addEventListener('load', function () {
function submitAnswers() {
$(this).hide();
$('#loader').show();
$('.answer_form').each(function () {
var answer={};
answer['analiza_question_id'] = $(this).find('input[name="analiza_question_id"]').val();
answer['answer'] = $(this).find('input[name="answer"]:checked').val();
console.log(answer);
$.ajax({
type: "POST",
url: "/predmeti/{subject}/analiza_answers",
data: answer,
success: function(data) {
window.location.href = "/predmeti/{subject}/analiza";
},
});
});
}
$('#btn_submit_answers').click(submitAnswers);
});
Every time I try to post I get 'SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: '{subject}' for column 'subject_id' at row 1 (SQL: insert into analiza_answers (answer, analiza_question_id, user_id, subject_id, updated_at, created_at) values (Ne, 1, 56, {subject}, 2019-09-06 16:41:40, 2019-09-06 16:41:40))' and '%7Bsubject%7D' in my route. I don't know how to get the id from my route so I could post to database.
You're literally posting {subject} as $subject_id via /predmeti/{subject}/analiza_answers in your ajax request, but you need to replace {subject} with the $subject_id.
First, make sure you pass $subject_id to your view:
public function show(Request $request, $subject_id)
{
$analizaquestions=AnalizaQuestion::all();
return view('analiza.show', compact('analizaquestions', 'subject_id'));
}
Then, in your ajax request, pass the value. If your javascript is within a <script> element in your show.blade.php file, you can simply do:
window.addEventListener('load', function () {
function submitAnswers() {
...
$('.answer_form').each(function () {
$.ajax({
url: "/predmeti/{{ $subject_id }}/analiza_answers",
...
window.location.href = "/predmeti/{{ $subject_id }}/analiza";
Note: {{ $subject_id }} is .blade.php syntax that outputs the value of your php variable $subject_id. This is valid as long as this is a .blade.php file and not an external .js file.
If your js is in an external .js file, you need to assign the value to a javascript one before you include your js:
<script type="text/javascript">
var subjectId = "{{ $subject_id }}";
</script>
<script src="external.js"></script>
And make sure you replace the value as required:
url: "/predmeti/" + subjectId + "/analiza_answers",
window.location.href = "/predmeti/" + subjectId + "/analiza";
At this point, when your ajax submits, $subject_id in your public function store() will be the same value as public function show() as you have successfully replaced {subject} in the url with the subject ID.

how to access laravel controller data in imported javascript file

I use ajax to update a table based on the entries of the user.
$('#user').change(function(){
var user= $("#user").val();
if (user !='None'){
$.ajax({
type: "GET",
url: '/getUserAccounts/' + user,
success: function (data) {
$.each(opts, function(i, d) {
console.log(d);
});
},
error: function (data) {
console.log('Error:', data);
}
});
}
});
I write the code in a <script> tag, all work fine. now i prefer to organize the javascript code in files and import them into my .blade.php file.
the problem: the data passed from the controller is not recognized in my javascript file.
it's not possible to use controller data from a javascript file because they're not blade templates. What I usually do is have a hidden field on the page (or a meta header) that allows me to store the data I need and then I get the value I want from my JS files from those fields, example:
<input id="user_id" type="hidden" value="{{user_id}}">
In your javascript file:
var user_id = $("#user_id").val();
possible by creating pass value function
sample.js
function runCode(url) {
// your code process
}
in blade.php
...
include sample.js here
<script>
runCode('{{ $user_id }}');
</script>

How to set a Model property inside javascript and be able to receive it in POST method

I have a button when that button is clicked I want to set a model property to true and be able to receive it in the back end. Code is a bit messed up but bear with me please as I have taken alot of code out of it.
#model FullConfigurationMV
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "MyForm" }))
{
#Html.HiddenFor(model => model.IsTemplate)
// Code removed for brevity
<button id="DraftName">Click me</button>
}
<script>
$( document ).ready(function() {
debugger;
$("#DraftName").click(function()
{
#Model.IsTemplate = true; // I AM SETTING THE VALUE AS TRUE
SaveStyles();
});
});
</script>
<script>
function SaveStyles() {
var data = $('#MyForm').serialize();
var URL = "SOME URL"
$.ajax({
url: URL,
type: 'POST',
data: data,
success: function (result) {
},
error: function (error) {
}
});
}
</script>
POST ACTION
public JsonResult SaveStyles(FullConfigurationMV data)
{
// data.IsTemplate is coming out to be false
// Rest of the UI control data is coming back properly
}
EDIT
Since I have below code. is that the issue?
var data = $('#MyForm').serialize();
Think about this problem a little differently.
All the view does is render html. Since you have a form in html, all your javascript has to do is to set the form element's value to true.
You should be able to use the jQuery selector like
$('input:hidden[name=IsTemplate]').val(true);
And your form serialize should pick it up.
Razor view are generated in server side. So when you browser get the HTML there is no razor code in it so the following code will not work:
$("#DraftName").click(function()
{
#Model.IsTemplate = true; // <-- this will not work and will not exist in client side
SaveStyles();
});
You should set the hidden field you just put in your form #Html.HiddenFor(model => model.IsTemplate) which generate <input type='hidden' /> and just update your javascript code by doing this:
$("#DraftName").click(function()
{
$("#MyForm input[type='hidden']").val("true"); // <- Replace your Razor code with this.
SaveStyles();
});

Print passed value from url in jquery

This is my test.rb
require 'sinatra'
require 'json/pure'
get '/2015/:teachername/teaching/:subjectname' do
content_type :json
{
"message" => "#{params[:teachername]} teaching #{params[:subjectname]}."
}.to_json
end
It's all fine, like when I access through url localhost:4567/2015/Anil/teaching/Sunil, but when I access this url in jquery I couldnot get passed :teachername and :subjectname.
Here is my test.html
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$.getJSON('/2015/:teachername/teaching/:subjectname', function(data) {
alert(data.message);
});
</script>
You'll have to construct the URL string by appending your parameters in Javascript.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
var teachername = 'Anil';
var subjectname = 'Sunil';
$.getJSON('/2015/'+teachername+'/teaching/'+subjectname, function(data) {
alert(data.message);
});
</script>

Use Mustache.js to render a list of values from a JSON response

I am using Mustache.js to format a response from a jQuery getJSON() request. The getJSON request gets a list of images names. I want to display a series of these images at the end of my existing content when the call is made.
The JSON that is returned looks like this:
[
{"id":{"_time":1351063373,"_machine":56912161,"_inc":1690583039,"_new":false},"url":"5.jpg","tags":[]},
{"id":{"_time":1351063237,"_machine":56912161,"_inc":1690583038,"_new":false},"url":"Repinzle-Logo.png", "tags":[]},
{"id":{"_time":1351063186,"_machine":56912161,"_inc":1690583037,"_new":false},"url":"21.jpg","tags":[]}}
]
I am parsing it with the each function ... my AJAX request (with jQuery looks like this):
<script type="text/javascript">
var imageNum=20;
var imageCount=0;
function getMoreImages(){
imageCount=imageCount+imageNum;
$.getJSON("/getImages", { start: imageNum, count: imageCount },
function(data){
$.each(data, function(key, val) {
// do stuff with val.url
var url = val.url;
var template = $('#item-tpl').html();
var newitem = Mustache.to_html(template, url);
$('#main').append(newitem);
});
});
}
</script>
And here is the mustache.js template
<script id="item-tpl" type="text/html">
<div><img src="https://myurlstem.com/mydir/{{url}}" class="item"></div>
</script>
As far as I can see I've set everything up correctly, but for some reason url is not being sent to the template correctly.
You need to pass an object to the to_html method.
var newitem = Mustache.to_html(template, { url: url });
Normally, I think you'd pass your entire model or collection.

Categories

Resources