IE SCRIPT5002 error (Function ecpected) - javascript

I was looking for that error in stack but didn't find anything about it (exept listeners). So I have code like this:
<a onclick="startDownload(447, '63dc7ed1010d3c3b8269faf0ba7491d4', 217)">
and my Js is:
function startDownload(modId, secret, file){
var transfer = {
id : modId,
secret : secret,
file : file
};
$.ajax({
url: "download/index",
type: 'POST',
dataType: 'json',
data: transfer,
success: function(data) {
if(data.redirect_failed){
location.href = data.redirect_failed;
} else if(data.redirect_success){
location.href = data.redirect_success;
}
}
});
};
so why this not working with IE? how to fix it?

Related

MethodNotAllowedHttpException when trying to post data to controller via ajax in laravel

I'm trying to send dynamically generated data to controller via ajax in laravel. When user select an option from the dropdown then along with selected option and other data should be sent to controller.
I've tried to send data to controller when an option from dropdown is selected. But every time i try this error,
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
and in the error
REQUEST_METHOD is GET
This is the where i call the ajax function
$(document).on('change', '.route-code-selector', function() {
var selectorID = $(this).attr('id');
addRoutePlanDetails(selectorID);
});
AJAX function
function addRoutePlanDetails(selectorID) {
var routePlanCode = document.getElementById("routeplanno").value;
var driver = $("#selectDriver").val().split('|');
var salesman = $("#selectSalesman").val().split('|');
var router_01 = $("#selectRouter01").val().split('|');
var router_02 = $("#selectRouter02").val().split('|');
var vehicle_no = document.getElementById("enterVehicleNo").value;
var route_code = document.getElementById(selectorID).value;
var date = document.getElementById("date").value;
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
url: 'addNewRoute',
method: 'POST',
dataType: 'json',
data: {
routePlanCode: routePlanCode,
driver: driver[1],
salesman: salesman[1],
router_01: router_01[1],
router_02: router_02[1],
vehicle_no: vehicle_no,
route_code: route_code,
date: date
},
success: function() {
console.log("success");
}
});
}
Route
Route::group(['prefix' => 'admin'], function () {
Voyager::routes();
Route::get ('route-plan', 'RoutePlanController#index');
Route::get ('excludePorterRes', 'RoutePlanController#excludePorterRes');
Route::get ('retreiveRouteData', 'RoutePlanController#retrieveRouteCodeData');
Route::get ('retreiveUserData', 'RoutePlanController#retreiveUserData');
Route::get ('retreiveNewRouteData', 'RoutePlanController#retreiveNewRouteData');
Route::post('addNewRoute', [
'uses' => 'RoutePlanController#insertNewRoute',
'as' => 'addNewRoute'
]);
});
controller
public function insertNewRoute(){
$routeplan = new Routeplan;
$user_email = auth()->user()->email;
$routeplan->RouteplanCode = Input::get('routePlanCode');
$routeplan->RouteCode = Input::get('route_code');
$routeplan->DriverID = Input::get('driver');
$routeplan->SalesmanID = Input::get('salesman');
$routeplan->Routercode1 = Input::get('router_01');
$routeplan->Routercode2 = Input::get('router_02');
$routeplan->VehicleNo = Input::get('vehicle_no');
$routeplan->Date = Input::get('date');
$routeplan->Createuser = $user_email;
$routeplan->Status = 'TEMP';
$routeplan->save();
}
when user select an option all the data should be stored in the db.
Try it once
url: '{{ route('addNewRoute') }}',
The issue is here:
url: 'addNewRoute',
here you are calling the route in a wrong manner, use it like:
url: '{{ url('admin/addNewRoute') }}',
you have to call the url() method so that it can create the right url format and don't forget the addNewRoute is grouped under admin, so you have to append that to while calling it.
If ajax method is runs in external javascript file, you should define a url variable in the blade (generally it layout blade.) that using as ajax request url on the ajax call method. (before .js file is loaded);
Example var url = '{{ route('addNewRoute') }}'
$.ajax({
url: url',
method: 'POST',
dataType: 'json',
data: {
routePlanCode: routePlanCode,
driver: driver[1],
salesman: salesman[1],
router_01: router_01[1],
router_02: router_02[1],
vehicle_no: vehicle_no,
route_code: route_code,
date: date
},
success: function() {
console.log("success");
}
});
If you using ajax in the blade, you can use directly route as ajax request url.
$.ajax({
url: "{{ route('addNewRoute') }}",
method: 'POST',
dataType: 'json',
data: {
routePlanCode: routePlanCode,
driver: driver[1],
salesman: salesman[1],
router_01: router_01[1],
router_02: router_02[1],
vehicle_no: vehicle_no,
route_code: route_code,
date: date
},
success: function() {
console.log("success");
}
});
You forgot / in your routes.
Route::group(['prefix' => 'admin'], function () {
Add / in admin/
Route::group(['prefix' => 'admin/'], function () {
Then you can try this in your ajax
url: '{{ url('admin/addNewRoute') }}',
or
url: 'admin/addNewRoute',
Try if this will work.
You have used prefix for your routes. So all your route in group will be prefix/uri.
So in ajax call you should url: '{{ url('admin/addNewRoute') }}', and change method to type
$.ajax({
url: '{{ url('admin/addNewRoute') }}',
type: 'POST',
dataType: 'json',
data: {
routePlanCode: routePlanCode,
driver: driver[1],
salesman: salesman[1],
router_01: router_01[1],
router_02: router_02[1],
vehicle_no: vehicle_no,
route_code: route_code,
date: date
},
success: function() {
console.log("success");
}
});
In ajax for specifying HTTP Verb use type not method.
if your script is in blade file then use route() to set url in ajax:
$.ajax({
url: '{{route('addNewRoute')}}',
method: 'POST',
dataType: 'json',
...
});
Try this:
Please use url: '{{ route('addNewRoute') }}' instead of url: 'addNewRoute'.
As many of you said.. I changed method to type.. And it still didn't work. But then i looked at laravel logs (storage/logs) and from the logs i found that some of my controller syntax are incorrect. And that's why it still gave me the 500 error. After I changed the syntax and do the corrections. It worked !! Anyways thanks for helping guys! If anyone is getting this error even if your ajax is correct take a look at laravel logs.. Hope this helps someone.

Failed to load resource: the server responded with a status of 500 using Ajax

I know this question has been asked previously, but I cannot find out what is the exact problem with my code.
function viewcalldetails(obj) {
alert("clicked");
var id = $(obj).attr("id");
$(".style-table-tab input[type='text']").val('');
setTimeout(function () {
$('.preloader-circle').show();// or fade, css display however you'd like.
}, 1000);
$.ajax({
type: 'POST',
url: pageUrl+"/LoadCallDetails",
data: '{LeadID: "' + id + '"}',
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: OnValuecall,
failure: function (response) {
alert(response.d);
}
});
}
function OnValuecall(response) {
$(".preloader-circle").hide();
$("#ctl00_ContentPlaceHolder1_lbrfullname").text(response.d.FirstName);
$("#ctl00_ContentPlaceHolder1_lbrphonenumber").text(response.d.MobileNo);
$("#ctl00_ContentPlaceHolder1_lbraddress").text(response.d.Address1);
$("#ctl00_ContentPlaceHolder1_lbrorganization").text(response.d.OrganizationName);
$("#ctl00_ContentPlaceHolder1_lblremail").text(response.d.PrimaryEmail);
}
Web Method:
public static UserAjax3 LoadCallDetails(string LeadID)
{
//System.Threading.Thread.Sleep(3000);
UserAjax3 oUserAjax = new UserAjax3();
//BD_CommonEmail[] ocall = BD_CommonEmail.GetEmailAll(Convert.ToInt32(LeadID)).ToArray();
BD_Leads[] ocall = BD_Leads.getCallDetails(Convert.ToInt32(LeadID)).ToArray();
if (ocall.Length == 1)
{
// oUserAjax.LeadID = oLeads.LeadID.ToString();
oUserAjax.LeadID = ocall[0].LeadID.ToString();
oUserAjax.FirstName = ocall[0].FirstName;
oUserAjax.MobileNo = ocall[0].MobileNo;
oUserAjax.OrganizationName = ocall[0].OrganizationName;
oUserAjax.Address1 = ocall[0].Address1;
oUserAjax.PrimaryEmail = ocall[0].PrimaryEmail;
}
return oUserAjax;
There are many things in question:
Where does "pageUrl" comes from?
You're awaiting a JSON result, but your method seems to return a normal object. Where do you convert to JSON?
Did you try running with a debugger in single-step mode trhough your web method?
Why is your web method static?

Send form data to client side function to retrieve a page title

I'm attempting to pull the title from the metadata of a URL on the client side so it appears in real time (much like pasting a link on FB / Twitter). However I am struggling to load the url from an input and send the data to a function to make it read on console.log without having to submit the form yet.
Jade
form(method='post' action='/submit', class='plans', id='plans')
.form-group
label Do you have a link?
input.form-control(name='link', type='url', required='required', onchange='scrapeMetadata();', onkeyup='this.onchange();', onpaste='this.onchange();', oninput='this.onchange();')
JS
function scrapeMetadata(link) {
var url = link;
console.log(url)
};
Server-side, have the browser send the url via ajax and display that.
Like in this fiddle: https://jsfiddle.net/mo0qa8yk
function getTitle(url) {
try {
return new window.URL(url).host;
} catch(ex) {
console.error(ex);
return 'N/A';
}
}
window.scrapeMetadata = function () {
var url = $('#url').val();
$.ajax({
type: 'GET',
url: '//jsfiddle.net/echo/jsonp/',
data: {
url: url,
title: getTitle(url) //cheat , the server sould return {title:'...'}
},
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: show_response,
error: function(e) {
console.error(e.message);
}
});
};
show_response = function(obj) {
var result = $('#post');
result.html("");
result.append('<li>' + obj.title + '</li>')
};

Dotnetnuke Call ajax from a module

I am now trying to build a dnn module using ajax calls. But there is a jquery error stating
SyntaxError: Unexpected token <
I have tried to work around with ajax "url: " and tried to create a new ascx at the root folder but still showing error 404.
My ajax call is as below
$.ajax({
url: "NewsManagement.ascx/Add",
contentType: "application/json; charset=utf-8",
dataType: "json",
method: "POST",
beforeSend: function () {
},
cache: false,
data: {
title : $('#txt_Title').val(),
news_content : $('#txt_Content').val(),
image : $('#file_Image').val(),
chapter_id : $('#sel_Chapter').val(),
is_draft : $('#chk_Draft').val(),
posted_date : $('#dp_PostDate').val(),
created_by : "",
lastupdate_by : ""
},
success: function (data) {
console.log(data);
if (data == "success") {
console.log(data);
}
else {
initMdlError("SERVER : " + data);
}
},
error: function (data, textStatus, error) {
// ERROR IS BEING CALLED FROM HERE
console.log("JQUERY JAVASCRIPT : " + error);
initMdlError(error);
},
complete: function () {
console.log('complete');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Is there any way to solve the issues?
The problem you're running into is that DNN isn't handling the requested URL properly that you are calling. If you want to call a service URL in DNN you're going to want to setup routes to handle the calls.
namespace Christoc.Com.Modules.SlidePresentation.services
{
public class SlidePresentationRouteMapper : IServiceRouteMapper
{
public void RegisterRoutes(IMapRoute mapRouteManager)
{
mapRouteManager.MapRoute("SlidePresentation", "{controller}.ashx/{action}",
new[] {"Christoc.Com.Modules.SlidePresentation.services"});
}
}
}
In the Controller you can define the methods available
[DnnAuthorize(AllowAnonymous = true)]
public ActionResult ListOfSlides()
{
try
{
var slides = Slide.GetSlides(ActiveModule.TabID, ActiveModule.ModuleID);
return Json(slides, JsonRequestBehavior.AllowGet);
}
catch (Exception exc)
{
DnnLog.Error(exc);
return Json(null, JsonRequestBehavior.AllowGet);
}
}
https://slidepresentation.codeplex.com/SourceControl/latest#DesktopModules/SlidePresentation/services/SlidePresentationController.cs
sample Javascript
//get slides on initialization
this.init = function(element) {
//var data = {}; //removed because we don't need this
//data.moduleId = moduleId; //removed because we don't need this when calling setModuleHeaders
//data.tabId = tabId; //removed because we don't need this
//serviceFramework.getAntiForgeryProperty(); //removed because we don't need this
$.ajax({
type: "POST",
cache: false,
url: baseServicePath + 'ListOfSlides',
//data: data,
//dataType:"json",
beforeSend: serviceFramework.setModuleHeaders
}).done(function(data) {
viewModel.slides = ko.utils.arrayMap(data, function(s) {
return new slide(s);
});
ko.applyBindings(viewModel);
$(element).jmpress();
}).fail(function () {
Console.Log('Sorry failed to load Slides');
});
};
Here's an example module that does this
https://slidepresentation.codeplex.com/
And a user group video I did years ago on this module.
https://www.youtube.com/watch?v=hBqn5TsLUxA

How to post webform with file to webmethod using Jquery/Ajax?

Is this even possible? I have a webform with certain textboxes etc and a file upload element. I am trying to send the data to webmethod using .ajax() method.
It seems to me that it is not possible to send file content to the webmethod in this manner. I am not even able to hit the webmethod.
script type="text/javascript">
var btn;
var span;
$(document).ready(function (e) {
$('#btnsave').on('click', function (event) {
Submit();
event.preventDefault();
});
})
function Submit() {
$.ajax({
type: "POST",
url: "SupplierMst.aspx/RegisterSupplier",
data: "{'file' : " + btoa(document.getElementById("myFile").value) + ",'biddername':" + document.getElementById("txtsuppliername").value + "}",
async: true,
contentType: "application/json; charset=utf-8",
success: function (data, status) {
console.log("CallWM");
alert(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
}
</script>
HTML:
<input id="txtsuppliername" type="text" /><br />
<input type="file" id="myFile">
Code behind :
[WebMethod]
public static string RegisterSupplier(string file, string biddername)
{
// break point not hit
return "a";
}
I have been trying to find solution to this for hours now. Nobody seems to be able help me out on this. Is this even possible using this approch. If not how do I do it? Somebody suggested that I should try to submit entire form instead of passing individual values.
This can be done without any library, by using the JavaScript FileReader API. With it, modern browsers can read the content of the file using JavaScript once it has been selected by the user, and then you could proceed as you were doing (encoding it as a string, and sending it over to the server).
The code would be like this (using the one above as a reference):
// NEW CODE
// set up the FileReader and the variable that will hold the file's content
var reader = new FileReader();
var fileContent = "";
// when the file is passed to the FileReader, store its content in a variable
reader.onload = function(e) {
fileContent = reader.result;
// for testing purposes, show content of the file on console
console.log("The file content is: " + fileContent);
}
// Read the content of the file each time that the user selects one
document.getElementById("myFile").addEventListener("change", function(e) {
var selectedFile = document.getElementById('myFile').files[0];
reader.readAsText(selectedFile);
})
// END NEW CODE
var btn;
var span;
$(document).ready(function (e) {
$('#btnsave').on('click', function (event) {
Submit();
event.preventDefault();
});
})
function Submit() {
$.ajax({
type: "POST",
url: "SupplierMst.aspx/RegisterSupplier",
// changed this line too!
data: {
'file': btoa(fileContent),
'biddername': document.getElementById("txtsuppliername").value
},
async: true,
contentType: "application/json; charset=utf-8",
success: function (data, status) {
console.log("CallWM");
alert(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="txtsuppliername" type="text" /><br />
<input type="file" id="myFile">
You can run the code above, select a file (use a plain text file for testing so it's readable), and check the console to see its content. Then the rest of the code would be the same (I made a slight change to fix the parameters in the AJAX call).
Notice that sending the file like this has limits: if you use the GET method, you'll have a shorter parameter size limit, and with POST it will depend on the server settings... but I guess that you had those limits even for a file.
First of all go to App_Start>>RouteConfig.cs>>settings.AutoRedirectMode = RedirectMode.Off; and then Just Replace your function by my code it will definitely work for you,
Good Luck..
function Submit() {
$.ajax({
type: "POST",
url: "UploadImage.aspx/RegisterSupplier",
data: "{'file' : " + JSON.stringify(document.getElementById("myFile").value) + ",'biddername':" + JSON.stringify(document.getElementById("txtsuppliername").value) + "}",
async: true,
contentType: "application/json; charset=utf-8",
success: function (data, status) {
console.log("CallWM");
alert(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});

Categories