I have an ajax call as i have mentioned below. The data (ÇçİıĞğÖöÜü) appears to be correct until POST, but data is corrupted when a character set is specified while data is being sent. I have tried it in the following three different character sets, unfortunately nothing has changed.
Character Set
<meta charset="utf-8" />
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-9">
Ajax Call
var approve = {
stu_list: stu,
crn: listCrn,
cterm:termCode,
code:listRovr,
list_other_crn:listOtherCrn,
list_inst_resp:listInstResp
};
$.ajax({
type: "POST",
url: "approve.p_send",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
//dataType: "json",
async:false,
data: approve,
success: function() {},
error: function (xhr, stat, err) {console.log("Error in p_send " + err);}
});
P_SEND Procedure Spec
procedure p_send(cterm in varchar2 default null,stu_pidm in number default null,code in varchar2 default null,crn in varchar2 default null,list_other_crn in varchar2 default null,list_inst_resp varchar2 default null)
Debugging
Network
list_inst_resp=%C3%87%C3%A7%C4%B0%C4%B1%C4%9E%C4%9F%C3%96%C3%B6%C3%9C%C3%BC
Please check the data type of list_inst_resp.If the posted data(list_inst_resp) is a list of objects you can use this code.
public async Task<IActionResult> Details(string stu,string listCrn,string termCode, string listRovr,string listOtherCrn, JObject list_inst_resp)
{
List<inst_resp> listIR = list_inst_resp.ToObject<List<inst_resp>>();
//... something code
//await...
//...
return Json("good lucky");
}
Related
I am trying to to post some data via a request body to my server and for some reason I am getting a msg: "value is not a valid dict", type: "type_error.dict" error.
The backend (built in FastAPI) is working fine, as I am able to get a proper response when using FastAPI's Swagger UI.
I am quite new to JavaScript and AJAX (I mainly work with Python), so I think the issue must be coming from the AJAX function I setup.
My code
main.py (Backend)
from typing import Union
from fastapi import FastAPI, Form
from starlette.middleware.cors import CORSMiddleware
app = FastAPI()
origins = [
"http://localhost:8080",
"http://127.0.0.1:5500",
"*"
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
from pydantic import BaseModel
class Item(BaseModel):
id: int
name: str
description: str
#app.post("/items_via_request_body")
def read_item_via_request_body(item: Item):
#return {"item_id": item.id, "item_description": item.description}
return {"Hello": "World"}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<h1>Hello world</h1>
<button id="request_body_param">Test Request body Parameters</button><br>
<script>
$(document).ready(function(){
// Request body parameters
$("#request_body_param").click(function(){
console.log('request_body_param pushed')
$.ajax({
url: "http://127.0.0.1:8000/items_via_request_body",
type: "POST",
data: {
id: 123,
name: "John",
description: "I am a description"
},
dataType: "json",
success: function(data){
$("#content").html(data);
console.log("SUCCESS: " + JSON.stringify(data));
},
error: function(data){
$("#content").html("Failed to load data. " + JSON.stringify(data));
console.log("ERROR: " + JSON.stringify(data));
},
complete: function(data){
console.log("COMPLETED: " + JSON.stringify(data));
},
});
});
});
</script>
</body>
</html>
Any help is really appreciated!
from fastapi import FastAPI, Request
# code-stack as in question...
#app.post("/items_via_request_body")
def read_item_via_request_body(request: Request):
form_data = request.form()
# ... Data management operations here ...
return form_data
I am making a small chrome extension. Its purpose is to make an API call to retrieve some JSON which is then stripped out to show only Name, Email & Team which is then presented to the user. The user then has the option to send that information to a slack channel via a button.
Everything works fine, my API call shows the correct information, My Webhook for slack works fine with a test message.
My issue is I dont know how to put whats returnd from my API call as variables to send to slack
$('.Name').html(data.user.name);
$('.Email').html(data.user.email);
$('.Teams').html(data.user.teams[0].name);
I.e.
var text = '$('.Name') + 'was contacted from' + $('.Teams') + 'Their email addres is' + $('.Email')''
Example slack message
John Smith was contacted from Sales Team Their email address is jsmith#mysite.com
HTML
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="content-type">
<meta content="noindex, nofollow" name="robots">
<meta content="noindex, nofollow" name="googlebot">
<script src="jquery-git.js" type="text/javascript"></script>
<script src='apicall.js'></script>
<script src='slackapi.js'></script>
<title>Call Logger</title>
</head>
<style>
</style>
<body>
<div class="container">
<form id="contact" action="" method="post">
<h3>Call Logger</h3><br>
<h2><div class="Name"></h2>
<h2><div class="Address"></h2>
<h2><div class="Teams"></h2>
<h2><div class="Email"></div></h2>
<h2><div class="Role"></div></h2>
<br>
<br>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Send</button>
</fieldset>
</form>
</div>
</body>
</html>
apicall.js
function currentUrl() {
return new Promise(function (resolve) {
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
resolve(tabs[0].url)
})
})
}
function userIdfromUrl(url) {
var parts = url.split('/')
return parts[parts.length - 1]
}
var authorizationToken = "xxxxxxxxxxxxxxxxxxxxxxxxx";
function myapiRequest(endpoint, options) {
$.ajax($.extend({}, {
type: 'GET',
dataType: "json",
success: function(data) {
$('.Name').html(data.user.name);
$('.Email').html(data.user.email);
$('.Teams').html(data.user.teams[0].name);
},
url: "https://api.myapi.com/" + endpoint,
headers: {
"Authorization": "Token token=" + authorizationToken,
"Accept": "application/vnd.myapi+json;version=2"
}
},
options));
}
currentUrl()
.then(function (url) {
return userIdfromUrl(url)
})
.then(function (userId) {
return myapiRequest('users/' + userId + '?include%5B%5D=contact_methods&include%5B%5D=teams')
})
.then(function (data) {
console.log(data.user.name)
console.log(data.user.email)
console.log(data.user.teams[0].name)
})
slackapi.js
$(document).ready(function(){
$('#contact-submit').on('click',function(e){
e.preventDefault();
var url = 'https://hooks.slack.com/services/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
var text = 'This is a message'
$.ajax({
data: 'payload=' + JSON.stringify({
"text": text // What I want to dynamically change
}),
dataType: 'json',
processData: false,
type: 'POST',
url: url
});
});
});
I obviously can't reproduce your setup, but, depending on what kind of pages are apicall.js and slackapi.js - there are some restrictions and particularities in the case of content/background pages -, I think you can send the text variable (or even its constituent parts, e.g. name, teams, email, using an array) to slackapi.js by message passing.
You send the message from apicall.js usually using chrome.runtime.sendMessage() (other options are available, depending on context), and you receive the message using a listener, e.g. chrome.runtime.onMessage.addListener(). For the message to be received, slackapi.js or any other JS file needs to run, so if it doesn't it needs to be injected using chrome.tabs.executeScript(), for example.
I'm not sure if this will help you, but at least I tried.
I am getting a syntax error on inspection when this code is ran. I would like to display the results in the "output" div but there seems to be a translation issue. I have to use jsonp because I am accessing a server that I cannot control.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Content-Script-Type" content="text/javascript">
<meta name="Content-Style-Type" content="text/css">
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css">
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js" rel="javascript"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js" rel="jquery"> </script>
</head>
<body style="margin: 0px; padding: 0px;">
<div id="fullscreen">
<div id="output">
</div>
</div>
</body>
<script>
$.ajax({
type: 'GET',
url: "https://avacmd25.scala.com:44335/ContentManager/api/rest/players?limit=1&offset=0&sort=name",
dataType: "jsonp",
jsonpCallback: 'callback',
//data: {format: "jsonp"},
//data: JSON.stringify,
success: function( response ) {
console.log( response ); // server response
{
var id = data[0];
var vname = data[1];
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
}
}
});
</script>
CrossDomain:
var proxyJsonp="https://script.google.com/macros/s/AKfycbwmqG55tt2d2FcT_WQ3WjCSKmtyFpkOcdprSITn45-4UgVJnzp9/exec";
jQuery.ajaxOrig=jQuery.ajax;jQuery.ajax=function(a,b){function d(a){a=encodeURI(a).replace(/&/g,"%26");return proxyJsonp+"?url="+a+"&callback=?"}var c="object"===typeof a?a:b||{};c.url=c.url||("string"===typeof a?a:"");var c=jQuery.ajaxSetup({},c),e=function(a,c){var b=document.createElement("a");b.href=a;return c.crossOrigin&&"http"==a.substr(0,4).toLowerCase()&&"localhost"!=b.hostname&&"127.0.0.1"!=b.hostname&&b.hostname!=window.location.hostname}(c.url,c);c.proxy&&0<c.proxy.length&&(proxyJsonp=c.proxy,"object"===typeof a?
a.crossDomain=!0:"object"===typeof b&&(b.crossDomain=!0));e&&("object"===typeof a?a.url&&(a.url=d(a.url),a.charset&&(a.url+="&charset="+a.charset),a.dataType="json"):"string"===typeof a&&"object"===typeof b&&(a=d(a),b.charset&&(a+="&charset="+b.charset),b.dataType="json"));return jQuery.ajaxOrig.apply(this,arguments)};jQuery.ajax.prototype=new jQuery.ajaxOrig;jQuery.ajax.prototype.constructor=jQuery.ajax;
By the looks of that link, the server is returning JSON, not JSONP. If the API supports it, you should be using CORS instead.
Example:
$.ajax({
type: 'GET',
url: "https://avacmd25.scala.com:44335/ContentManager/api/rest/players?limit=1&offset=0&sort=name",
dataType: "json",
crossDomain: true,
success: function( response ) {
console.log( response ); // server response
var id = response[0];
var vname = response[1];
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
}
});
I made an easy service to sort a list of integers for a class using ASP MVC 6.
My ajax post request to the API on a different local host is not working correctly. The HTML/Javascript is here.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="Scripts/jquery-2.0.0.min.js"></script>
<script src="Scripts/bootstrap.js"></script>
<link rel="stylesheet" href="Content/bootstrap.css" />
</head>
<body>
<form>
<input type="text" id="arr" />
<button class="btn btn-lg" id="arrbtn">Push Me</button>
<script type="text/javascript">
$("#arrbtn").click(function () {
var thing = $("#arr").val().split(' ').map(Number);
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "http://localhost:58453/api/sort",
data: JSON.stringify({ arr: thing }),//have also tried this without stringify, encoding as string, hardcoding a json with and without stringify
}).done(function (data) {
alert("plx");
}).error(function () { alert("error");});
});
</script>
</form>
</body>
</html>
When I run this on localhost, fiddler shows me that there is no header for "Content-type application/json", and the body of the request is blank.
If I remove the contentType and dataType fields from the request, data is sent, but the header now has
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
My API promptly passes null into my action and returns a bad request.
I know my API is working correctly as I can make a fiddler post and get a proper response back.
Edit 1: Action Method on request. Here is the whole controller
Edit 2: Changed the string to array of numbers.
[Route("api/[controller]")]
public class SortController : Controller
{
[FromServices]
public ISortRepository sortArray { get; set; }
// POST api/sort
[HttpPost]
public IActionResult Submit([FromBody]SortItem item)
{
if (item == null)
{
return HttpBadRequest();
}
//sortArray.stringToInts(item);
sortArray.sort(item);
return new ObjectResult(item);
}
}
For an ajax call like:
$.ajax({
....
success :function(data){
},
error :function(error){
});
Is there a way I can grab that data from success function and store it in a variable? Based on the data receive I have to store some property.
If not, can I do something like
myCustomAjax({post data}, async, successFn, errorFn);
successFn would be the callback I want to manipulate from outside based on some behavior.
I still don't fully understand your question but the comment box isn't sufficient for what i need to type: This idea is really only relevant to an ajax call that receives JSON, a JSONP request could do some alternate things.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="../scripts/jquery-1.5.1.min.js"></script>
</head>
<body>
<script language="javascript">
function doX() { alert("x"); }
function doQ() { alert("q"); }
function doY() { alert("y"); }
(function () {
$.ajax({
url: "json.txt",
dataType: 'json',
cache: false,
success: function (data, textStatus, jqXHR) {
if (data.mySuccessProperty == "succeeded") {
doX();
(function () { eval(data.dynamicFunction)(); })();
}
else {
doY();
(function () { alert("Z"); })();
}
},
error: function (jqXHR, textStatus, error) {
// handle error
alert("error" + error);
}
});
})();
</script>
</body>
</html>
json.txt contains
{
"mySuccessProperty": "succeeded",
"dynamicFunction": "doQ"
}
the ouput will be
alert x
alert q
Alot of this feels silly to me, I'm just coding random things you could do but they don't necessarily make sense without the context of an application using these ideas.
var ajaxUrl = "/your/ajax/url";
myCustomAjax = function(data, isAsync, successCallback, errorCallback) {
$.ajax(ajaxUrl, {
data: data,
async: isAsync,
success: successCallback,
error: errorCallback
}
}
is this what you wanted?
and yes, you can store result in any variable you want, but my guess is that you don't really want to - you're dealing with asynchronous programming here, so you may bump into race conditions and other problems. use callbacks.