I need to send id my load page and how can ı send id and load another page ?
MY error : Uncaught SyntaxError: Unexpected string
I now this error syntax error but ı am tried everything , ı am new in ajax and mvc
this is my code :
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url : "http://localhost:9000/api/Customer/CustomerList",
success: function (data) {
$("#customerList").DataTable({
pageLength:50,
destroy: true,
"data": data,
"columns": [
{ "data": "CustID"},
{
"data": function send(data) {
return "#using (Html.BeginForm("CustomerList", "Customers", FormMethod.Post, new { target = "_blank" })) {<input type='submit' value=" + data.custID + " />}";
}
}
]
});
},
error: function (data) {
alert("CustomerList");
}
});
The Razor syntax has to be parsed before it works. If you inspect the output of your page, you will never find the "Html.BeginForm" tag/code.
You code shows you are getting the CustomerList using an ajax request. You can simply use the same technique to post the id when the button is clicked.
return "<input type='submit' onClick='sendID(" + data.custID )'/>";
the sendID function could look something like this
function sendID(customerID){
$.ajax({
type: "POST",
data: {custID: customerID},
contentType: "application/json; charset=utf-8",
url : "http://localhost:9000/api/Customer/GetCustomer", // your endpoint url here
success: function (data) {
// do something
});
},
error: function (data) {
alert("Could not send customerid");
}
});
}
This is untested code.
Related
I have this simple ajax method:
$.ajax({
type: 'POST',
url: 'http://localhost:1195/widget/postdata',
datatype: "jsondata",
async: false,
success: function (data) {
alert("ok")
},
error: function (data) {
alert(data.status + ' ' + data.statusText);
}
});
And this simple method in c#:
[HttpPost]
public JsonResult PostData()
{
return Json("1");
}
When I check the inspector console I have "1" in response but my ajax method always goes to error function.
Why is it so?
In your AJAX call it should be dataType: "json" and not datatype: "jsondata". You can refer to the docs
Also use #Url.Action tag in your url call: url: '#Url.Action("postdata", "widget")'
For a small test, I have used the following AJAX call to the same controller method that you have posted and I am getting the correct result:
$(document).ready(function () {
$("#button_1").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url:'#Url.Action("PostData", "Home", null, Request.Url.Scheme)',
datatype: "json",
async: false,
success: function (result) {
alert(result);
},
error: function (error) {
alert(error);
}
});
});
});
</script>
<button id="button_1" value="val_1" name="but1">Check response</button>
Output:
Change the Ajax request to the following :
$.ajax({
type: 'POST',
url: '/widget/postdata',
datatype: "json",
async: false,
success: function (data) {
console.log(data);// to test the response
},
error: function (data) {
alert(data.status + ' ' + data.statusText);
}
});
Always use relative URL instead of full URL that contains the domain name, this will make the deployment easier so you don't have to change the URls when going live
I've found a small problem in sending just plain text(string) via ajax compared to sending an json object.
I have currently this setup working
(cs)html
<label for="search">
<i class="fa fa-search" onclick="sendtoC()"></i>
<input type="search" id="search" placeholder="Sök här..." autofocus; />
<input type="button" id="SÖK" value="SÖK" onclick="sendtoC()" />
Script
<script>
var invalue;
var input = document.getElementById("search");
input.addEventListener("keyup", function go (event) {
if (event.keyCode === 13) {
invalue = document.getElementById("search").value;
sendtoC(invalue);
}
});
function sendtoC() {
$.ajax({
url: "/Home/SearchResults",
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: { input: invalue },
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
}
and current controller
public ActionResult SearchResults(string input)
{
Data.gsPersonLista = db.GetPerson(input);
return Json(new { success = true, message = input }, JsonRequestBehavior.AllowGet);
}
I would like to just send a straight string to the controller and i tried this Script
function sendtoC() {
$.ajax({
url: "/Home/SearchResults",
dataType: "text",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: invalue ,
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}});}
with this Controller
public ActionResult SearchResults(string input)
{
Data.gsPersonLista = db.GetPerson(input);
return View(input);
}
however this didn't work, the input string was shown to get value of null and ajax gave error. I currently have no idea of how to fix this nor what gives the error. If someone could Point me in the right direction I would appreciate it
You can simply use the $.get function here and secondly you should use the Ùrl.Action helper for getting the url against the controller action method, as the magic strings would cause issues in deployments where the application might be deployed in sub-directories and in those case the url becomes wrong :
$.get('#Url.Action("SearchResults","Home")?input='+invalue , function (data) {
if (data.success) {
alert(data.message);
}
});
You can easily pass it as a request parameter, since you've also set the type to "GET".
url: "/Home/SearchResults?input="+invalue
You also have to remove the data attribute. Let me know if it helps.
UPDATED ANSWER
datatype is what you are expecting to return from the server. Content type is what you are sending. so to return a view change datatype to htmL.
dataType: 'html',
the problem is that when you call the function sendtoC you are not receiving any parameters in the function. Change the function to accept a parameter.
var invalue;
var input = document.getElementById("search");
input.addEventListener("keyup", function go (event) {
if (event.keyCode === 13) {
invalue = document.getElementById("search").value;
sendtoC(invalue);
}
});
function sendtoC(invalue ) {
$.ajax({
url: "/Home/SearchResults",
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: { input: invalue },
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
}
I have to call a REST url for example : https://{baseurl}/employees/taxvalidation/. The Request type is JSON, but I'am always get the error Alert. I can't figure out what is the wrong in my code. I am using JQuery
The Supported HTTP Method is : PUT (HTTP PUT with correct request needs to be made) and also i need to pass a API key: XXXXX-XXXXX-XXXXX-XXXXX as request Header.
I have just have two mandatory fields in web page Employee name and Employee Tax.
I have tried the below using JQuery Ajax call.
Request Body Sample:
"name": "Company XYZ", /* mandatory */
"TAX": "*********", /* mandatory */
"taxType": "U", /* Could be E, S, or U */
"address": "2501 Boilermaker road", /* optional */
"citystatezip":"Lapalma ca 76567", /* optional */
"country": "US", //optional
"checks" : "DT",`enter code here`
"details": "DT"`enter code here` //optional
$(function() {
$("#btnSubmit").click(function() {
alert("Hi JQuery");
var URL = "https://api.dev.amx-city.com/tesmdm/dev/tesmdm/empcatalog/partners/taxvalidation/";
$.ajax({
url: URL,
headers : {
'AMX-API-KEY': '487b9474-27a6-4d21-8eda-c3a2a14e4ebe'
},
type: 'POST',
data: {
name: 'Employeename',
tin: '79847324987',
tinType: 'U'
},
dataType: 'json',
success: function(result) {
alert(result);
},
error: function (restul) {
alert(result);
}
});
});
});
when i try to hit the button the debugging is stopped till Alert, after that i don't see the URL is hitting. Let me know if i am doing any wrong?
I am able to get the response now. Below is the working script
$.ajax({
url: URL,
type: "PUT",
headers: {
'AXT-API-KEY': '48776474-26a6-4d21-8eda-c3a2a14e4ebe'
},
data: JSON.stringify({"name": "SupplierName, LLC","tin": "522323454","tinType": "U","checks": "DT"
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr);
alert(thrownError);
}
});
It worked when i use the key in beforeSend function. But i am not sure the difference.
beforeSend: function (xhr) {
xhr.setRequestHeader("AXT-API-KEY': '48776474-26a6-4d21-8eda-c3a2a14e4ebe");
In ASP.NET MVC I was using this script to call a method in controller:
<script>
$.ajax({
url: '#Url.Action("getBookedByUser", "Home")',
data: "2",
dataType: "html",
success: function (data) {
$('#someElement').html(data); // add the returned html to the DOM
console.log(data);
},
});
</script>
and this is the method I call:
public async Task getBookedByUser(string id)
{
BenchesService benchService = new BenchesService();
List<Bench> obj = await benchService.getLastBenchByUser(id);
userBench = obj.ElementAt(0);
}
My problem is that id in my controller method is null. It doesn't assume the value "2" as I intend.
Any idea why?
You're almost there. You need to setup the JSON to include your id property:
$.ajax({
url: '#Url.Action("getBookedByUser", "Home")',
data: { id: '2' },
dataType: "html",
success: function (data) {
$('#someElement').html(data); // add the returned html to the DOM
console.log(data);
},
});
Im having the following ajax cal in my JS file in Durundal ,
var dataJSON ={ID : "jo"};
self.js = $.ajax({
type: "POST",
dataType: text,
url: "http://localhost:53081/api/File",
data: JSON.stringify(dataJSON),
error: function (xhr, status, error) {
alert(error);
},
success: function (json) {
alert("Data Returned: " + JSON.stringify(json));
}
});
and my REST api is
[HttpPost]
public string upload(string ID)
{
string givenId = ID;
return givenId;
}
but when i call thsi methos im simply getting error alert . what went wrong
update
i have updated my code but now im getting Not found error
Change string to Text:
self.js = $.ajax({
type: "POST",
dataType: **Text**,
url: "url",
data: JSON.stringify(dataJSON),
error: function (xhr, status, error) {
alert(status);
},
success: function (json) {
alert("Data Returned: " + JSON.stringify(json));
}
});
click here for list of datatype and there representation.
You may need to change the name of the method to be PostFile. I had issues getting this to work without having the proper naming convention, even though I had the [HttpPost] attribute at the beginning of the method.
Also: try changing your dataType to "json" and adding the content type:
dataType: "json",
contentType: "application/json"