I need to update html tag text, based on respond from backend. I am using Django server to run the app. In the backend, I am running a timer, measuring the amount of time, the process had taken. I need to get this amount of time to frontend, and display it.
class Timer():
def __init__(self):
self._start_time = datetime.datetime.now().replace(microsecond=0)
print(self._start_time)
def elapsed_time(self):
return (datetime.datetime.now().replace(microsecond=0) - self._start_time).seconds
urls.py:
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', views.home, name='home'),
url(r'^$', views.output, name='output')
]
views.py:
def output(request):
time = timer.elapsed_time()
return time
And my html looks this so far:
<td class="value" id="elapsed-time">00:00</td>
<script>
var urlMappings = {
url_elapsed_time : "{% url 'output' %}"
}
$.ajax({
type: "POST",
url: urlMappings.url_elapsed_time
}).done(function(data){
console.log("Done");
}).fail(function(data){
console.log("Fail");
});
</script>
So far, I am only getting 403 error message. Any help?
You can try with this process...
$.ajax('yourRrquestURL',{
method: 'POST',
data: formData,
processData: false,
contentType: false,
success:function () {
console.log("Done");
},
error:function () {
console.log("Fail");
}
);
or
$.ajax('yourRrquestURL',{
method: 'GET',
processData: false,
contentType: false,
success:function () {
console.log("Done");
},
error:function () {
console.log("Fail");
}
);
Related
For my single page web app, I need to:
Send a json from .js to flask (DONE)
Run the input through a python function - getString() and get a str output (DONE)
Send the str output back to the .js file (PROBLEM)
Here is the flask app:
#app.route('/',methods =['GET','POST'])
def index():
req = json.dumps(request.get_json())
if request.method == 'POST':
result = getString(req) #Function outputs a string
return jsonify(result)
else:
print('Not Received')
return render_template('index.html')
if __name__ == '__main__':
app.run()
The problem is that the jsonify(result) is not being sent probably due to the request.method == 'POST' switching to else when jsonify is called. Is there any way to fix my code to send the str output to the .js?
Here is the .js:
//To send info to flask
document.querySelector('#generate').addEventListener('click',function() {
var json_inputs = JSON.stringify(inputs);
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/",
traditional: "true",
data: json_inputs,
dataType: "json"
});
})
//To receive from Flask
$.ajax({
url: "/",
type: 'GET',
success: function(data) {
console.log(data);
}
});
I think you've misunderstood what GET and POST are, GET is a request that only fetches something from the back end without a message body but a POST can send a body and recieve something.
try this instead:
document.querySelector('#generate').addEventListener('click',function() {
var json_inputs = JSON.stringify(inputs);
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/",
traditional: "true",
data: json_inputs,
dataType: "json",
success: function(data) {
console.log(data);
}
});
})
This is my code , When I click on submit , somehow the data is inserting but that echo data in back php form is not showing in this front ajax js code , please tell me if anything is wrong in my data
var formData = new FormData(this);
$.ajax({
url: '../back/regback.php',
type: 'POST',
data: formData,
success: function (data) {
alert(data);
},
cache: false,
contentType: false,
processData: false
});
}
return false;
ok this is my full js code
$(document).ready(function(){
$('form#off').submit(function(event){
event.preventDefault();
if($('#name').val()==''){
$('#nameid').text('Plase Select Customer Name ');
return false;
}
else{
var formData = new FormData(this);
$.ajax({
url: '../back/regback.php',
type: 'POST',
data: formData,
success: function (data) {
//alert('data has been added');
error: (err)=>{console.warn(err)}
// location.href='gst_chargeoff.php';
alert(data);
},
cache: false,
contentType: false,
processData: false
});
}
return false;
});
});
The ajax call is working fine. It is also getting response from the url. If there would be any server side error , It can be detected in the error: of the ajax parameter.
In your code it was written incorrectly, the same i have corrected in the below code, you will get the error in console if there will be any server side error. else the response will be returned properly.
Check the below code.
$(document).ready(function(){
$('form#off').submit(function(event){
event.preventDefault();
if($('#name').val()==''){
$('#nameid').text('Plase Select Customer Name ');
return false;
}
else{
var formData = new FormData(this);
$.ajax({
url: '../back/regback.php',
type: 'POST',
data: formData,
success: function (data) {
//alert('data has been added');
// location.href='gst_chargeoff.php';
alert(data);
},
error: function(err){
console.log(err);
},
cache: false,
contentType: false,
processData: false
});
}
return false;
});
});
You forgot to add the error attribute to your AJAX request. It's most likely throwing an error.
error: (err) => {
console.warn(err)
}
Wrap the entire $.ajax block inside a console.log($.ajax({...}));.
Then look into the console for the response codes for more info
Also you can use this to find more about the case:
error: function(err){
console.log(err);
}
I write an application with speech recognition. All I want is to record some speech and send it to server where I will convert it into text. And I have a problem with sending that sound file. I record voice using p5.js library and when I try to download it there is no problem.
The problem is when I try to send it to server using ajax.
script.js
function toggleRecording(e) {
if (e.classList.contains("recording")) {
recorder.stop();
e.classList.remove("recording");
sendAudioToServer(soundFile)
} else {
e.classList.add("recording");
recorder.record(soundFile);
}
}
function sendAudioToServer(soundFile)
{
var data = new FormData();
data.append('fname', 'test.wav');
data.append('data', soundFile);
console.log(soundFile);
console.log(data);
$.ajax({
type: 'POST',
url: '/recognizeCommand',
data: data,
dataType: 'jsonp',
processData: false,
contentType: false,
success: function(data) {
alert("works!");
},
error: function() {
alert("not works!");
}
})
Java controller
#PostMapping("/recognizeCommand")
public #ResponseBody String recognizeCommand(#RequestParam MultipartFile mpf) {
try {
byte[] bytes = mpf.getBytes();
SpeechRecognitionApplication.logger.info(bytes);
} catch (IOException e) {
e.printStackTrace();
}
return "finish";
}
When I stop recording regardless to toggleRecording function it should stop recording and send it to server. And there is a problem with sendAudioToServer function. Here is the result from Chrome console:
I'm not sure but there is probably problem with FormData. As you can see when I printed it in console it's empty. Founded some similar questions here but there is no solution to solve my problem.
EDIT:
After add dataType: 'jsonp'
There is that error:
EDIT 2:
After adding csrf token:
Please add csrf tokens as this.
<meta name="_csrf" th:content="${_csrf.token}"/>
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
In header:
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
Set headers.
$.ajax({
type: 'POST',
url: '/recognizeCommand',
data: data,
dataType: 'json',
processData: false,
contentType: false,
beforeSend: function(xhr) {
// here it is
xhr.setRequestHeader(header, token);
},
success: function(data) {
alert("works!");
},
error: function() {
alert("not works!");
}
})
Try adding debug point here.
SpeechRecognitionApplication.logger.info(bytes);
Try adding dataType: 'jsonp' to your $.ajax call like,
$.ajax({
type: 'POST',
url: '/recognizeCommand',
data: data,
dataType: 'jsonp',
processData: false,
contentType: false,
success: function(data) {
alert("works!");
},
error: function() {
alert("not works!");
}
})
Hope this helps!
I am sending data via ajax to my controller as
$.ajax({
url: 'test',
type: 'POST',
data: { id: sessionStorage.getItem('user_id') },
dataType: 'json',
contentType: "application/json; charset=utf-8"/*,
success:function(id){
alert(sessionStorage.getItem('user_id'));
}*/
});
and in the controller I am using
public function getUserMessages(){
$id = Input::get('id');
$messages = Message::where('message_by' , Auth::user()->id)->where('message_for',$id)->get();
echo "id is ",$id;
return $messages;
}
I am getting nothing in $id. I have also tried $_POST['id'] which says undefined index id. How I can retrive the id value?
$request->has('id') returns false too.
You should use the Request class instead of Input:
public function getUserMessages(\Illuminate\Http\Request $request){
$id = $request->id;
$messages = Message::where('message_by' , Auth::user()->id)->where('message_for',$id)->get();
return $messages;
}
Your ajax call doesn't work and will throw a 500 Server Error because you need to pass laravel's csrf token with it whenever you POST something. Create a meta tag at the top of your blade view like:
<meta name="_token_" content="{{ csrf_token() }}">
and get the value when you are doing the ajax call:
$.ajax({
url: '/test',
type: 'POST',
data: {
id: sessionStorage.getItem('user_id'),
_token:document.getElementsByName('_token_')[0].getAttribute('content')
},
success:function(id){
alert(id);
}
});
Most likely the success function in your ajax call will only alert [object Object], to get a better overview over whats returned, use
console.log(id);
instead.
You may also create an error function for the ajax call so that possible errors will be shown. Just do add
error: function(err){
console.log(err);
}
after the success function.
The problem is that you are setting the application content as json, You don't need to set the content.
jQuery ajax
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
$.ajax({
url: 'test',
type: 'POST',
data: { id: sessionStorage.getItem('user_id') },
dataType: 'json',
success:function(data){
console.log(data); // always good to output content for debugginn
}
});
Hope this help. Your ajax should work now.
Have you a route for AJAX requests? (I don't see it.)
Please try following code:
In your AJAX code:
$.ajax({
type: "POST",
url: "{{ route('ajax_route') }}",
data: { _token: "{{ csrf_token() }}", data: "sample data" },
success: function(data){
$(".result").html(data);
},
dataType: "json"
});
In your controller code:
public function ajaxAction(Request $request){
if ($request->isXmlHttpRequest() && $request->isMethod('post')) {
$data = $request->input('data', null);
echo json_encode($data);
}
}
In your route code:
Route::post('/ajax_route', ['as' => 'ajax-action', 'uses' => 'YourController#ajaxAction']);
I wrote a Python script that inserts data into a PostgreSQL database. I have a simple HTML page with a couple of buttons, and I am having a hard time posting the data from the button click on the client to Python CGI on the server side.
Here is what the HTML, ajax and javascript look like:
''<div class="note" id="(Untitled)">
<script type="text/javascript" src="./jquery-2.1.1.js">
$(function () {
$('#1').on('click', function () {
$.ajax({
type: "POST",
url: "~/pythonscript.py",
datatype: "json",
data: JSON.stringify({
'param': {
"1"
}
}),
success: function (response) {
alert(response);
}
})
}
$('#2').on('click', function () {
$.ajax({
type: "POST",
url: "~/pythonscript.py",
datatype: "json",
data: JSON.stringify({
'param': {
"2"
}
}),
success: function (response) {
alert(response);
}
})
}
)
<body>
<a href="index2.html">
<button id="1">one</button><br>
<button id="2">two</button><br>
</a>
</body>
Here is what some of the Python looks like:
def cgi_get_from_ajax(self):
import json
import cgi
data = cgi.FieldStorage()
chosen = data.value
return chosen
def set_choice(self):
process = Name_of_class()
choice = process.cgi_get_from_ajax()
entry = []
if choice == '1':
entry = [1,0,0,0]
else:
entry = [0,0,0,1]
return entry
What am I doing wrong?
Try changing you code to:
data: {param: '2'} --- in the jQuery
data["param"].value ---- in the Python script
This usually works for me. Maybe it does for you too ;)