ajax failing getting data from pre element after it gets filled - javascript

The thing is that i have an embedded python interpreter and after a user presses "Run", the output from interpreter gets transferred to a pre element. I want to take that data from pre element and send it to django server through AJAX. The problem is that even after assigning of that data to a variable, django gets nothing. Also i can start interpreter and AJAX script only after pressing "Run", both work work with onclick. I am using POST request.
`$(document).ready(function(){
$('#run').click(function(){
var input_string = String(document.getElementById("output").innerHTML);
alert(input_string);
$.ajax({
url: '/courses/python3/lesson_validate/{{ lesson_number }}/',
data: {"text": input_string, csrfmiddlewaretoken: '{{ csrf_token }}'},
dataType: "json",
type:"POST",
success: function(data, textStatus){
alert('get_response');
alert(data);
},
error : function(xhr,errmsg,err) {
alert(xhr.status + ": " + xhr.responseText);
}
});
});
});
`
So that code works perfectly
var input_string = String(document.getElementById("output").innerHTML);
alert(input_string);
but when i try to use that variable in ajax, server fails to get it.
I tried using async: false, it doesn't change anything.
This is view code:
`def lesson_validate(request,lesson_number):
args = {}
args.update(csrf(request))
out_compare = Lessons.objects.get(id=lesson_number).lesson_output
if request.method == "POST" and request.POST.get('text') == out_compare:
text = "they are equal"
return HttpResponse(json.dumps(text), content_type='application/javascript')
else:
args['testtest']=request.POST.get('text')
return render_to_response('course_lesson.html', args, context_instance=RequestContext(request))`
After i check request.POST.get('text') it is empty
The question is how can i get data from ajax, from a variable assigned before, not just from a sting?

It looks like you're sending JSON to the server in that request, so to get the variables in Django you'd need to do:
def lesson_validate(request,lesson_number):
import json
data = json.loads(request.body)
text = data.get('text')
# Do stuff.

Related

How to send multiple variables from a HTML web page to a python script without form submissions

This is going to be a strange one if I'm honest so please bare with me.
Im currently working on a project that requires me to call python scripts that are part of a webserver that is running a HTML webpage from the page itself i.e You move a slider on the webpage and it calls the python script and passes the value of the slider and an ID value that the script requires to pass the value to its relevant end point. In this case its a monitor ID and the slider value is the brightness value that the brightness must be set to.
Currently I have achieved this with a form submission action but I don't want the webpage to reset once a new value is sent and so JavaScript is my next best option using Ajax requests and while I have made some progress I am basically a noob with web development and have hit a brick wall.
Here is the script I have attempted and the python script that it calls.
<script>
slider.oninput = function (event, ui)
{
var slider_val=event.target.id;
console.log(slider_val);
$( "#"+slider_val ).val( ui.value );
$( "#amount_"+slider_val ).val( $( "#"+slider_val ).slider( "value" ) );
changeBrilliance();
}
function changeBrilliance(value, monid)
{
$.ajax({
type: "POST",
url: "/brilliancechange",
data: { mydata: value, mon: monid }
});
}
</script>
Python:
#app.route('/brilliancechange', methods=['POST'])
def brillchange():
userinput = request.form['mydata']
selectedMon = request.form['mon']
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
DATA = "A6" + selectedMon + "0000000401C0"
DATA += hex(int(userinput)).lstrip("0x")
check = checksum(bytes.fromhex(DATA))
DATA += hex(int(check)).lstrip("0x")
dataarray = hextobyte(DATA)
s.sendall(dataarray)
s.close()
What should the javascript look like if i want to call this method with a different ID and value each time without it reloading the webpage everytime?
It looks like changeBrilliance() accepts two parameters but when called nothing is getting passed. I'm not too familiar with the Python framework being used, but as long as it accepts content-type: application/json in POST body you could do:
// not totally sure which value/id combo you need but just pass the necessary ones here
changeBrilliance(slider_val, ui);
function changeBrilliance(value, monid)
{
var myObj = { 'myData': value, 'mon': monid };
$.ajax({
type: "POST",
url: "/brilliancechange",
contentType: "application/json",
data: JSON.stringify(myObj)
});
}
Then if you want something in the browser to change, you'll have to callback on done if successful or fail if something goes wrong, and always callback for some behavior that should always happen:
$.ajax({
type: "POST",
url: "/brilliancechange",
contentType: "application/json",
data: JSON.stringify(myObj)
}).done(function(data) {
// do something
}).fail(function(jqXHR, textStatus, err) {
// handle error
}).always(function(data) {
// always callback
});

passing data from laravel view to controller via ajax onchange event

I have a dropdown list in a blade view. I want to send the value of the selected item to the controller immediately onchange. I have 2 routes in web.php:
Route::get('/plots', 'PlotController#index');
Route::get('/plots/{testId}', 'PlotController#getData');
The first one populates the dropdown list. The second one is supposed send the value of the dropdown list to the controller, which pulls stuff from mysql and sends the data back to the view, which draws a chart. I can get the dropdown to populate ok, but I can't figure out how to send the selected value to the controller. I'm trying to use ajax to do it like this:
$(document).ready(function() {
$('#sel_test').change(function() {
var testId = $(this).val();
console.log("testId=" + testId);
$.ajax({
url: 'plots/' + testId,
type: 'get',
dataType: 'json',
success: function(response) {
console.log("success");
}
});
});
});
The testId output to the console is correct but it never makes it to the controller. The error I see in the console is:
GET http://homestead.test/plots/1 500 (Internal Server Error)
I'm pretty new to laravel and find it extremely confusing. Can anyone explain the correct way to do this?
EDIT:
After testing and confirming Rian's answer as correct, I then tried to implement the real code, which of course is much more complicated. Instead of the controller returning the input test_id:
return $request->test_id;
It actually returns a more complex structure:
return view('plot')
->with('measurements',json_encode($result))
->with('events',json_encode($timeline))
->with('limits',json_encode($limits));
When I uncomment the original controller code, including the return section above, it seems to affect the ability of the controller to return anything at all. Here is the first few lines of the PlotController getData method:
public function getData(Request $request) {
Log::debug("made it to PlotController.php#getData");
Log::debug("test_id="+$request->testId);
And here is the log output:
[2020-02-23 16:43:52] laravel.DEBUG: made it to
PlotController.php#getData
The second line does not output anything. Here is what I see in the javascript console after I select an item from the dropdown list:
testId=49 jquery.min.js:2 GET
http://homestead.test/get-data-by-id?test_id=49 500 (Internal Server
Error)
Any ideas?
The easiest way is to get the data in Laravel Request. At least that's how I do it.
So your route shouldn't contain any parameter for that.
Your route will look like this:
Route::get('get-data-by-id', 'PlotController#getData')->name('get.data.by.id');
Your ajax should be like this:
$(document).on('change', '#sel_test',function(){
var testId = $(this).val();
$.ajax({
type:'GET',
url:"{{ route('get.data.by.id') }}",
data:{'test_id':testId},
success:function(data){
console.log(data);
}
});
});
In your controller's getData() function just use Laravel Request to fetch the data.
public function getData(Request $request)
{
// You can return the ID to see if the ajax is working
return $request->test_id;
}
Make it post from Get for easier
At Web.php
Route::post('/list/plots', 'PlotController#getData')->name('getData');
At Blade file Ajax Request :
$(document).ready(function() {
$('#sel_test').change(function() {
var testId = $(this).val();
var url = '{{ route("getData")}}';
var token = "{{ csrf_token()}}";
$.ajax({
method:"post",
url: url,
data:{testId:testId,_token:token}
dataType: 'json',
success: function(response) {
console.log("success",response);
}
});
});
});
At Controller :
public function getData(Request $request){
$testId = $request->testId;
// Write your logic here
}
Try this. Hopefully work for you

ajax call based on the value of 2 input fields to populate jquery autocomplete

I have been stuck with this problem for a while. I would like to pass 2 arguments (the value of 2 input fields of one form) in my ajax call to be used for a jquery autocomplete (the search is based on a mysql query using the values of input1 and input2). I had a few suggestions but so far i have no luck:
here my ajax call trying to pass the 2 arguments input1 and input2. there is no code error showing up but the autocomplete does not work. it is working if i am using only one argument.
function fillbox2(){
$('#input2').autocomplete({
source: function(request, response ){
var frmStr={
input1:$('#input1').val(),
input2:$('#input2').val()
requestTerm: request.term
};
$.ajax({
url: './cgi_temp3.cgi',
dataType: 'json',
data:{data: frmStr},
contentType: "application/json; charset=utf-8",
success: function (data) {
response ($.map( data.matches, function(item){
return {
value: item.info2,
}
}));
}
});
},
minLength: 2,
select: function(event, ui){
$("#prod_term").val(ui.item.value);
return false;
}
});
and here my cgi script that process the MYSQL query
#!/usr/local/bin/python3
import cgi, json
import os
import mysql.connector
def main():
print("Content-Type: application/json\n\n")
form = cgi.FieldStorage()
term2 = form.getvalue('input2')
term1=form.getvalue('input1')
conn = mysql.connector.connect(user='***', password='***', host='localhost', database='***')
cursor = conn.cursor()
qry = """
SELECT name2, info2
FROM table2
join table1 ON
info2_id=information2_id
WHERE name2 LIKE %s AND info2_id=%s
"""
cursor.execute(qry, ('%' + term2 + '%',term1))
where could be the problem?
At first glance I'd say it's possibly a timing issue. The source function isn't going to wait for your ajax call to complete, so you're essentially giving it a blank value. Try initiating the autocomplete inside the ajax success function.
function fillbox2(){
$.ajax({
...
success: function (data) {
...
$('#input2').autocomplete(...);
});
}

submit a form with jQuery function

i have a html page, which contains a form and i want when the form is successfully submited, show the below div:
<div class="response" style="display: none;">
<p>you can download ithere</p>
</div>
i also have a jquery function:
<script type="text/javascript">
$(function() {
$('#sendButton').click(function(e) {
e.preventDefault();
var temp = $("#backupSubmit").serialize();
validateForm();
$.ajax({
type: "POST",
data: temp,
url: 'backup/',
success: function(data) {
$(".response").show();
}
});
});
});
</script>
and in my views.py (code behind) i create a link and pass it to html page. i have:
def backup(request):
if request.is_ajax():
if request.method=='POST':
//create a link that user can download a file from it. (link)
variables = RequestContext(request,{'link':link})
return render_to_response('backup.html',variables)
else:
return render_to_response('backup.html')
else:
return render_to_response("show.html", {
'str': "bad Request! :(",
}, context_instance=RequestContext(request))
backup = login_required(backup)
my problem: it seems that my view doesn't execute. it doesn't show me the link that i send to this page. it seems that only jQuery function is executed. i'm confused. how can i make both of them to execute(i mean jQuery function and then the url i set in this function which make my view to be executed.)
i don't know how to use serialize function. whenever i searched, they wrote that:
The .serialize() method creates a text string in standard URL-encoded notation and produces query string like "a=1&b=2&c=3&d=4&e=5.
i don't know when i have to use it, while i can access to my form field in request.Post["field name"]. and i don't know what should be the data which is in success: function(data) in my situation.
thank very much for your help.
You have to get and display the data from your ajax post function, where data is the response you render through your DJango server, for example:
t = Template("{{ link }}")
c = Context({"link": link})
t.render(c):
Your JS / jQuery should become something like this:
<script type="text/javascript">
$(function() {
$('#sendButton').click(function(e) {
e.preventDefault();
var temp = $("#backupSubmit").serialize();
validateForm();
$.ajax({
type: "POST",
data: temp,
url: 'backup/',
success: function(data) {
// 'data' is the response from your server
// (=the link you want to generate from the server)
// Append the resulting link 'data' to your DIV '.response'
$(".response").html('<p>you can download ithere</p>');
$(".response").show();
}
});
});
});
</script>
Hope this helps.

insert data in database and show same data after insert without refresh page(call data after insert of database)

i want insert some of data in database by ajax call ($.ajax()) and generation tracking code by a code php and with others data it insert in database . how after (upon) insert in database, displaying to user it tracking code ? (Without Refresh Page)
With respect
my code:
$('.insert').live('click',function(e){
e.preventDefault();
var dataObj = $(this).closest('form').serialize();
//alert(dataObj)
$.ajax({
type: "POST",
url: 'insert_customers',
data: dataObj,
cache: false,
success: function() {
//alert(idname)
$('.result').hide().fadeIn('slow').html("<div class='message'>Your information was successfully. your tracking code is : '+$tracking' </div>");
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
return false;
})
You can send back data to the client (either html or objects) and use the data in the success function. To do so you use whatever print method that your server language uses (ie. if php use echo, perl print, etc) To print a content header and the information (like you would on a normal request for a web page. I would sugesst sending a content header of Content-type:application/json and format your data back as {"tracking":trackingVar} Then in your success function define it as:
success: function(data) {
//alert(idname)
$('.result').hide().fadeIn('slow').html("<div class='message'>Your information was successfully. your tracking code is : " + data.tracking + " </div>");
},

Categories