Ajax success function issue - javascript

My javascript looks like that.
There are some problems that I can't figure out, where I did mistake
#status_message doesn't show generated message
$("#status").className = 'fail'; doesn't override current class
var message=$("#status_message"), form=$("#bcscan"), ids=$('#itemids'),proctype, destination, counter=0, tenWordCounter = 0, autoPostInterval=null, errorcount=0, successcount=0;
function ajaxPost() {
formData = form.serialize()+'&process=Scan';
formUrl = form.attr('action');
formMethod = form.attr('method');
$.ajax({
url: formUrl,
type: formMethod,
dataType: "json",
data: formData,
success: function (data) {
var now = new Date();
if(data.err_detected==="yes")
{
if(data.errors.indexOf(",") != -1)
errorcount=errorcount+data.errors.split(",").length;
else errorcount=errorcount+1;
$("#status").className = 'fail';
message =errorcount+" errors found";
$('#errors').prepend(data.errors).slideDown("slow");
}
$('#success').prepend(data.success).slideDown("slow");
if(data.success.indexOf(",") != -1)
successcount=successcount+data.errors.split(",").length;
else successcount=successcount+1;
message +="Last submitted:"+now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
$("#status_message").text(message);
}
});
}
Here is page in action
If you want to test, please choose some option from selects like, output from db, ebay.fr and press "scan". Enter 10 digits seperated by comma try 41,42 (they exist in db tables) too between them. After 10th digit it will post textarea via ajax.

For the message, you've declared a jQuery object pointing at the element:
var message = $('#status_message'), ...
but then you're overwriting it with a string:
message = errorcount + ' errors found';
You should be calling:
message.text('some string...')
to change its contents.
For the class change, the correct syntax is:
$("#status").addClass('fail');

How about
$('#status').attr('class','fail');
This will override the current class.

did you try this?? $("#status").addClass( 'fail');

Related

Bad request error in Flask while request names generated with javascript

I'm creating an app to calculate a projection of the transit given the years and some other values, first I created a script in javascript where depending on if the user decide to add a new type of vehicle a new div is created with unique ids and names and ofcourse the data the user introduced, for showing the final result i'm using ajax, the problem comes when i tried to access the data via flask, i'm getting a bad request from the names of each vehicle like if they did not exist, but the page is actually displaying them (hope you understand my english and my problem :) )
I've tried giving a specific name (a1) an then tried to take the value in flask but i still can#t make it work.
Python
#app.route("/pavimentos/calculoTransito" , methods=['POST'])
def calculoTransito():
direc = float(request.form["direc"])
zr = float(request.form["zr"])
years = float(request.form["years"])
tc = float(request.form["direc"])
vehicles = int(request.form["vehicles"])
car1 = request.form.get("a1", None)
if car1==None:
print("No funciona")
else:
print("Funciona")
always get "No funciona"
Javascript
countClicks = 0
lista_vehiculos = []
function addVehicle(){
countClicks += 1;
//var automovil = document.getElementById("automovil").value
var fd = document.getElementById("damage_factor").value
var currentType = document.getElementById("vehicleType")
if(currentType.value == 1){
var icon = "<h2 class='pt-4'><i class='fas fa-car text-secondary'></i></h2>";
var tipoVehiculo = "Automóvil";
}
... More code for select the currentType ...
var vehicleStyle = "<div><input id=a" + countClicks + "name=a" + countClicks + "value=" + fd + "></div>"
lista_vehiculos.push(vehicleStyle)
var vehicle = document.getElementById("vehiclesContainer").innerHTML += lista_vehiculos[countClicks-1]
document.getElementById("vehicles").value = countClicks
}
AJAX part
$(document).ready(function(){
$('form').on('submit', function(event){
$.ajax({
data:{
direc: $('#direc').val(),
zr: $('#zr').val(),
years: $('#years').val(),
tc: $('#growingRate').val(),
vehicles: $('#vehicles').val(),
car1: $('#a1').val()
},
type: 'POST',
url: '/pavimentos/calculoTransito'
})
.done(function(data){
if (data.resultado){
$('#resultado').text(data.resultado).show()
}
})
event.preventDefault();
});
});
You're not submitting a form, you're sending JSON. The initial event might be the submission of a form, but your AJAX uses event.preventDefault() and does not end up submitting a traditional serialized form. You can't use car1 = request.form.get("a1", None) here.
Firstly, you should correct your AJAX to add a contentType:
$(document).ready(function(){
$('form').on('submit', function(event){
$.ajax({
data: JSON.stringify({
direc: $('#direc').val(),
zr: $('#zr').val(),
years: $('#years').val(),
tc: $('#growingRate').val(),
vehicles: $('#vehicles').val(),
car1: $('#a1').val()
}),
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '/pavimentos/calculoTransito'
})
.done(function(data){
if (data.resultado){
$('#resultado').text(data.resultado).show()
}
})
event.preventDefault();
});
});
And then you need to change your Flask method from request.form to request.json. So the Flask side would look something like:
#app.route("/pavimentos/calculoTransito" , methods=['POST'])
def calculoTransito():
req = request.json
direc = float(req["direc"])
zr = float(req["zr"])
...
car1 = req.get("a1", None)
if car1 is None: # None is a singleton, you shouldn't use == here
print("No funciona")
else:
print("Funciona")
LATE EDIT
This can't work because calculoTransito does not actually return anything, so Flask will throw an error from that alone. Your view function actually has to return something other than an implicit None.

Passing data that is coming from a server, from one page to another in javascript without using forms

I do not have much grip on javascript and having problemswith it.
My data is coming from a server and the user when clicks on an item is redirected to a new page which has that items all details. The problem is when a user clicks on an item,how to send the data from one page to the next.
No php is used. javascript ajax jquery used and data coming from json
this is format and when user clicks on play button a new age should be displayed where the data is to be shown to user.
Template={"Big_Display_Template": '{{#items}}<input type="hidden" name="guid" value="{{id}}"><div class="hero"
style="background-image:url({{videoStillURL}})"><div class="hero-content"><br>
<h2>{{name}}</h2> <p>{{shortDescription}}</p> <div class="hero-links"><a href="Watch_Live.html"
onclick="PassDataToNextPage({{name}},{{id}},{{shortDescription}});">
Play<span class="genericon genericon-play"> </span></a></div>
<div class="hero-links-fav"><a href="#">Favourite<span class="genericon genericon-fav">
</span></a></div></div></div>{{/items}}'
}
This is my function PassDataToNextPage()
function PassDataToNextPage(name,guid,Description)
{
var url = 'Watch_Live.html';
$.ajax({
url: url,
type: 'POST',
data: 'name=' + name + '&guid=' + guid + '&shortDescription=' + Description,
success: function(result) {
dataUrl=data;
}
});
return window.location+"/"+dataUrl;
}
I know this is wrong but how to make it right? thanks a lot in advance
The problem lies in the return window.location+"/"+dataUrl; line: the redirect should be done inside the success function because it will be called when the request is completed:
function PassDataToNextPage(name,guid,Description)
{
var url = 'Watch_Live.html';
$.ajax({
url: url,
type: 'POST',
data: 'name=' + name + '&guid=' + guid + '&shortDescription=' + Description,
success: function(result) {
dataUrl = data;
window.location = window.location + "/" + dataUrl;
}
});
}
In the template you must add return false in the onclick attribute to avoid the browser following the link interrupting your handler:
<a href="Watch_Live.html" onclick="PassDataToNextPage({{name}},{{id}},{{shortDescription}});return false">
You can pass key:value data via url GET parameters.
For example: if you want to pass data to this page: Watch_Live.html, you can do something like:
<button>Pass data</button>
To parse the parametesr in the other page, read this SO answer to a similar question.
https://stackoverflow.com/a/901144/4440845
Look like you want to pass data and go to the next page with the data, you don't need ajax to achieve. Simply:
function PassDataToNextPage(name,guid,Description)
{
var url = 'Watch_Live.html';
window.location.href = url + '?name=' + name + '&guid=' + guid + '&shortDescription=' + Description;
}
Comment:
You can use:
< a onclick="PassDataToNextPage({{name}},{{id}},{{shortDescription}});">Play< /a>
The click event will be handled by the function PassDataToNextPage in onclick.
Assuming you use PHP in your next page, you can fetch the data
$name = $_GET['name'];
$guid = $_GET['guid'];
$shortDesc = $_GET['shortDescription'];

Strange error: Uncaught TypeError: Illegal invocation ajax

UPDATE
The problem was solved, it seems that I was being stupid and forgot to put the .value after referencing the title element.
I have been using ajax for a few months now, and have never come across an error like this before.
I am creating an array of formData and passing it over to a php script using ajax like I have done many times before, however I am now getting that strange error.
Could it possibly have something to do with my formData? I can't see how as it isn't any different to how I have done it before.
Any help would be great, thanks!
//This function will add the product and its details to the cart.
function addToCart(e)
{
//alert("CLick");
calculatePrice();
//Get the product ID from the URL
var id = getParameterByName('productID');
alert(id);
//Get the title.
var title = document.getElementById('title');
//Get the qty.
var qty = document.getElementById('qty').value;
//Get the weight.
var weightList = document.getElementById('weightList');
var weightText = weightList.options[weightList.selectedIndex].text;
//alert("Text: " + weightText);
var weightValue = weightList.options[weightList.selectedIndex].value;
//alert("Val: " + weightValue);
formData = {"ID" : id, "SRC": "", "Title" : title, "Qty" : qty, "Weight" : weightText, "Totalprice" : totalPrice, "Singularprice" : weightValue, "Action" : "Add"};
$.ajax(
{
url: 'manipulateCart.php',
type: "POST",
data: formData,
success: function(data)
{
alert("cc");
//document.getElementById('content').innerHTML = "";
//$('#content').append(data);
},
error: function(xhr,err)
{
alert("Error: " + xhr + " " + err);
}
});
}
Missing .value in this line
var title = document.getElementById('title').value;
^^^^^
You are passing the title variable to the formData object. This variable holds the #title element, not the value of that element. Add .value to var title = document.getElementById('title');
Result:
var title = document.getElementById('title').value;.
More info: https://stackoverflow.com/a/11071290/1130234

Foundation contact form js not working

I have my contact form ready to go but for some reason when i gulp it with uglify it returns an error and won't minify. My javascript seems correct and it will uglify when I remove the ajax call but with the ajax call it breaks. Any insight? Here's my js:
$('.contact-form').on('valid.fndtn.abide', function() {
var name = $(".contact-form input#name").val();
var email = $(".contact-form input#email").val();
var message = $(".contact-form textarea#message").val;
// Data for response
var dataString = 'name=' + name +
'& email =' + email +
'& message =' + message;
//Begin Ajax Call
$.ajax({
type: "POST",
url: "php/mail.php",
data: dataString,
success: function() {
$('.contact-form').html("<div id ='success'></div>");
$('#success').html("<h2>Thanks!</h2>")
.append("<p>Dear" + name + "!, I look forward to working with you.</p>")
.hide()
.fadeIn(1500);
},
}); //ajax call
return false;
});
JsLint throws error on this code. Removing the trailing comma seems to clear it up:
.fadeIn(1500);
}, /* <-- remove this comma */

AJAX post - {"readyState":0,"responseText":"","status":0,"statusText":"error"}

I have this javascript but it is not working : I receive the following error : {"readyState":0,"responseText":"","status":0,"statusText":"error"}
This script is included in a webpage of my site which is in a subdirectory of the site.
From my debugging, I do not understand where the error can come from... (since I do quite exactly the same for the index webpage of my site with another javascript which looks almost the same)
$(document).ready(function() {
//if submit button is clicked
$('#filterbtn').click(function () {
//Get the data from all the fields
var a = JSON.stringify( $("#multiselect").val() );
var b;
if ($('#b').prop('checked')) {
b = 0;
} else {
b = 1;
}
var c = JSON.stringify($("#Sliderstart").slider("value"));
var d = JSON.stringify($("#Sliderend").slider("value"));
//organize the data properly
var data = 'b=' + b + '&c=' + c + '&d=' + d + '&a=' + a;
//start the ajax
$.ajax({
url: "./filter.php",
type: "POST",
data: data,
crossDomain: true,
cache: false,
success: function (html) {
document.getElementById("message").innerHTML=html;
},
error: function (e) {
alert(JSON.stringify(e));
}
});
return false;
});
});
Thank you guys !
Cheers
This is the kind of error you get when you request an url that doesn't exist.
Try changing this:
url: "./filter.php"
to an aboslute path like this:
url: "/PATH_TO_FILTER/filter.php"

Categories