How to pass Json string as a javascript method parameter - javascript

I formed a Json String.
var jsonProduct = "{Product:'" + Details[0] + "',Brand:'" + Details[1] + "',Model:'" + Details[2] + "',Price:'" + Details[3] + "'}"
<input class="button black" type="submit" value="Add To Cart" onclick="return addOrderItem(' + jsonProduct + ')" />
How to pass this 'jsonproduct to javascript function addOrderItem as follows
function addOrderItem(product)
{
cartproduct[cartproduct.length] = " + product + ";
//cartproduct[cartproduct.length] = " + {Product:'1001',Brand:Dell',Model:'Inspiron',Price:'25000'} + ";
}
When I pass product as parameter it is not working

You could parse it using
var product = JSON.parse(jsonProduct);
but you don't have to use JSON at all. Do this :
var product = {
Product: Details[0], Brand:Details[1],
Model:Details[2], Price:Details[3]
};
addOrderItem(product);
If you want to call this from an input click, you can bind the call using
onclick="return addOrderItem(product)"
or, better, give an id to your element and then bind the event handler from the JS code :
<input id=submit class="button black" type="submit" value="Add To Cart">
<script>
document.getElementById('submit').onclick=function(){addOrderItem(product)};
</script>

Related

If it possible to submit form form Ajax with Flask?

I have an application using Flask and JavaScript. I have a function in JavaScript when the user click the button and the data are send to Flask. This function create a marker on the map and set the data from function in Flask to marker popup. I use form in popup because I want to get the name form this popup. I want to submit this form from popup and get the name but when I do it print("Name :",nazwa_event) it return me None. I create a input with hidden tag in html and I set input value to the name from form $('input[id=nameOF]').val(nazwa.value);. It is possible to do that or I can't submit form from Ajax ?
HTML code:
<input type="text" id="name_of_event" class="form-control mb-2" name="name_event" placeholder="Nazwa wydarzenia">
<input name="nameOfEvent" type="hidden" value="" id="nameOF">
<br>
<button id="search-button_event" type='submit' name="event_form" class="btn btn-primary">Szukaj</button>
JS code:
$("#search-button_event").click(function () { // make ajax request on btn click
$.ajax({
type: "POST",
url: "/mapaa", // url to the function
data: {
nameevent: $("#name_of_event").val(), // value of the form
},
success: function (response) {
nazwa = (response['name']);
let marker_event = L.marker(array[0]).bindPopup()
marker_event._popup.setContent(
'<form method="POST" action="/mapaa"'+
'<p>Nazwa: '+nazwa+'</p>'+
'<button type="submit" id="form-submit" name="form-submit" class="btn btn-warning btn-block">Dołącz do wydarzenia</button>'+
'</form>')
marker_event.addTo(mymap)
polyline_event = L.polyline(array,{color: 'red'})
marker_event.on('click',function(){
polyline_event.addTo(mymap)
})
marker_event.getPopup().on('remove', function() {
polyline_event.remove()
})
$('input[id=nameOF]').val(nazwa.value);
mymap.setView(array[0],14)
},
});
});
FLASK code:
#app.route('/mapaa',methods=['GET','POST'])
def mapa():
user_id = current_user.get_id()
slownik = {}
if request.method == "POST":
if request.is_json:
req = request.get_json()
nazwa = req['name']
data_pocz = req['data_start']
data_kon = req['data_end']
typ = req['type']
dlugosc = req['len_route']
coord = req['coordinates']
event_database = Event(date_start=data_pocz, date_end=data_kon, type=typ, name=nazwa, len_route=dlugosc,admin=user_id, route=coord)
db.session.add(event_database)
db.session.commit()
print('Dodano wydarzenie')
if 'form-submit' in request.form:
nazwa_event = request.form.get('nameOfEvent')
print("Id ev:",nazwa_event)
else:
name_ev = request.form.get('nameevent')
all_data = Event.query.filter_by(name=name_ev).all()
for row in all_data:
date_st_string = str(row.date_start)
date_end_string = str(row.date_end)
slownik = {'id':row.id,'date_st':date_st_string,'date_end':date_end_string,'type':row.type,'name':row.name,'len_route':row.len_route,'route':row.route}
return jsonify(slownik)
return render_template('mapaa.html', title='Mapa')
I can't test it but as for me you have hidden <input> in wrong place - it has to be inside form inside popup. And you can set value directly in HTML without using jQuery
marker_event._popup.setContent(
'<form method="POST" action="/mapaa"' +
'<input name="nameOfEvent" type="hidden" value="' + nazwa.value + '" id="nameOF">' +
'<p>Nazwa: ' + nazwa + '</p>' +
'<button type="submit" id="form-submit" name="form-submit" class="btn btn-warning btn-block">Dołącz do wydarzenia</button>' +
'</form>'
)
I'm not sure if it should be nazwa.value or only nazwa like in '<p>Nazwa: ' + nazwa + '</p>'

JavaScript function not getting called?

So I have a button that calls
<a class="btn btn-primary" id="btnAdd" href="#" onclick="ChangesJs.AddPlayList()"> <i class="fa fa-fw fa-plus fa-lg"></i>Add </a>
and the JS function creates additional form on its own.
function AddPlayList() {
var form = "<div class='form-group col-sm-3 clscommercial_" + addPlayList + "' style='display:none;' ><label>Break No.</label> <span class='red_color'>*</span><input class='form-control' id='txtBreakno_" + x + "' maxlength='2' onblur='ChangesJS.IsNumeric(this)' onchange='CommonJs.HideErrorMessage(this)' placeholder='Break No.' type='text'></div>";
This is the definition of IsNumeric function
function IsNumeric(selectinput) {
var _value = selectinput.value;
var ID = selectinput.id;
if (_value !== "" && !$.isNumeric(_value)) {
$("#div_" + ID).show();
$("#span_" + ID).html("Please Enter numeric value !");
selectinput.value = "";
selectinput.focus();
}
}
When I get of out focus in the text field no validation is shown.
The elements created in the dom after initial load need to have an event listener added.
function AddPlayList() {
var form = "<div class='form-group col-sm-3 clscommercial_" + addPlayList + "' style='display:none;' ><label>Break No.</label> <span class='red_color'>* </span><input class='form-control' id='txtBreakno_" + x + "' maxlength='2' onblur='ChangesJS.IsNumeric(this)' placeholder='Break No.' type='text'></div>";
// append it to the DOM....
var element = document.getElementsByClassName("clscommercial_" + addPlayList);
element.addEventListener('change', function() {
CommonJs.HideErrorMessage(this);
}, false);
}
Also, don't forget to remove the listener if you remove the element it you may end up having it fire multiple times.
The jQuery way handles this well if your using it.
$('body').on('change', '.clscommercial', function() {
// This will fire even on elements added programmatically as long
// as your top selector is (body) was created on page load.
CommonJs.HideErrorMessage($(this)[0]);
)};

Calling a function with multiple arguments

<!DOCTYPE html>
<html>
<head>
<title>Calling Functions</title>
</head>
<body>
<script type="text/javascript">
function buttonReport(buttonId, buttonName, buttonValue) {
// Information about the button id
var userMessage1 = "button id: " + "buttonId" + "\n";
// Information about the button name
var userMessage2 = "button name: " + "buttonName" + "\n";
// Information about the button value
var userMessage3 = "button value: " + "buttonValue" + "\n";
// alert the user
alert(userMessage1 + userMessage2 + userMessage3);
}
</script>
<input type="button" id="id1" name="Left Hand Button" value="Left" onclick="buttonReport(this.id, this.name, this.value)"/>
<input type="button" id="id2" name="Center Button" value="Center" onclick="buttonReport(this.id, this.name, this.value)"/>
<input type="button" id="id3" name="Right Hand Button" value="Right" onclick="buttonReport(this.id, this.name, this.value)"/>
</body>
</html>
The above function isn't giving me the right values, instead it gives me this
I want the function to show me the id, name and value of the input when I click the button.
You are concatenating string but you need to concat the parameter value with the string
function buttonReport(buttonId, buttonName, buttonValue) {
// Information about the button id
var userMessage1 = "button id: " + buttonId + "\n";
// Information about the button name
var userMessage2 = "button name: " + buttonName + "\n";
// Information about the button value
var userMessage3 = "button value: " + buttonValue + "\n";
// alert the user
alert(userMessage1 + userMessage2 + userMessage3);
}
<input type="button" id="id1" name="Left Hand Button" value="Left" onclick="buttonReport(this.id, this.name, this.value)" />
<input type="button" id="id2" name="Center Button" value="Center" onclick="buttonReport(this.id, this.name, this.value)" />
<input type="button" id="id3" name="Right Hand Button" value="Right" onclick="buttonReport(this.id, this.name, this.value)" />
Remove the quotes from around the parameter names in the var userMessage1 ... lines, e.g.:
var userMessage1 = "button id: " + buttonId + "\n";
var userMessage1 = "button id: " + "buttonId" + "\n";
// Information about the button name
var userMessage2 = "button name: " + "buttonName" + "\n";
// Information about the button value
var userMessage3 = "button value: " + "buttonValue" + "\n";
You are concatenating strings here see, "button id: " + "buttonId",
remove the quotes "" and try
There's a much easier way of doing this, note the class:
<input type="button" id="id1" class="hand-button" name="Left Hand Button" value="Left" />
<input type="button" id="id2" class="hand-button" name="Center Button" value="Center" />
<input type="button" id="id3" class="hand-button" name="Right Hand Button" value="Right" />
Then during window.onload or whatnot, add event listeners and use this to reference the button:
var handbuttons = document.getElementsByClassName('hand-button');
for (var i = 0, c_handbuttons = handbuttons.length; i < c_handbuttons; i++) {
handbuttons[i].addEventListener('click', function buttonReport() {
// Information about the button id
var userMessage1 = "button id: " + this.id + "\n";
// Information about the button name
var userMessage2 = "button name: " + this.name + "\n";
// Information about the button value
var userMessage3 = "button value: " + this.value + "\n";
// alert the user
alert(userMessage1 + userMessage2 + userMessage3);
});
}
https://jsfiddle.net/hkeLkegL/
Technically, you can do the same thing in your onclick handler by passing this too:
onclick="buttonReport(this)"
And:
function buttonReports(elem)
... elem.value ... elem.id ... elem.name ...
Or .bind(), which gives you context (this):
onclick="buttonReport.bind(this)()"
The () at the end executes the function. Which, of course, means you can use .call() without needing the extra IIFE tagalong:
onclick="buttonReport.call(this)"

Accessing Textbox Value Using Inserted JavaScript

I'm Having a bit of an issue. I'm using JavaScript to inset HTML into a webpage along with an event handler for the onblur event. It looks like this:
return '<input id = "txtIn" type="text" value=" ' + dateTime + '" onblur= "submitManualDate(document.getElementById("txIn").value(), 2, 3);" />';
I'm getting a syntax error. However, the following works perfectly fine:
return '<input id = "txtIn" type="text" value=" ' + dateTime + '" onblur= "submitManualDate(1, 2, 3);" />';
Any idea what I'm missing?
Using " inside "(double quoted) expression will break the string.
It's better to pass this as an argument as you should not have multiple elements with same id attributes in a document.
Try this example:
(function() {
var input = '<input type="text" value="5" onblur= "submitManualDate(this, 2, 3);" />';
document.getElementById('parent').innerHTML = input;
})();
function submitManualDate(elem, j, k) {
alert(elem.value + ' ' + j + ' ' + k);
}
<div id='parent'></div>
Fiddle here

Element is not defined jQuery $(element).remove()

I have this JavaScript that adds a form field, along with a link to remove that field:
var fieldCount = 0;
function addField() {
var name = 'file' + fieldCount;
var row = 'row' + fieldCount;
var str = '<p id="' + row + '"><label for="' + name + '">File to upload: <input type="file" name="' + name + '" id="' + name + '" />(100MB max size) <a onclick="removeRow(' + row + '); return false;">[-]</a></label></p>';
fieldCount++;
$("#fields").append(str);
};
function removeRow(id) {
$(id).remove();
};
Here is the markup:
<form id="ajaxUploadForm" action="<%= Url.Action("AjaxUpload", "Upload")%>" method="post" enctype="multipart/form-data">
<fieldset id="uploadFields">
<legend>Upload a file</legend>
<div id="fields"></div>
<input id="ajaxUploadButton" type="submit" value="Submit" />
</fieldset>
<a onclick="addField(); return false;" id="add">Add</a>
<div id="resultBox">
<p id="status" style="margin:10px;"></p>
</div>
</form>
The addFields works as expected, but when I click the remove link firebug tells me that row# is not defined, where # is any number of the added fields.
Any help would be appreciated!
You need to pass a valid selector expression for an ID selector (#ID), either in the removeRow call (also note the quotes surrounding the ID selector):
'<a onclick="removeRow(\'#' + row + '\'); return false;">'
Or in the removeRow function itself:
function removeRow(id) {
$("#" + id).remove();
};
You need to have quotes around it, since it's a string.
You also need the "#" to make it into a selector:
var str = '... <a onclick="removeRow(\'#' + row + '\'); return false;">...';
A better way would be to assign the onclick as a function (not sure of the jQuery way to do this but in plain Javascript):
var a = document.createElement('a');
a.onclick = (function(row)
{
return function()
{
removeRow(row);
return false;
};
})();
You are passing in the string value of row12, but the selector should be:
$('#'+row).remove()
The # specifies that you are looking for an ID. I agree with what I think one of the other answers was about to say, you should just use the onclick events natural this keyword instead:
<p onclick="remove(this)">something</p>
function remove(what) {
$(what).remove()
}
Or, maybe just forget the whole thing all together and switch to behavior for those kinds of rows:
$('.removableRow').live('click', function() {$(this).remove()});
Then you just specify that the row is removable, and never have to worry about binding events at all:
<p><a class="removableRow" href="#">Remove</a></p>

Categories