Selenium is not handling my javascript dialog box correctly - python

I've passed the last 5 hours trying to find a solution that's been bugging me since yesterday. I am writing some BDD tests using behave and selenium to test the product addition functionality of my web app.
So to add a product the user have to click on a button which will launch a dialog box containing the form that will allow him to fill in the details of the product he wants to add. When the user clicks on submit the dialog box disappears and a JS code updates a datatables table with the new product using an Ajax request.
When I launch my test selenium finds the product addition form and fill in the details I provided, the problem is that when it clicks on submit basically nothing happens, my JS code isn't executed. Here's the behave code that submits the form:
#when(u'I click on Add new product')
def subscribe_click(context):
context.browser.find_element_by_id('add-submit').click()
and what follows is the JS function that really handles the form submission
function submitEditForm(form, upload_data)
{
data_serialized = $(form).serializeArray();
data = {
'csrf_token': data_serialized[0].value,
'name': data_serialized[1].value,
'description': data_serialized[2].value,
'price': data_serialized[3].value,
'image': upload_data.data ? upload_data.data.image : ""
};
$.ajax({
type: "PUT",
url: "/api/products/"+row_data[0],
data: data,
dataType: "json",
success: function(data) {
$("#edit-frm").fadeToggle("fast");
new_data = [
data['name'],
data['description'],
data['price'],
data['image']
]
$('#myTable').dataTable().fnUpdate(data.data, row_index, undefined, 1);
},
error: function (resp) {
$("#edit-frm").fadeToggle("fast");
alertify.alert("There was a problem with your request please try again.")
}
});
}
So what I want to is: is selenium even capable of running Ajax requests? And if that's not the case what do I need to do so that my test works??

Related

Pass a string variable from javascript file to a python function

I have an ag-grid. Clicking on its context menu is opening a modal that has a drop-down menu that I want to populate dynamically by fetching the data from a SQLite database.
I want to pass a string variable - network_num from my .js file to a python function. I will then use this variable to execute a query to fetch data from the database. I should then send the fetched data in JSON format to .js file to populate the drop down menu. I am using ajax to send the variable, but it is not working. Please help.
Here is the code
$.ajax({
url: "/get_activity",
type: "POST",
dataType: "json",
data: {
network_num: network_num,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success : function(json) {
alert("Successfully sent the variable");
},
error : function(xhr,errmsg,err) {
alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText);
}
});
def get_activity(request):
print("Get activity function is running")
#I have my sql query here that I want to execute
Assuming you already have the infrastructure built, in python, request should be passed as a dictionary object, so unless the caller is doing something crazy, it should just be request['network_num']

Ajax with long polling cannot display celery results on web pages

I have a web page running on Flask, the user clicks the button then gives celery a long-running program. Ajax keeps polling to check if celery has output. If celery has a result, an alert will be displayed on the web page. Now if the program running in celery is very short, the alert can be displayed occasionally. If the program running in celery takes a long time, it cannot be displayed. And now the web page seems to be: click the button - alert - refresh the page in the order.
ubuntu 16.04, Chrome
the celery parts:
#celery.task(name='app.add')
def add():
z=getLength()
return {'result':z}
#app.route('/addit', methods=['POST'])
def addit():
task = add.delay()
return jsonify({}),202,{'Location': url_for('taskstatus',task_id=task.id)}
#app.route('/status/<task_id>')
def taskstatus(task_id):
task = add.AsyncResult(task_id)
if 'result' in task.info:
response['result'] = task.info['result']
return jsonify(response)
the ajax polling parts:
<script>
function start_long_task() {
$.ajax({
type: 'POST',
url: '/addit',
success: function(data, status, request) {
status_url = request.getResponseHeader('Location');
update_progress(status_url) ;
},
error: function() {
alert('Unexpected error');
}
});
}
function update_progress(status_url) {
// send GET request to status URL
$.getJSON(status_url, function(data) {
if ('result' in data) {
// show result
alert('Result: ' + data['result']);
}
else {
setTimeout(function() {
update_progress(status_url);
}, 1000);
}
});
}
$(function() {
$('#start-bg-job').click(start_long_task);
});
</script>
The actual results may be that the webpages can show an alert when celery is done. But now it can't, please help me to fix this issue, thanks a lot!
I found that if the button that performs the polling and the button that submits the form in the flask are the same, the webpage cannot display the alert. I just created a new button, dedicated to start ajax polling, so that it is successful, the web page can display alert!

I am getting jQuery Jtable error while fetching data from the python server

I have a jQuery Jtable in the front end and I am using python flask in my server.
I used python flask to fetch data from the MYSQL server which I can view in the JSON format in my browser but, unfortunately I couldn't able to make the JSON data into the Jtable.
My front end jQuery Jtable is
$('#eventsummary').jtable({
actions: {
listAction: function (postData) {
return $.Deferred(function ($dfd) {
$.ajax({
url: '/backend/groupdata',
type: 'GET',
data: postData,
success: function (data) {
$dfd.resolve(data);
console.log("loading ");
},
});
});
}
},
fields: {
irs_type: {
title: "Date & Time",
list: true,
}
}
});
$('#eventsummary').jtable('load');
and this is the error I am getting
I am also able to view my console.log code in the browser, with no error in the console.
Can someone please help me with this
Thanks,
I achieved this by using python jsonify to add my json data to the front end Jtable.
for result in data:
json_data.append(dict(zip(row_headers,result)))
return jsonify(
{
'Result': "OK",
'Records': json_data,
}
)
Thanks
The output you are seeing is the standard jTable application error. Your listAction has passed the server response to jTable, so there is no communications error.
When the json response does NOT contain Result = 'OK' it displays the application error dialog, and shows the json Message in the dialog.
The very fact that the error dialog appears means jTable is not seeing Result = 'OK' in your server response. Look for that first, if you are still stuck please post your json response. The dialog is blank because there is no error message or jTable can't see it.

Passing Parameters to a Mail Script

I want to send an email from python using the below codes i wrote/reffered
<script>
$(document).ready(function() {
$("#form1").submit(function(){
$("#form1").validationEngine();
if($('div input[type=text]').val() != "")
{
var textfield2=document.getElementById("textfield2").value;
var textarea=document.getElementById("textarea").value;
var dataS=$("#form1").serialize();
$.ajax({
type: "POST",
crossDomain: 'true',
url: "mail.py",
success: function( ){
alert("completed");
},
error: function(){
alert(dataS);
}
});
}
return false;
});
});
</script>
For the mail part , i reffered the below google code
from google.appengine.api import mail
mail.send_mail(sender="Example.com Support <support#example.com>",
to="Albert Johnson <Albert.Johnson#example.com>",
subject="Your account has been approved",
body="""
Dear Albert:
Your example.com account has been approved. You can now visit
http://www.example.com/ and sign in using your Google Account to
access new features.
Please let us know if you have any questions.
The example.com Team
""")
Now the question is , on ajax call .. How can i recieve the HTML parameters in the mail.py script? pls help i'm new to python
Within a cgi script, if you instantiate a cgi.FieldStorage(), it is automatically filled with the GET or POST parameters. If you want to post content, then just add a data property to your ajax request object:
$.ajax({
...
data: {param1: 'value1', param1: 'value2', ...}
...
})
In your python script it should the be enough to do:
import cgi
store = cgi.FieldStorage()
par1 = store.getfirst('param1')
...
One more thing -
Ask yourself: do you really want to submit the form when the page is loaded? (Your're using the 'ready' event). Wouldn't it be better to wait until somebody has entered somehting in the form?

Multiple request when FB edge.create Event catched

I wanted to use facebook's like button for voting on my page. Unfortunately when 'Like' is clicked I get 3-5 requests to my function instead of only one. Is there a way to prevent this ?Sample code:
FB.Event.subscribe('edge.create', function(href, widget) {
console.log(href, widget);
});
My code:
FB.Event.subscribe('edge.create', function(href, widget) {
$.ajax({
type: "POST",
url: "/votes/register",
data: "href="+href,
dataType: 'json',
success: function(data){
$(".list-submissions").html(data["html"])
}
});
return false;
});
Or maybe I can block this from the function's side using django ? Here's my function code:
def register_vote(request):
ip = request.META['REMOTE_ADDR']
url = request.POST.get("href", "")
id = os.path.basename(url)
try:
vote = Vote.objects.filter(ip=ip, id=id)
except:
vote = None
if not vote:
vote = Vote(ip=ip, uid=id)
vote.save()
html = render_finalists(request)
ajax = simplejson.dumps({
"html": html
}, cls=LazyEncoder)
return HttpResponse(ajax, mimetype='application/javascript')
I do facing slightly same issue, have been creating like buttons on the fly using AJAX, specific to the content but 'edge.create' some how storing the event and incrementing the edge.create events and firing multiple times when I click on another FB like widget.
Have bee hitting my head so badly, no luck till yet :(
Any quick help, should be appreciated.
Finally I cracked it, just compared the response which I was getting from the response object to the one which I needed to pass and that works.
FB.Event.subscribe('edge.create', function(response) {
if ( response.toString() == shareUrl.toString() ) {} }
You might get multiple requests to you callback function if the Facebook core JS SDK has been referenced multiple times, i.e. the following script tag (or variations) are more than once:
<script src="http://connect.facebook.net/en_US/all.js"></script>

Categories

Resources