Moved javascript to separate file, ajax calls are giving error - javascript

In trying to cleanup my code base, I moved all of my javascript from script tags to their own javascript file. After doing that, all of my ajax calls are failing.
Here's the javascript, this is EXACTLY how it was in the *.cshtml file, excluding the script tags:
$(function () {
$("#weightList").change(function () {
var weight = $("#weightList").val();
var conference = $("#conference").val();
$("#wrestlerAList").prop('disabled', true);
$("#wrestlerBList").prop('disabled', true);
$.ajax({
url: '#Url.Action("GetByWeight", "Wrestler")',
data: {
weight: weight
},
type: 'POST',
success: function (data) {
var wrestlers = "<option></option>";
$.each(data, function (i, wrestler) {
wrestlers += "<option value='" + wrestler.Value + "'>" + wrestler.Text + "</option>";
});
$("#wrestlerAList").html(wrestlers);
$("#wrestlerBList").html(wrestlers);
$("#wrestlerAList").prop('disabled', false);
$("#wrestlerBList").prop('disabled', false);
},
error: function (error) {
alert("An error occurred retrieving the wrestlers for this weight.");
}
});
});
});
I've tried removing the "$(function () {...});" but that didn't work. Is there other syntax required when the javascript is not directly on the cshtml page?
Edit: I'm loading my javascript file at the very end of the cshtml file, right before the closing tag.
Also, I'm getting a 404 back. If the code stayed the same, why would it now be getting a 404?

url: '#Url.Action("GetByWeight", "Wrestler")',
that line needs to be rendered on a cshtml page. it doesnt get processed in a .js file.

The problem is with the way you are setting the ajax url
url: '#Url.Action("GetByWeight", "Wrestler")'
The ASP.NET MVC tag helper #Url.Action() will not work inside a .js file.
You could place the url in a hidden form field and read it from there.
Place this somewhere in the .cshtml preferably outside of any forms so it is not posted back in the form for any reason.
#Html.Hidden("ServiceUrl", Url.Action("GetByWeight", "Wrestler"))
Then use the code below to set the jQuery ajax url
url: $('#ServiceUrl').val(),

Related

Knockout binding not updating in html

I have been working on a project that uses knockout for databinding from javascript to html. I am also reading data from a PLC using ajax, the data from the ajax request will put into the knockout viewmodel and shown on the webpage. I am having some trouble with the updating of the data binding.
I searched on the internet for help but didn't find anything so far that helped me so I hope you can help me further.
I have setup the viewmodel as following inside a javascript file:
function AppViewModel() {
var self = this;
self.hmitags = ko.observableArray(groupDataValues);
self.Capa100 = ko.observable("Cap100");
self.Testvar = ko.observable(50);
}
var viewModel = new AppViewModel();
ko.applyBindings(viewModel);
And have the data binding in the html file:
<span data-bind="text: Testvar></span>
when I now load the html file I see the value 50 as defiened in the viewmodel, so that is working. But now I want to read a variable from my PLC using ajax that is done through a function inside that same javascript file. This is how the function looks:
function ReadVariable()// function for reading out individual variables
{
// list can contain only one variable
var HMIReadList = "&paths=MainInstance.Testvar"
data.length = 0; // get rid of the data from the last query
// issue the data request
$.ajaxSetup({
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + BearerToken);
}
});
$.ajax({
type: "GET",
url: baseurl + "_pxc_api/api/variables?pathPrefix=Arp.Plc.Eclr/" + HMIReadList,
})
.done(function (data, status, jqXHR) {
viewModel.Testvar = data.variables[0].value;
console.log(viewModel.Testvar);
})
.fail(function (jqXHR, status, errorThrown) {
console.log("CreateSession Error: " + errorThrown);
console.log("Status: " + status);
console.dir(jqXHR);
alert("CreateSession $.ajax failed. Status: " + status);
});;
}
I am using a button in the html page to call this function. In the console I can see that it is reading a value from the PLC and that it is different that the initial value 50. But on the html page it is not changing. I am not sure why it isn't working I have been looking around for some solutions but have not found anything that is working.
A knockout observable is a function. In order to update the value of the observable, you need to invoke the function with the new value as follows:
viewModel.Testvar(data.variables[0].value)

Jquery/AJAX function not working onChange Event

I am trying to populate a dropdown menu on behalf of the value of an other dropdown. the problem here is that the function i am trying to call in select tag's onChange event is not being compiled. and an error is appearing in console.enter code here.
HTML:
<select name="street_id" id="street_id" onchange="get_data(this)" class="input-xlarge">
</select>
Jquery:
<script type="text/javascript">
function get_data()
{
$('#client_list').empty()
var dropDown = document.getElementById("street_id");
var street_id = dropDown.options[dropDown.selectedIndex].value;
$.ajax({
type: "GET",
url: "http://localhost:7777//index.php/admin/get_one_street_client/" + street_id,
data: { 'street_id': street_id },
success: function(data){
// Parse the returned json data
var opts = $.parseJSON(data);
// Use jQuery's each to iterate over the opts value
$.each(opts, function(i,d) {
console.log(d.client_name);
// You will need to alter the below to get the right values from your json object. Guessing that d.id / d.modelName are columns in your carModels data
<?print "var value == '$balance_data[0]->client_id'";
//$selected = 'selected';
?>
$('#client_list').append('<option value="' + d.client_id + ' ">' + d.client_name + '</option>');
});
}
});
}
</script>
Error:
insert_balance:180
Uncaught ReferenceError: get_data is not definedonchange #
insert_balance:180
i have already added the jquery library address on top.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Clearly, you should not put that php inside the success callback of the AJAX response. I can't imagine what good this could do. Just erase those lines.
I don't know what that php generates, but it looks like it generates a syntax error in function get_data().
This means the whole script (within the script tags) does not get compiled.
Also, it looks like that line of code isn't doing anything, even if it didn't cause problems
var value == 5 ; no idea why this code is present

Laravel 5 attach with Ajax?

I have this laravel code in my controller detach function.
$input = Input::all();
$product= Products::findOrFail($input['product_id']);
$product->tags()->detach($input['tag_id']);
$product= Products::where('customer_id', Auth::user()->customers_id)->get();
return view('products.tagsdelete', [
'products' => $product,
]);
This works fine, it deletes the tag realation from my pivot table. The only thing that bugs me it that I don't want to reload the page everytime I press the delete button on my view.
( Of course I could make a selection of all tags the user want to delete, but I want to to this live with Ajax )
My problem is, I couldn't find anything that helps me with detachment from laravel + Ajax. I'm quite okay with Javascript and Jquery but Ajax is still a new thing for me..
So can anybody help me there? I'm really stuck.
Thanks for taking your time :)
#Wiriya Rungruang
current controller code:
public function detach()
{
$input = Input::all();
$product= Products::findOrFail($input['product_id']);
$product->tags()->detach($input['tag_id']);
$product= Products::where('customer_id', Auth::user()->customers_id)->get();
}
my button:
<button type="submit" class="delete-tag-btn" data-product_id="{{ $product->id }}" data-tag_id="{{ $tag->id }}"><i class="glyphicon glyphicon-trash"></i></button>
at the bottom of the code the JS:
<script>
$(".delete-tag-btn").on('click', function(){
var url = "{{ route('detach') }}"; // Url to deleteTag function
url += "product_id=" + $(this).data('product_id');
url += "&tag_id=" + $(this).data('tag_id');
// Now url should look like this 'http://localhost/deletetag?product_id=2&tag_id=5
// Send get request with url to your server
$.get(url, function(response){
alert("success");
});
});
</script>
First : You should create function detach tag from product in your controller and return status success or failure(or nothing)
In your controller
function detachTag(){
$input = Input::all();
$product= Products::findOrFail($input['product_id']);
$product->tags()->detach($input['tag_id']);
$product= Products::where('customer_id', Auth::user()->customers_id)->get();
return "Some state for checking it a success or not";
}
Second : Create javascript function for checking when you click on delete button send request with parameter to function that we created in the first step and rerender or remove that tag from your HTML page
**Parameter is mean product_id and tag_id that your want to detach it
In your js
$(".delete-tag-btn").on('click', function(){
var url = "localhost/deletetag?"; // Url to deleteTag function
url += "product_id=" + $(this).data('product_id');
url += "&tag_id=" + $(this).data('tag_id');
// Now url should look like this 'http://localhost/deletetag?product_id=2&tag_id=5
// Send get request with url to your server
$.get(url, function(response){
// Do what you want
});
});
So when you click on .delete-tag-btn It will send request for detach it
While you can right a simple ajax call, send data and return html and replace it with the old html
lets begin :)
first step is to write ajax, and send it when form is submit or any button is clicked (as per your code)
this one is sample ajax, just fill in your data in it.
var BASEURL = window.location.origin + "/your_domain_name/";
$.ajax({
url: BASEURL + "your_route",
type: "POST/GET", //any_one
data: {
// Your data comes here (object)
},
beforeSend: function () {
},
success: function (response) {
console.log(response); // your html in return
},
complete: function (response) {
}
});
now a call will be send with your data to controller respective to specified route you mentioned, processing will be normal.
It will return only html. You can do whatever you want with this html.
One important problem you might face if considering these instructions is, right now the view you are returning is probably of whole page (because the page is been refresh every time), but if you are thinking to replace it with new html, your will only have to return that part of the page may be a single row or something like that. So break your view in many sub views. Php #include(//path) (blade) might come handy. Thats how I use to work. :)

Jquery error in reloading javascript function trying to load json data with AJAX

I am trying to visualise a folder structure with javascript and json. It automatically loads the root of the folder. When a user clicks on a folder, it should load the files and folder in that folder etc.
The javascript code to get deeper in the json works fine, it loads the first "layer" of the json file with the variable "root". If I change this manually to "roots.deeperFolder" it reaches that folder. That's works fine.
$.ajax({
type: 'GET',
url: 'directory.json',
data: {
get_param: 'value'
},dataType: 'json',
success: buildRoot
});
Code for ajax reaquest and call buildRoot function if succes.
function buildRoot(root, clickedFolder){
if (typeof root === 'string') {
var addFolder = "." + clickedFolder;
var stringRoot = root + addFolder;
var root = eval(stringRoot);
console.log(stringRoot);
}
$.each(root, function(index, element){
if (isNaN(index)) {
$("#sideFolderContainer").append("<li class='folder' id=" + index + ">" + index + "</li>");
}
else {
$("#sideFolderContainer").append("<li>" + element + "</li>");
}
});
}
This function succesfully iterates through the first layer of the JSON file. The "if string" function only applies after click function.
$(document).on('click', '.folder', function(e) {
var root = "root";
var clickedFolder = $(this).attr("id");
buildRoot(root, clickedFolder);
});
This function sends the "deeper folder" information to the previous buildRoot function. The buildRoot function adds the name of the deeper folder to root. (root.deeperFolder) what manually works.
I guess passing through the data between the function is not the problem since this works fine. I get the errors at this line:
$.each(root, function(index, element){
This is what the console outputs (ignore first line).
Link to JSON data.
http://codebeautify.org/jsonviewer/f56dce
I do recommend to use JSON.parse(jsonString); instead of eval.
I thing this is a better approach. (see the jQuery documentation)

JQuery AJAX function not receiving PHP-returned text

I've been searching for a while for a solution to this problem. I've found many people with the same problem, but not the same solution.
The issue I'm having is that PHP is not returning any data to the AJAX function. The alert spits out data = undefined. As you can see, using return instead of echo is not the problem. I know that the PHP script I call completes correctly because the values are properly inserted into the database. No matter where I place the echo statement, I can't get it to return the value. Am I using the data variable incorrectly? Is returnValue not the proper variable to use? Has any of the functionality I've been trying to use been deprecated? I'm really at a complete loss. I can't see why this is failing.
//AJAX function
$("document").ready(function(){
$("#add_interest_form").submit(function(event) {
event.preventDefault();
$("#output").html("");
var values = $(this).serialize();
$.ajax
({
url: "./php/add_interest.php",
type: "POST",
data: values,
success: function(data) {
alert('data = ' + data.returnValue);
$("#output").html(data.returnValue);
},
error: function() {
alert('failed adding to database. Please try again or contact the Webmaster.');
}
});
});
});
//PHP snippet
echo 'Success!';
Just do alert('data = ' + data); instead of alert('data = ' + data.returnValue);.

Categories

Resources