I am new to React and Ajax and I am trying to make an api call to an Azure model but it seems to throw an error. For the time being I am using static data.
My code looks like this
example.js
var RecommendationInfo = React.createClass({
getInitialState: function() {
return {data: {}};
},
loadRecommendationInfo: function(e){
$.ajax({
async: true,
crossDomain: true,
url: 'http://ussouthcentral.services.azureml.net/workspaces/150de299226b41698270c2ddfbc6794b/services/604f4a58cc5e44daab413ecd3dd4dd5b/execute?api-version=2.0&format=swagger',
method: 'POST',
headers: {
'content-type': 'application/json',
'authorization': 'Bearer dSvR98YJPxUvGNvmVWaXcFIIBYmIA1ieSrDLde6qgpvUfV1uxq4/pT5EnfuTse1zwK1VHoOb4xg6gVVGmyFQsw=='
},
data:
{
'USER': 'user2',
'PARENT_SKU': '1',
'RATING': '1',
},
success: function(result) {
this.setState({data: result});
console.log(result);
}.bind(this)
});
},
render: function() {
return (
<div>
<h2><button onClick={this.loadRecommendationInfo} > Click me</button></h2>
</div>
);
}
});
ReactDOM.render(
<RecommendationInfo />,
document.getElementById('container')
);
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="../shared/css/base.css" />
</head>
<body>
<div id="container">
<p>
If you can see this, React is not working right. This is probably because you're viewing
this on your file system instead of a web server. Try running
<pre>
python -m SimpleHTTPServer
</pre>
and going to http://localhost:8000/ .
</p>
</div>
<script src="../../build/react.js"> </script>
<script src="../../build/react-dom.js"> </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"> </script>
<script type="text/babel" src="example.js"> </script>
</body>
</html>
There is an error which is coming from the above code in chrome
ERR_CONNECTION_TIME_OUT. I am not sure why is this happening. Please help.
Related
I have a button subscribe that should submit a post request via ajax to my controller for insertion to my table.
This is how my view look like:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8">
<div class="flash-message"></div>
<div class="card">
<div class="card-header">
<div class="level">
<span class="flex">{{$thread->creator->name}} posted:
{{$thread->title}}
</span>
#if(auth()->check())
#if($subscription)
<button class="btn btn-secondary" id="unsubscribe">Unsubscribe</button>
#else
<button class="btn btn-danger" id="subscribe">Subscribe</button>
#endif
#endif
#can('update',$thread)
Edit Thread
<form action="{{$thread->path()}}" method="POST">
#csrf
#method('delete')
<button class="btn btn-link" type="submit">Delete Thread</button>
</form>
#endcan
</div>
</div>
<div class="card-body">
{{$thread->body}}
</div>
</div>
..............
My app.blade:
<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Scripts -->
<script src="{{ asset('js/app.js') }}" defer></script>
<!--jQuery/share.js -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha256-4+XzXVhsDmqanXGHaHvgh1gMQKX40OUvDEBTu8JcmNs=" crossorigin="anonymous"></script>
<script src="{{ asset('js/share.js') }}"></script>
<!-- Fonts -->
<link rel="dns-prefetch" href="//fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
<style>
body{
padding-bottom:100px;
}
.level{
display: flex;
align-items: center;
}
.flex{
flex: 1;
}
</style>
</head>
<body>
<div id="app">
#include('layouts.nav')
<main class="py-4">
#yield('content')
</main>
<flash message="{{session('flash')}}"></flash>
</div>
</body>
<style>
.btn-width{
min-width: 70px;
}
</style>
</html>
The code calling the button:
<script type="application/javascript">
$(document).ready(function(){
$('#subscribe').click(function(e){
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{route('subscription.store')}}",
method:'POST',
data: {
thread_id: "{{$thread->id}}",
},
success:function(response){
$('div.flash-message').html(response);
},
error:function(error){
console.log(error);
}
});
});
});
From what I could tell, there is no other element that shares the same id as my button. And, my button is not in a form submit so it should not be called twice. Inspecting dev tools shows no error and in the network tab, two requests are called identically with the same initiator.
So, I am kinda wondering why would this happen. Shouldn't an ajax post request submit the request once only?
I would really like to get to the bottom of this as most of the other similar issues have calling the submit twice while my code is only supposed to call it once. Instead, it makes two insertion to my db.
What else can I do to figure out the root cause of the issue?
Is it possible that your javascript is being loaded twice somehow? That would attach two identical listeners and send the request twice on a single click. If you put a console.log inside of the event handler, do you see that twice as well?
Also, apparently, .click adds a separate event listener for each element that matches the selector passed to the jQuery object, whereas .on only adds a single one.. What would happen if you did this instead?
$(document).ready(function () {
$("#subscribe").on("click", function(e) {
e.preventDefault();
$.ajaxSetup({
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
},
});
$.ajax({
url: "{{route('subscription.store')}}",
method: "POST",
data: {
thread_id: "{{$thread->id}}",
},
success: function (response) {
$("div.flash-message").html(response);
},
error: function (error) {
console.log(error);
},
});
});
});
You can try these options:
(1) Use async: false in your ajax call to stop the execution of other code until you receive response of the current ajax call.
$('#subscribe').click(function(e) {
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{route('subscription.store')}}",
method: 'POST',
async: false,
data: {
thread_id: "{{$thread->id}}",
},
success: function(response) {
$('div.flash-message').html(response);
},
error: function(error) {
console.log(error);
}
});
});
OR
(2) You can use stopPropagation() method of the Event interface which prevents further propagation of the current event in the capturing and bubbling phases.
$('#subscribe').click(function(e) {
e.preventDefault();
e.stopPropagation();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{route('subscription.store')}}",
method: 'POST',
async: false,
data: {
thread_id: "{{$thread->id}}",
},
success: function(response) {
$('div.flash-message').html(response);
},
error: function(error) {
console.log(error);
}
});
});
OR
(3) Use a variable that stores the status of the request.
var isLoading = false;
$(document).ready(function() {
$('#subscribe').click(function(e) {
if (!isLoading ) {
isLoading = true; //make true when request starts
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{route('subscription.store')}}",
method: 'POST',
data: {
thread_id: "{{$thread->id}}",
},
success: function(response) {
$('div.flash-message').html(response);
isLoading = false; //make false when response is received
},
error: function(error) {
console.log(error);
isLoading = false; //make false when error is received
}
});
}
});
});
Have you tried giving return false? like this:
$(document).ready(function(){
let subscribeClick = function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{route('subscription.store')}}",
method:'POST',
data: {
thread_id: "{{$thread->id}}",
},
success:function(response){
$('div.flash-message').html(response);
},
error:function(error){
console.log(error);
}
});
return false;
}
$('#subscribe').click(function(e){
e.preventDefault();
e.stopImmediatePropagation();
subscribeClick();
});
});
you are calling you function twice one in document ready and second on button click remover document
I'm receiving a data from AJAX response and I'm trying to update a jQuery plugin with that value in the success callback:
$.ajax({
url: '/some/url',
type: 'GET',
dataType: 'json',
success: (data) => {
$(".my-rating").starRating('setRating', data.rating);
}
});
I'm using the star-rating-svg plugin to show ratigns (http://nashio.github.io/star-rating-svg/demo/). The problem is that I'm having an error:
Uncaught TypeError: $(...).starRating is not a function
However, this function works perfectly when is called outside AJAX callback. Do you know how to deal with this?
EDIT:
Larger piece of my code:
show.ejs
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="/star-svg/src/jquery.star-rating-svg.js"></script>
<link rel="stylesheet" type="text/css" href="/star-svg/src/css/star-rating-svg.css">
</head>
<body>
<div class="my-rating mb-1"></div>
<script>
function getUserRating() {
$.ajax({
url: '/some/url/rating',
type: 'GET',
dataType: 'json',
success: () => {
$(".my-rating").starRating('setRating', data.rating);
}
});
}
function webpageReady() {
if($(".my-rating").is(':visible')) {
$(".my-rating").starRating({
starSize: 20,
disableAfterRate: false,
callback: function(currentRating, $el){
$.ajax({
url: '/some/url/setRating',
type: 'POST',
data: {'rating' : currentRating}
});
}
});
getUserRating();
}
}
</script>
<script type="text/javascript">webpageReady();</script>
</body>
</html>
rating.js
router.get("/some/url/rating", function (req, res) {
Rating.findOne({'author.id': req.user._id}).populate("ratings").exec(function(err, rating){
if(err){
console.log(err);
}
else{
res.send({userRating : rating});
}
});
});
I had the same question, and I figured it out like this - I use jQuery StarRatingSvg v1.2.0:
callback: function(rating, $el){
$.post(
URL,
{ rating: rating, _token : "csrf_token" }
).done(function (resp) {
$el.starRating('setRating', parseFloat(resp.rating), false);
});
}
The callback function has two parameters: rating - the value set by a user when they click the stars, and $el - the rating element.
I hope it helps someone.
Here is simple demo for this plugin
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/star-rating-svg#3.5.0/src/jquery.star-rating-svg.js"></script>
</head>
<body>
<div class="my-rating"></div>
<script>
$(document).ready(function(){
$(".my-rating").starRating({
starSize: 25,
callback: function(currentRating, $el){
// make a server call here
}
});
});
</script>
</body>
</html>
Problem solved: In a footer there was another link to a jquery.
I intercepted a POST request with Burp Suite and I want to send this request manually from JavaScript Ajax call.
This is my request's raw:
I tried to send POST request like that:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$.ajax({
type: 'POST',
url: 'http://10.10.20.103/mutillidae/index.php?page=add-to-your-blog.php',
data: {
'csrf-token': '',
'blog_entry': 'post from ajax',
'add-to-your-blog-php-submit-button': 'Save+Blog+Entry'
};
});
</script>
</head>
<body>
</body>
</html>
But I couldn't manage it. Where is my mistake? Or, how should I do this? How could I convert raw request to Ajax request?
Thanks!
The correct solution is:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$.ajax({
method: 'POST',
url: 'http://10.10.20.103/mutillidae/index.php?page=add-to-your-blog.php',
data: {
'csrf-token': '',
'blog_entry': 'post from ajax',
'add-to-your-blog-php-submit-button': 'Save+Blog+Entry'
},
xhrFields: {
withCredentials: true
}
});
</script>
</head>
<body>
</body>
</html>
I forgot a semicolon at the end of the data field's closing curly brace. An addition, I must add xhrFields field for bypassing cookie needing.
I am new to Microsoft Cognitive services and this problem seems to have an easy fix but it has spoiled my two days. I have just copied the Computer vision for javascript code and replaced my the subscription key with mine and opened the .html file in my browser it says error.
DO I have to add something in the code
Also, I have nowt provided any image in this code what's he doing without an image?
The script code is here
<!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() {
var params = {
// Request parameters
"visualFeatures": "Categories",
"details": "{string}",
"language": "en",
};
$.ajax({
url: "https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","{6e07223403d94848be20af6f126fsssd}");
},
type: "POST",
// Request body
data: "{body}",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
code and preview of error
While it's not very obvious, in any code snippet from the Cognitive Service API reference page such as this one that I suspect you were using, you must provide a value (or remove) wherever it shows {something}. Here's code with suitable values:
<!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">
var myKey = "6e07223403d94848be20af6f126fsssd";
var myBody = {url:"http://www.gannett-cdn.com/-mm-/2d2a8e29485ced74b7537554043aeae2e0bba202/c=0-104-5177-3029&r=x1683&c=3200x1680/local/-/media/2015/07/18/USATODAY/USATODAY/635728260394906410-AP-GOP-Trump-2016.jpg"}
$(function() {
var params = {
// Request parameters
"visualFeatures": "Categories",
"language": "en",
};
$.ajax({
url: "https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", myKey);
},
type: "POST",
// Request body
data: JSON.stringify(myBody),
})
.done(function(data) {
alert("success");
debugger;
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
Well i do a simple ajax request to my controller and when i console log it just shows the html from my webpage.
$(document).ready(function(){
$('.modelLink').click(function(){
var $reviewID = $(this).attr('data-id');
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
jQuery.ajax({
url: '/flyout',
type: 'post',
data:{
'reviewID':$reviewID
},
success: function( data ){
alert('Success Alert');
console.log(data);
}
});
});
});
Controller:
public function flyout(){
$result[] = ['value' =>'test', 'id' => '1'];
return Response::json($result);
}
Route::
Route::post('flyout','DashboardController#flyout');
So i get the pop up "success alert". but my console shows
<html>
<head>
<meta name="_token" content="UEUPcy9i7HMxTo65Ga2HumCplY158H8Ph5cD3eOP"/>
<link href='//fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
and this carries on and matches my pages html content.
Why is this?