Submitting multiple dynamic forms - javascript

I'm trying to submit multiple forms at once when a single button is clicked. These forms are all generated automatically. They all have different action urls but the same id's. That's how the system (SaaS) works.
The problem is that I'm having issues getting the correct selectbox values and then send the forms. I'm not getting any error but I think it has something to do with identifiers. I'm working on this one for a few days now and I can't figure this one out.
So for every set/product there's some empty html, like so:
HTML
<div id="sets" class="clearfix">
// first set
<div class="set" data-handle="url" >
<div class="right">
<div class="products">
<div class="close"></div>
<div class="product">
/// in here comes the product data from json ///
</div>
<div class="set-bestellen">
<div class="link">
<a title="add" class="trigger"><span>add to cart</span></a>
</div>
</div>
</div><!-- .products -->
</div><!-- .right -->
<div class="image"></div>
</div>
// second set
<div class="set" data-handle="url" >
<div class="right">
<div class="products">
<div class="close"></div>
<div class="product">
/// in here comes the product data from json ///
</div>
<div class="set-bestellen">
<div class="link">
<a title="add" class="trigger"><span>add to cart</span></a>
</div>
</div>
</div><!-- .products -->
</div><!-- .right -->
<div class="image"></div>
</div>
// etc... can be as much as 10 sets
</div><!-- .#sets -->
Inside the above HTML .product there comes an automatically generated form. This form is generated like so:
Jquery
$('#sets .set').each( function(){
$(this).click(function(){
if($(this).hasClass('open')){
$('.close').click(function(){
$('#sets .product').fadeOut();
$('.products',this).animate({
width: 'toggle'},500, function() {
.......
});
});
} else {
.....
}
var url = $(this).data('handle')+'?format=json';
$.getJSON(url, function (data){
var product = data.product;
var $container = $('.products .product');
var productsHtml = [];
var fullurl = 'http://www.shop.com';
var variants = '';
$.each(product.related, function(index, rel){
var url = ''+fullurl+''+rel.url+'?format=json';
...... etc ...
var productHtml = '<div id="'+rel.id+'" class="p"><form method="post" id="product_configure_form" action="http://www.shop.com/cart/add/'+rel.vid+'/" name="formsub"><div class="foto"><img class="rollover" src="'+image+'" hover="'+image2+'" alt="'+rel.fulltitle+'"/></div><div class="prijs" data-price="'+rel.price.price_incl+'">€'+rel.price.price_incl+'</div><div class="varianten_'+rel.id+'">';
$.getJSON(url, function (data){
var rel = data.product;
var wqsSelectVariants = $('<div class="product-configure-variants tui" />');
var select = $('<select id="product_configure_variants"/>');
$.each(rel.variants, function (index, variant){
select.append('<option value=' + variant.id + '>' + variant.title + '</option>');
wqsSelectVariants.append(select);
});
$('.varianten_'+rel.id).html(wqsSelectVariants);
});
var price = rel.price.price_incl;
sum += price;
productHtml = productHtml + '</div></form></div>';
productsHtml.push(productHtml);
});
$('.total').text('€'+sum.toFixed(2));
productsHtml = productsHtml.join('')
$container.html(productsHtml);
});
}
});
});
etc....
<script type="text/javascript">
$(document).ready(function(){
$(".trigger").on("click", function(e){
e.preventDefault();
$('form[name="formsub"]').each(function(){
var variant = $('#product_configure_variants').val();
var $form = $(this);
$.ajax({
type: $form.attr('method'),
url: $form.attr('action')+variant+'/?quantity=1',
data: $form.serialize(),
success: function(data, status){
if(status == 'success'){
}else if(status == 'error'){
}
}
});
});
});
});
</script>
Does anyone know what's going wrong or give me some directions on how to fix that?

Try using $('form[name="formsub"]:visible') as your selector. That should give you just the visible forms instead of all the ones on the page.

Related

AngularJS: Add toggle function to an image inside ng-repeat

I am using ng-repeat for div element. I have a toggle function on image inside div element. However, when I click on image, function gets triggered but it is showing up same data for all divs. Below is the code.
HTML :
<div ng-repeat="item in items">
<div>
<img src="img/icon1.png" class="pull-right" ng-click="showDiv(item.itemId,$index)">
</div>
<div ng-show="hiddenDiv[$index]">
<div ng-repeat="student in studentData">
<div class="row">
<div>
<div>{{student.name}}</div>
<div>{{student.adress}}</div>
</div>
</div>
</div>
</div>
</div>
JS :
$scope.hiddenDiv=[];
$scope.showDiv=function(itemId,index) {
$scope.hiddenDiv[index] = !$scope.hiddenDiv[index];
var myResult = ListService.getList(url here);
myResult.then(function (data) {
if(data && data.list)
$scope.studentData = data.list;
});
}
Here, I am using same scope variable in all divs inside ng-repeat.
Updated Answer :
js :
$scope.studentData = [];
$scope.studentData[index] = data.list;
HTML :
If you want to have unique students for every item, you need to do something like this:
<div ng-repeat="item in items">
<div>
<img src="img/icon1.png" class="pull-right" ng-click="showDiv(item.itemId,$index)">
</div>
<div ng-show="hiddenDiv[$index]">
<div ng-repeat="student in item.studentData">
<div class="row">
<div>
<div>{{student.name}}</div>
<div>{{student.adress}}</div>
</div>
</div>
</div>
</div>
</div>
and js:
$scope.hiddenDiv=[];
$scope.showDiv=function(itemId,index) {
$scope.hiddenDiv[index] = !$scope.hiddenDiv[index];
var myResult = ListService.getList(url here);
myResult.then(function (data) {
if(data && data.list)
$scope.items[index].studentData = data.list;
});
}
or use the same as for hiddenDiv
$scope.hiddenDiv=[];
$scope.studentData = [];
$scope.showDiv=function(itemId,index) {
$scope.hiddenDiv[index] = !$scope.hiddenDiv[index];
var myResult = ListService.getList(url here);
myResult.then(function (data) {
if(data && data.list)
$scope.studentData[index].studentData = data.list;
});
}
and html:
<div ng-repeat="student in studentData[$index]">

why I see html tag in php using tinymce textarea for input?

I've a problem with TinyMCE.
When I load the TinyMCE textarea content (with jQuery) into my database, and then I see the result on a php page, I see html tag...in the picture you can find an example.
HTML
<div class="container pt">
<!-- +++++ Posts Lists +++++ -->
<div class="row mt">
<div class="col-lg-6 col-lg-offset-3 centered">
<h3>MY BLOG</h3>
<hr>
</div>
</div>
<div id="white">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2" id="menublog">
</div>
</div><!-- /row -->
</div> <!-- /container -->
</div><!-- /white -->
</div>
JQuery
$(document).ready(function() {
$("#Insert").click(function(){
event.preventDefault();
var user = "2", titolo = $('#titolo').val(), articolo = tinyMCE.activeEditor.getContent({format : 'raw'});
var id_immagine = $('#menuimmagini').val();
alert(id_immagine);
object = JSON.stringify({r: 'InsertPost', u: user, t: titolo, a: articolo, i:id_immagine});
$.post("server.php", { js_object: object },
function(msg){
console.log(msg);
if(msg)
{
alert("Post inserito con successo!");
location.reload();
}
});
});
});
OUTPUT JQUERY
$(document).ready(function() {
event.preventDefault();
object = JSON.stringify({r: 'InitializeBlog'});
$.post("servo.php", { js_object: object },
function(response)
{
var obj = jQuery.parseJSON(response);
$.each( obj, function( index ) {
$('#menublog').append("<p><img class=\"img-circle\" src=\"assets/img/user.png\" width=\"50px\" height=\"50px\"> <ba>Salvo Bertoncini</ba></p> <p><bd>Posted on "+obj[index].date+"</bd></p> <h4>"+obj[index].title+"</h4> <p><img class=\"img-responsive\" src=\"show.php?id="+obj[index].idimmagine+"\"></p> "+obj[index].articles+" <p>Continue Reading...</p><hr>");
});
}
);
});
All editor WYSWYG convert the content to html entities. you should use this library for example:
http://www.strictly-software.com/htmlencode

How should I be using ko.applyBindings ? I am getting an error when using this

My script is the following:
#using (Html.BeginFooterScripts())
{
<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"></script>
<script type="text/javascript" src="/Content/Northwestern/js/_libs/knockout.mapping/knockout.mapping.2.4.1.js"></script>
<script type="text/javascript" src="~/Content/Northwestern/js/views/TabPanel/location-card.js"></script>
<script type="text/javascript">
$(function() {
initialize();
});
</script>
<script>
$(function() {
// we must be on a detail page, we don't have a current location, so get it!
if (viewModel.currentLocation.latitude == 0 || viewModel.currentLocation.longitude == 0) {
geoLocate(function(location) {
viewModel.currentLocation.latitude = location.coords.latitude;
viewModel.currentLocation.longitude = location.coords.longitude;
displayLocation('#Model.LocationId');
}, geoLocateError);
} else {
displayLocation('#Model.LocationId');
}
});
</script>
}
my external script is :
/**********************************************
* Global variables
**********************************************/
var applied = false;
var geoLocateError = function onError(error) {
alert(error.message);
};
function ViewModel() {
var self = this;
self.currentLocation = {
latitude: 0,
longitude: 0
};
self.LocationId = ko.observable();
}
var viewModel = new ViewModel();
$(function () {
});
function initialize() {
ko.applyBindings(viewModel);
geoLocate(function(location) {
initLocation(location);
}, geoLocateError);
}
/**********************************************
* Location Functions
**********************************************/
function initLocation(location) {
viewModel.currentLocation = {
latitude: location.coords.latitude,
longitude: location.coords.longitude
};
}
function displayLocation(id) {
var apiUrl = '/api/northwestern/locations/getlocationbyid/' + id;
var data = {
'latitude': viewModel.currentLocation.latitude,
'longitude': viewModel.currentLocation.longitude
};
self.LocationId = id;
$.getJSON(apiUrl, data, function (response) {
var fragment = document.createDocumentFragment(),
container = document.createElement('div'),
viewModel = response;
fragment.appendChild(container);
// merge together all the display types into a commma-separated list
response.TypeListDisplay = $.map(response.Types, function (obj, t) {
return obj.ItemName;
}).join(', ');
ko.renderTemplate(
"location-detail-template",
viewModel, {
afterRender: function () {
$('#detail-container').html(container.innerHTML);
}
},
container
);
});
}
and here is the markup :
<div class="row">
<div class="col md-4">
<div class="section-content">
<div id="detail-container">
</div>
</div>
<script type="text/html" id="location-detail-template">
<div class="card card-locations-alt">
<div class="card-content">
<figure class="map">
<a target="_blank" href="https://www.google.com/maps/dir/Current+Location/#Model.Location.Latitude, #Model.Location.Longitude">
<img src="https://maps.googleapis.com/maps/api/staticmap?center=#Model.Location.Latitude,#Model.Location.Longitude&zoom=13&size=65x65&maptype=roadmap&markers=color:0x776EA7%7Clabel:%7C #Model.Location.Latitude,#Model.Location.Longitude">
</a>
</figure>
<div class="location-content" itemscope="" itemtype="http://schema.org/LocalBusiness">
<div class="location-name">
<h2 class="location-title" itemprop="name" data-bind="text: ItemName"></h2>
</div>
<div class="distance">
<i class="material-icons">place</i> <span data-bind="text: Distance.toFixed(1)"> Mi</span>
</div>
<div class="location-phone">
<a data-bind="attr: { 'href': clickToCallify(Phone), 'data-track-event': 'Find a Location - Detail', 'data-track-action': 'call icon' }" class="tel" itemprop="telephone"></a>
</div>
</div>
<div class="location-actions flex-container align-center no-print">
<a class="locations-icon flex-item tel" href="tel:8475358000">
<div class="call-icon uppercase">
<i class="material-icons">phone</i><br>
call
</div>
</a>
<a data-bind="attr: {'href' : 'https://www.google.com/maps/dir/Current+Location/' + Latitude + ',' + Longitude, 'data-track' : 'Find a Location', 'data-track-action' : 'directions', 'data-track-label' : ItemName }" target="_blank" class="locations-icon flex-item uppercase">
<i class="material-icons">directions</i><br>
directions
</a>
<a href="" class="location-detail locations-icon flex-item uppercase">
<i class="material-icons">info</i><br>
details
</a>
</div>
</div>
</div>
</script>
</div>
<div class="col md-7">
#(new HtmlString(Model.Body))
</div>
</div>
<br />
}
now, when I applyBindingsviewModel) under the initialize function, it works the first time, then it throws an error "cannot apply bindings muliple times for the same element.
I have tried to do a ko.cleanNode, but that did not work.
when i take the applyBindings off, I don't get the error, but the program skips over all but the last page component.
The problem is cause binding applies two times to the same elements. So the can be some other knockout binding in your code or initialize function executes second time.
If you have few models which you would like to bind to your page you can use second parameter of applyBindings, if you do not pass it model binds to body.
Optionally, you can pass a second parameter to define which part of the document you want to search for data-bind attributes.
http://knockoutjs.com/documentation/observables.html

Creating a search query using JSON news api

So I got to create a search query based on an written javascript file (below) and I also have to use this URL to create the search query. At the end of the URL, you can add any search term you like. For example, we will search about food : https://ajax.googleapis.com/ajax/services/search/news?v=1.0&q=food
Can anyone tell me what to do to create it?
$(document).bind('pageinit', function(ev){
$('#search').on('keyup', function(e){
if(e.keyCode == 13){
$.get('search.php', {"q": $('#search').val()}, function(data){
var json = JSON.parse(data);
console.log(json);
$('#results').listview('refresh');
});
}
});
First:
You can access this api direct with javascript (jquery).
If you try it with the normal url https://ajax.googleapis.com/ajax/services/search/news?v=1.0&q=food you get an error because of the "Access-Control-Allow-Origin" Settings.
If you append "&callback=?" you will get proper data returned
Now you have to append the returned data to your listview.
The important thing to know is: what is returned. In your code the value of data or the value of var json Since you dont provide any of your php. i can only do it direct with the jquery getJSON Call.
$(document).bind('pageinit', function(ev) {
$('#search').on('keyup', function(e) {
if (e.keyCode == 13) {
// The Base URL
var baseUrl = 'https://ajax.googleapis.com/ajax/services/search/news?v=1.0&q=';
// The question from the inputfield
var q = $('#search').val();
// putting the url togehter and append &callback=?
var url = baseUrl + q + "&callback=?";
console.log(url);
// Call The API for a JSON
$.getJSON(url, function() {
console.log("success");
}).done(function(data) {
console.log("second success");
console.log(data.responseData.results);
// create a var for the results and append a header
var results = '<li data-role="list-divider">Results</li>';
$.each(data.responseData.results, function(index, item) {
results += '<li>';
results += item.title;
results += '</li>';
});
// clear the results . append the results .refresh the listview
$('#results').empty().append(results).listview('refresh');
}).fail(function() {
console.log("error");
}).always(function() {
console.log("always");
});
}
});
});
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<!-- jQuery Mobile -->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js"></script>
<!-- page1 -->
<div data-role="page" id="page1" data-title="page1">
<!-- Header -->
<div data-role="header" data-position="fixed">
<h1>Page 1</h1>
</div>
<!-- /Header -->
<!-- Content -->
<div role="main" class="ui-content">
<label for="search">Search Input:</label>
<input name="search" id="search" value="" placeholder="palceholder" type="search">
<ul data-role="listview" id="results" data-inset="true">
</ul>
<script>
</script>
</div>
<!-- /Content -->
</div>
<!-- /page1 -->
$(document).bind('pageinit', function(ev) {
$('#search').on('keyup', function(e) {
if (e.keyCode == 13) {
// The Base URL
var baseUrl = 'https://ajax.googleapis.com/ajax/services/search/news?v=1.0&q=';
// The question from the inputfield
var q = $('#search').val();
// putting the url togehter and append &callback=?
var url = baseUrl + q + "&callback=?";
console.log(url);
// Call The API for a JSON
$.getJSON(url, function() {
console.log("success");
}).done(function(data) {
console.log("second success");
console.log(data.responseData.results);
// create a var for the results and append a header
var results = '<li data-role="list-divider">Results</li>';
$.each(data.responseData.results, function(index, item) {
results += '<li>';
results += item.title;
results += '</li>';
});
// clear the results . append the results .refresh the listview
$('#results').empty().append(results).listview('refresh');
}).fail(function() {
console.log("error");
}).always(function() {
console.log("always");
});
}
});
});
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<!-- jQuery Mobile -->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js"></script>
<!-- page1 -->
<div data-role="page" id="page1" data-title="page1">
<!-- Header -->
<div data-role="header" data-position="fixed">
<h1>Page 1</h1>
</div>
<!-- /Header -->
<!-- Content -->
<div role="main" class="ui-content">
<label for="search">Search Input:</label>
<input name="search" id="search" value="" placeholder="palceholder" type="search">
<ul data-role="listview" id="results" data-inset="true">
</ul>
<script>
</script>
</div>
<!-- /Content -->
</div>
<!-- /page1 -->

how to pass id to another html page

Below is my javascript in nextPage.js. When I click on it, it must pass category_id to the reportlist.html page. Please help me.
var base_url = "http://dev.edfutura.com/nithin/jps/edfuturaMob/";
$(document).on("pageinit", "#catlist", function() {
var submitUrl = base_url+"categorylist/get_categorylist";
$.ajax({
url: submitUrl,
dataType: 'json',
type: 'POST',
success: function(response) {
var categoryList = $('#category');
var category;
for(var i = 0, len = response.length; i < len; i++) {
category = response[i];
var a = $('<a>').attr('href', 'reportlist.html').html(category.category_name);
categoryList.append($('<li>').attr('id', category.category_id).append(a));
}
},
error: function() {
alert("error");
}
});
My first page is nextPage.html and my category_names are stored in a list as links through JS.
<body id="category_id">
<div data-role="page" id="catlist">
<div id="loading"></div>
<div data-role="header" data-position="fixed" data-theme="b">
<h1>category</h1>
</div>
<div data-role="main" class="ui-content">
<form id="nextForm" >
<ul data-role="listview" data-inset="true" id="category">
<li id="catid"></li>
</ul>
</form>
</div>
</div>
</body>
If you want to pass some data when you change the page, you must use request parameters
When you want to pass data in href link, you should use GET request like this:
reportlist.html?category_id=12
Then you can read your data similarly to this https://stackoverflow.com/a/979995/4772988

Categories

Resources