No response in html page call to web api - javascript

i am trying to call c# web api but there is no response in html page but i getting response in cshtml
WEB API CODE
namespace MvcApplication3.Controllers
{
public class StoreController : Controller
{
public string Get2()
{
return "response data";
}
}
}
HTML CODE
<html>
<head>
<script src="jquery-1.8.2.js">
</script>
<!--<script src="jquery-1.8.2.min.js">
</script>-->
<script type="text/javascript">
$(function () {
$(document).ready(function () {
$('body').on('click', '.test', function (e) {
alert('a');
jQuery.support.cors = true;
$.ajax({
// url: 'http://localhost:3595/api/values/5',
url: 'http://localhost:1152/Store/Get2',
type: 'GET',
dataType: "Jsonp",
success: function (data) {
alert(data);
}
});
});
});
});
</script>
<title>
</title>
</head>
<body>
<input type="button" value="submit" class="test"/>
</body>
</html>

Related

500 Internal Server Error when using Ajax in Laravel

I'm trying to use ajax call in my blade view and post ajax data to controller to insert to database.
Here is my ajax:
<!DOCTYPE html>
<html>
<head>
<title>FormBuilder Editor</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="https://formbuilder.online/assets/js/form-builder.min.js"></script>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
<div id="fb-editor"></div>
<div id="saveToDatabase">
<button id="saveBtn" type="button">Save To Database</button>
</div>
</body>
<script>
var formBuilder = $('#fb-editor').formBuilder();
$("#saveBtn").click(function() {
var mFormData = formBuilder.actions.getData(); //JSON data return
console.log(mFormData);
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "POST",
url: "save",
data: {
"mFormData":mFormData
}
}).done(function (msg) {
alert("Data saved!" + msg);
});
});
</script>
</html>
And here is my controller:
public function saveToDb(Request $request) {
$data = $request->all();
if($data) {
Form::insertData($data);
}
return view('welcome');
}
And this is my insert function in Model:
public function insertData($formData) {
DB::EnableQueryLog();
$sql = DB::table('form')->insert(['formKey' => 'testForm2', 'formData' => $formData]);
return $sql;
}
When I click on button save, this is error in Network XHR:
How I can fix this? Thank you very much!
you are calling the inserData statically. so it should be
public static function insertData($formData) {
DB::EnableQueryLog();
$sql = DB::table('form')->insert(['formKey' => 'testForm2', 'formData' => $formData]);
return $sql;
}
Replace this line:
Form::insertData($data);
with this:
app()->make(From::class)->insertData($data);
Or inject the Form model instance in the constructor if you prefer.
However, the way you are inserting is not how models are meant to be inserted.

JS changes cursor only when js function is completed

I have the following code
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
</head>
<body style="background-color:yellow;width:100%;height:100%;">
test
<script>
function test() {
$("body").css("cursor","wait"); //cursor must be changed here
$.ajax(...);
}
</script>
</body>
</html>
The problem with this code is that cursor changes from default to wait in browser only when function test() is completed, but I need it to change in certain point of function. I tried in FF 58 on Ubuntu 14 and in Opera in Windows 7. I've read many posts about it and tried also this solution
$(document).ajaxStart(function() {
$(document.body).css({'cursor' : 'wait'});
}).ajaxStop(function() {
//$(document.body).css({'cursor' : 'default'});
});
but without success. How to fix it? Any ideas?
I found the answer. I had in my ajax async:false -
$.ajax({ ...
async: false,
...
});
When I changed to
$.ajax({ ...
async: true,
...
});
everything started to work as expected.
$(document).ajaxStart(function (event, jqxhr, settings) {
$(document.body).css({ 'cursor': 'wait' });
});
$(document).ajaxComplete(function (event, jqxhr, settings) {
$(document.body).css({ 'cursor': 'normal' });
});
$(document).ajaxError(function (event, request, settings) {
$(document.body).css({ 'cursor': 'normal' });
});
function AjaxCall() {
$.ajax({
type: "POST",
url: '/home/AjaxURL',
contentType: "application/json; charset=utf-8",
global: true,// this makes sure ajax set up ajaxStart/ajaxComplete/ajaxerror will triggered
dataType: "json",
success: function () { },
error: function () { }
});
}
$(document).ready(function () {
AjaxCall();
});
Note- Setting the cursor to document.body as you did means it will only apply in document and did not apply in other dom elements like anchor, textbox etc
You can use before send like this:
$.ajax({
beforeSend: function(){
// Handle the beforeSend event
},
complete: function(){
// Handle the complete event
}
// ......`enter code here`
});
OR use when and timeout:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function ajaxready() {
setTimeout(function() {
$.ajax({
url: "https://www.w3schools.com/jquery/demo_test.txt",
beforesend: function() {},
success: function(result) {
$("#div1").html(result);
$("body").css("cursor", "");
}
});
}, 500);
}
function loading() {
$("body").css("cursor", "wait"); //cursor must be changed here
}
$(document).ready(function() {
$("button").click(function() {
$.when(loading()).done(function() {
ajaxready();
});
});
});
</script>
<style>
button {
cursor: inherit
}
</style>
</head>
<body>
<div id="div1">
<h2>Let jQuery AJAX Change This Text</h2>
</div>
<span></span>
<button>Get External Content</button>
</body>
</html>

Json object display in html

Hey guys I am new with this json syntax and I have one problem.
I made function that gets data from remote server in json like this:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-3.1.0.min.js"></script>
<script type="text/javascript">
function getStates(value) {
var data = {
q: value
}
$.ajax({
url: 'https://something.hr/api/search',
method: 'GET',
headers: {'Accept': 'application/json'},
data: data
}).done(function(data) {
//do something with data I returned to you
console.log("success")
console.log(data)
}).fail(function(data) {
//doSomethingWith the data I returned to you
console.log("fail")
console.log(data)
});
};
</script>
</head>
<body>
<input type="text" onkeyup="getStates(this.value)" >
<br>
<script>
</script>
</body>
</html>
My problem is that I know how to get object in console log, but i wish to get that object in html, like in some box, than click on it and open his data(name, id, adress etc.)
var httpManager = (function() {
var getData = function(value) {
$.ajax({
url: 'https://api.github.com/users/zixxtrth',
method: 'GET'
}).done(function(data) {
//do something with data I returned to you
jQuery('#avatar').attr('src', data.avatar_url);
jQuery('#name').html(data.name);
jQuery('#username').html(data.login);
}).fail(function(data) {
//doSomethingWith the data I returned to you
alert('No Data');
});
};
return {
getData: getData()
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<img src='' id='avatar' width='200' height='200' />
<h1 id='name'></h1>
<h2 id='username'></h2>

ajax request to Microsoft Emotion API in javascript

I am trying to try the microsoft emotion api. I am running a simple python web server with CORS enabled. Below is my server python file with which I start the server:
python-server.py
#! /usr/bin/env python2
from SimpleHTTPServer import SimpleHTTPRequestHandler
import BaseHTTPServer
class CORSRequestHandler (SimpleHTTPRequestHandler):
def end_headers (self):
self.send_header('Access-Control-Allow-Origin', '*')
SimpleHTTPRequestHandler.end_headers(self)
if __name__ == '__main__':
BaseHTTPServer.test(CORSRequestHandler, BaseHTTPServer.HTTPServer)
I have an index.html file in which I am sending the http request:
index.html
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key",JSON.stringify({"my-key"}));
},
type: "POST",
// Request body
data: JSON.stringify({"url": "http://tinyurl.com/2g9mqh"}),
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
After about 30 seconds I get the connection refused response. The http request code was taken from the emotion api's page I linked earlier. I wonder whether I need a real server or is there a mistake in the code? Thanks.
The JSON needs to be sent out as a string. So change your body specification to:
data: "{\"url\": \"http://...\"}"
Please use the code below(replace your-key), just save it as a .html and open it in the browser it shut work(without any server). If it works then try it in your python server.
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","your-key");
},
type: "POST",
// Request body
data: {"url": "https://oxfordportal.blob.core.windows.net/emotion/recognition1.jpg"},
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Face API</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj) {
// Request headers
xhrObj.setRequestHeader("Content-Type", "application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key",
"");
},
type: "POST",
// Request body
data: JSON.stringify({
"url": "http://i1.mirror.co.uk/incoming/article6395000.ece/ALTERNATES/s1200/MAIN-David-Beckham-next-James-Bond.jpg"
}),
})
.done(function(data) {
console.log(data);
})
.fail(function(e) {
console.log(e);
});
});
</script>
</body>
</html>

Why is this html not working

I have this short piece of code:
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<script type="text/javascript">
$("#term").autocomplete({
source: function(request, response) {
$.ajax({
url: 'http://query.yahooapis.com/v1/public/yql',
dataType: 'JSONP',
data: {
format: 'json',
q: 'select * from xml where url="http://google.com/complete/search?output=toolbar&q=' + encodeURIComponent(request.term) + '"'
},
success: function(data) {
response($.map(data.query.results.toplevel.CompleteSuggestion, function(item) {
return { label: item.suggestion.data, value: item.suggestion.data };
}));
}
});
}
});
</script>
</head>
<body>
<label for="term">Search term: </label>
<input id="term" />
</body>
</html>
It is working good online at JsBin: JsBin preview
However when I copy code to desktop so I can work with it it doesn't work (it used to work however) What am I doing wrong?? Why is this not working except online??
try wrapping the javascript code inside the ready handler, jsbin does it automatically
$(document).ready(function(){
//your code here
});
or the short cut
$(function(){
//your code here
});
this wil execute the script once the DOM has finished loading, or as an alternative you can place the javascript at the end of the document so it is executed when the DOM has loaded
You are referring to the input element before it has been created. Perform your autocompletion initialization after the DOM elements have been set up.
...
<script type="text/javascript">
$(function() {
$("#term").autocomplete({
source: function(request, response) {
$.ajax({
url: 'http://query.yahooapis.com/v1/public/yql',
dataType: 'JSONP',
data: {
format: 'json',
q: 'select * from xml where url="http://google.com/complete/search?output=toolbar&q=' + encodeURIComponent(request.term) + '"'
},
success: function(data) {
response($.map(data.query.results.toplevel.CompleteSuggestion, function(item) {
return {
label: item.suggestion.data,
value: item.suggestion.data
};
}));
}
});
}
});
});
</script>
...

Categories

Resources