i'm trying to post values inappbrowser but no success.
it does open browser twice and no data posted.
var options = {
email: 'test#email.com',
item_id: 1234,
reference: 1234,
item_descr: 'description',
item_quant: 1,
item_valor: 50 * 100
};
var form = document.createElement("form");
var url = "https://testurl.com";
form.setAttribute("method","post");
form.setAttribute("action",url);
for (var data in options) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", data);
hiddenField.setAttribute("value", options[data]);
form.appendChild(hiddenField);
}
document.body.appendChild(form);
var ref = cordova.InAppBrowser.open(url, '_blank', 'location=yes');
if(ref){
form.submit();
}
Here's another way of posting a HTML form via the InAppBrowser using a dataUrl:
var pageContent = '<html><head></head><body><form id="loginForm" action="YourPostURL" method="post">' +
'<input type="hidden" name="key1" value="' + YourValue1 + '">' +
'<input type="hidden" name="key" value="' + YourValue2 + '">' +
'</form> <script type="text/javascript">document.getElementById("loginForm").submit();</script></body></html>';
var pageContentUrl = 'data:text/html;base64,' + btoa(pageContent);
var browserRef = window.cordova.InAppBrowser.open(
pageContentUrl ,
"_blank",
"hidden=no,location=no,clearsessioncache=yes,clearcache=yes"
);
you can do it like this
var options = {
email: 'test#email.com',
item_id: 1234,
reference: 1234,
item_descr: 'description',
item_quant: 1,
item_valor: 50 * 100
};
var script = 'var form = document.createElement("form");';
script += 'var url = "https://testurl.com";';
script += 'form.method="post"';
script += 'form.setAttribute("action",url);';
for (var data in options) {
script += 'var hiddenField = document.createElement("input");';
script += 'hiddenField.setAttribute("type", "hidden");';
script += 'hiddenField.setAttribute("name","' + data +'");';
script += 'hiddenField.setAttribute("value","' + options[data] + '");';
script += 'form.appendChild(hiddenField);';
}
script += 'document.body.appendChild(form)';
var ref = cordova.InAppBrowser.open(url, '_blank', 'location=yes');
script += 'form.submit();';
and then execute script in the inappbrowser using on the loadstop event like this
ref.addEventListener('loadstop', onLoadStopFunction);
onLoadStopFunction(params){
ref.executeScript({ code: script }, executeScriptCallBack);
}
function executeScriptCallBack(params) {
if (params[0] == null) {
//error message
}
}
there are many other ways to do it.
You need to fill in the dynamic feild values on loadstop or load start event by using Execute Script.
First Bind the events , when you open the link:
{
var url= 'yourURL';
if( device.platform === "Android"){
ref =cordova.InAppBrowser.open(url, "_blank",'location=no,clearcache=yes,hardwareback=no,zoom=no');
}else{
ref =cordova.InAppBrowser.open(url, "_blank",'location=no,clearcache=yes,closebuttoncaption=Go back to App,toolbar=yes,presentationstyle=formsheet');
}
ref.addEventListener('loadstart',onBrowserLoadStart);
ref.addEventListener('loadstop',onBrowserLoadStop);
ref.addEventListener('loaderror', onBrowserError);
ref.addEventListener('exit', onBrowserClose);
}
Then on onBrowserLoadStop, check if its the right page to Post form:
function onBrowserLoadStop(event){
var cUrl= 'myformURL';
if(event.url===cUrl){
var msg;
var newHtml=YourFormHTML;
var withoutScriptHtml = $(newHtml.bold());
withoutScriptHtml.find('script').remove();
msg= " var formDiv = document.createElement('div'); formDiv.id='someFormDiv'; ";
msg+= " formDiv.innerHTML='" + withoutScriptHtml.html()+ "';" ;
msg += " document.getElementById('outerDiv').appendChild(formDiv);"; //outerDiv should be on the html page residing at cUrl
msg += " document.getElementById('yourFormName').submit();";
//console.log("the message: "+ msg);
ref.executeScript(
{
code: msg
},
function(values){
console.log(JSON.stringify(values));
}
);
}
}
From the 1 page:
window.localStorage.setItem('tempForm', JSON.stringify(form));
location.replace('page2.html');
2 page:
var passedForm = $.parseJSON(window.localStorage.getItem('tempForm'));
You can do that with all objects.
Related
I am working on a website and I am looking to make the recipes pages dynamic. I created a JSON test database, created a JS file that retrieves values from the JSON file and displays them in appropriate divs on the page.
What i want to do is be able to choose the respectful JSON for each recipe and display it on the same page when a user clicks a link in the sidebar without having to create a ton of blank HTML pages with the same divs.
Below is my code. Hoping someone can help guide me thanks!
(function() {
'use strict';
var url = 'my json url';
$.getJSON(url, function(json) {
//store json data into variable
var data = (json);
//store data in empty string
var title = '';
var image = '';
var directions = '';
var prep = '';
var cook = '';
var serve = '';
//retrieve values from dataArray
$.each(data[0], function (i, item) {
title += '<h1>' + item.recipeName + '</h1>';
image += '<img src="' + item.imageURL + '">';
directions += '<p>' + item.directions + '</p>';
prep += '<strong>' + item.prepTime + '</strong>';
cook += '<strong>' + item.cookTime + '</strong>';
serve += '<strong>' + item.servInfo + '</strong>';
});
//append results to div
$('#recipeTitle').html(title);
$('#recipeImage').html(image);
$('#recipeDirections').html(directions);
$('#recipePrep').html(prep);
$('#recipeCook').html(cook);
$('#recipeServes').html(serve);
var ul = $('<ul class="nav nav-stacked">').appendTo('#recipeIngredients');
$.each(data[0][0].ingredients, function(i, item) {
ul.append($(document.createElement('li')).text(item));
});
});
})();
new code`(function() {
function callback(json){
//store json data into variable
var data = (json);
//store data in empty string
var title = '';
var image = '';
var directions = '';
var prep = '';
var cook = '';
var serve = '';
//retrieve values from dataArray
$.each(data[0], function (i, item) {
title += '<h1>' + item.recipeName + '</h1>';
image += '<img src="' + item.imageURL + '">';
directions += '<p>' + item.directions + '</p>';
prep += '<strong>' + item.prepTime + '</strong>';
cook += '<strong>' + item.cookTime + '</strong>';
serve += '<strong>' + item.servInfo + '</strong>';
});
//append results to div
$('#recipeTitle').html(title);
$('#recipeImage').html(image);
$('#recipeDirections').html(directions);
$('#recipePrep').html(prep);
$('#recipeCook').html(cook);
$('#recipeServes').html(serve);
var ul = $('<ul class="nav nav-stacked">').appendTo('#recipeIngredients');
$.each(data[0][0].ingredients, function(i, item) {
ul.append($(document.createElement('li')).text(item));
});
}
$('#pasta').click(function(){
$('#recipeIngredients').empty();
//get the url from click coresponding to the item
$.getJSON(url,callback);
});
//intially load the recipies with the URL
var url = '';
$.getJSON(url,callback);
})();`
to achieve code reusability , try calling the $.getJSON() with a reusable function (callback) on click of the link in the sidebar
(function() {
function callback(json){
//store json data into variable
var data = (json);
//store data in empty string
var title = '';
var image = '';
var directions = '';
var prep = '';
var cook = '';
var serve = '';
.... //rest of the code
...
$.each(data[0][0].ingredients, function(i, item) {
ul.append($(document.createElement('li')).text(item));
});
}
$('.sidebarLink').click(function(){
$('#recipeIngredients').empty()
//get the url from click coresponding to the item
$.getJSON(url,callback);
});
//intially load the recipies with the URL
var url = 'my json url';
$.getJSON(url,callback);
})();
I'm currently using the jQuery get method to read a table in another page which has a list with files to download and links to others similar webpages.
$.get(filename_page2, function(response, status){
var data = $("<div>" + response + "</div>");
var target_element = data.find(target_element_type_page2 + '#' + target_element_id_page2)[0];
var container = document.getElementById(element_change_content_page1);
if (typeof target_element !== "undefined"){
var rows = target_element.rows;
for (var i = 1, n = rows.length; i < n; i++) {
var table = rows[i].cells[1].getElementsByTagName("TABLE")[0];
var isFolder = table.getAttribute("CType") == "Folder";
var elem = table.rows[0].cells[0];
var text = elem.innerText || elem.textContent;
var link = elem.getElementsByTagName("A")[0].getAttribute("href");
if (!isFolder) {
container.innerHTML += "<li class=\"mainfolderfile\">" + "<a class=\"filelink\" href=\"" + link + "\">" + text + "</a></li>";
} else {
container.innerHTML += "<li class=\"folderlist\">" + "<a class=\"folderlink\" onclick=\"open_submenu(this)\" href=\"#\">" + text + "</a><ul></ul></li>";
var elem_page1 = container.getElementsByTagName("li");
var container_page1 = elem_page1[elem_page1.length - 1].getElementsByTagName("ul")[0];
create_subfolder(container_page1, link);
}
}
} else {
container.innerHTML += "<li class=\"mainfolderfile\">" + "<a class=\"filelink\" href=\"" + "#" + "\">" + "Error..." + "</a></li>";
}
}, page2_datatype);
This is working fine, and all the folders and files are being listed. But when I try to do the same thing with the folders (calling the create_subfolder function) and create sublists with their subfolders and files, I'm getting a weird behavior.
function create_subfolder(container2, link1) {
$.get(link1, function(response, status){
var data = $("<div>" + response + "</div>");
var target_element = data.find("table" + "#" + "onetidDoclibViewTbl0")[0];
if (typeof target_element !== "undefined"){
var rows = target_element.rows;
for (var i = 1, n = rows.length; i < n; i++) {
var table = rows[i].cells[1].getElementsByTagName("TABLE")[0];
var elem = table.rows[0].cells[0];
var text = elem.innerText || elem.textContent;
var link2 = elem.getElementsByTagName("A")[0].getAttribute("href");
//nothing is changed in the webpage. The modifications in the html don't appear
container2.innerHTML += "<li>" + text + "</li>";
}
}
alert(container2.innerHTML); // Print the html with all the modifications
}, "html");
}
The second get(), inside the create_subfolder() function are not changing anything in the webpage, so no sublist is created. But, when I call the alert() function at the end of the get() function, it prints the code with all the modifications it should have made in the html at the second get callback. I believe the problem is related with the asynchronous behavior of the get function but I don't know exactly why. Any guess?
My code works when i'm slowly stepping through in debug mode, but when i try it in real time, it doesn't seem to want to update the page.
Here is the javascript:
searchButton = document.getElementById("searchButton");
var searchBox = document.getElementById('searchBox');
searchButton.addEventListener("click", searchItem);
function searchItem(){
searchString = searchBox.value;
article = document.getElementById("homeSection");
var xmlhttp = getXmlHttpRequestObject();
var string = '';
if(xmlhttp){
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
var response = JSON.parse(xmlhttp.responseText);
for(var i=0; i<response.length; i++){
string += '<section class="searchResult">';
string += '<h1>' + response[i].Name + '</h1>';
string += '<p class="photo"></p>';
string += '<p class="price">£' + response[i].Price + '</p>';
string += '<p class="productID">ID: ' + response[i].ID + '</p>';
string += '<p class="description">' + response[i].Description + '</p>';
string += '<p class="quantity">Quantity: ' + response[i].Quantity + '</p>';
string += '</section>';
}
article.innerHTML = '<h1>Search</h1><section><h1 class="bottomBorder">You searched for: "' + searchString + '"</h1></section>';
article.innerHTML += string;
}
};
xmlhttp.open("GET", "search.php?search=" + searchString, true);
xmlhttp.send(null);
}
}
Two things you need to do
Cancel the click action that is triggering the function
Second encode the content you are sending to the server
Updated code:
function searchItem (event){
event.preventDefault();
var searchStringEnc = encodeURIComponent(searchBox.value);
...
xmlhttp.open("GET", "search.php?search=" + searchStringEnc, true);
It's not working on IE, rest of the responses and suggestions here are correct. Why IE only? because you have undefined vars:
searchString = searchBox.value;
correct
var searchString = searchBox.value;
To check if your script is truly working just alert the formatted string.
article.innerHTML += string;
alert(string);
then you will know what is wrong.
If you're using a button in a form to post with AJAX, make sure the button type="button" or it will act as a submit button and submit the form. This little feature cost me days of frustration!!!
So i am learning Javascript and trying to set and retrieve a cookie, my code all looks to be ok but there is obviously a problem here.
function init()
{
var panel = document.getElementById("panel");
var user = escape("Dan, 000456");
var expiry = new Date();
expiry.setTime(expiry.getTime() + (7*24*60*1000) );
document.cookie = "myData=" + user + ";" + "expires=" + expiry.toGMTString() + ";";
if (document.cookie)
{
var cookieString = unescape(document.cookie);
var list = cookieString.split("=");
if (list[0] === "myData")
{
var data = list[1].split(",");
var userName = data[0];
var userAcct = data[1];
}
}
panel.innerHTML += "Cookie String:" + cookieString;
panel.innerHTML += "<br>Split List:" + list;
panel.innerHTML += "<br>User Name:" + userName;
panel.innerHTML += "<br>User Account:" + userAcct;
}
document.addEventListener("DOMContentLoaded",init, false);
When I look in the results they are not what I am expecting to see:
Cookie String:undefined
Split List:undefined
User Name:undefined
User Account:undefined
Your main issue is now that you have corrected your syntax errors is that the following line:
var user = escape("Dan, 000456");
note: I believe the escape function is now deprecated?
change your javascript to this and make sure your browser allows cookies:
function init(){
var panel = document.getElementById("panel");
var user = ["Dan, 000456"]; //<--change #1
var expiry = new Date();
expiry.setTime(expiry.getTime() + (7*24*60*1000) );
//change #2 below added the array index of user to set the cookie value for myData
document.cookie = "myData=" + user[0] + ";" + "expires=" + expiry.toGMTString();
if (document.cookie)
{
var cookieString = unescape(document.cookie);
var list = cookieString.split("=");
if (list[0] === "myData")
{
var data = list[1].split(",");
var userName = data[0];
var userAcct = data[1];
}
}
panel.innerHTML += "Cookie String:" + cookieString;
panel.innerHTML += "<br>Split List:" + list;
panel.innerHTML += "<br>User Name:" + userName;
panel.innerHTML += "<br>User Account:" + userAcct;
}
document.addEventListener("DOMContentLoaded",init, false);
Also make sure your html looks like this:
<div id="panel">Test</div>
You can remove the Test from the div in the html above if you want. The Test value should be replaced by values in your panel.innerHTML assignments.
I have a website which includes this RSS JavaScript. When I click feed, it opens same page, but I don't want to do that. How can I open with blank page? I have my current HTML and JavaScript below.
HTML CODE
<tr>
<td style="background-color: #808285" class="style23" >
<script type="text/javascript">
$(document).ready(function () {
$('#ticker1').rssfeed('http://www.demircelik.com.tr/map.asp').ajaxStop(function () {
$('#ticker1 div.rssBody').vTicker({ showItems: 3 });
});
});
</script>
<div id="ticker1" >
<br />
</div>
</td>
</tr>
JAVASCRIPT CODE
(function ($) {
var current = null;
$.fn.rssfeed = function (url, options) {
// Set pluign defaults
var defaults = {
limit: 10,
header: true,
titletag: 'h4',
date: true,
content: true,
snippet: true,
showerror: true,
errormsg: '',
key: null
};
var options = $.extend(defaults, options);
// Functions
return this.each(function (i, e) {
var $e = $(e);
// Add feed class to user div
if (!$e.hasClass('rssFeed')) $e.addClass('rssFeed');
// Check for valid url
if (url == null) return false;
// Create Google Feed API address
var api = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q=" + url;
if (options.limit != null) api += "&num=" + options.limit;
if (options.key != null) api += "&key=" + options.key;
// Send request
$.getJSON(api, function (data) {
// Check for error
if (data.responseStatus == 200) {
// Process the feeds
_callback(e, data.responseData.feed, options);
}
else {
// Handle error if required
if (options.showerror) if (options.errormsg != '') {
var msg = options.errormsg;
}
else {
var msg = data.responseDetails;
};
$(e).html('<div class="rssError"><p>' + msg + '</p></div>');
};
});
});
};
// Callback function to create HTML result
var _callback = function (e, feeds, options) {
if (!feeds) {
return false;
}
var html = '';
var row = 'odd';
// Add header if required
if (options.header) html += '<div class="rssHeader">' + '' + feeds.title + '' + '</div>';
// Add body
html += '<div class="rssBody">' + '<ul>';
// Add feeds
for (var i = 0; i < feeds.entries.length; i++) {
// Get individual feed
var entry = feeds.entries[i];
// Format published date
var entryDate = new Date(entry.publishedDate);
var pubDate = entryDate.toLocaleDateString() + ' ' + entryDate.toLocaleTimeString();
// Add feed row
html += '<li class="rssRow ' + row + '">' + '<' + options.titletag + '>' + entry.title + '</' + options.titletag + '>'
if (options.date) html += '<div>' + pubDate + '</div>'
if (options.content) {
// Use feed snippet if available and optioned
if (options.snippet && entry.contentSnippet != '') {
var content = entry.contentSnippet;
}
else {
var content = entry.content;
}
html += '<p>' + content + '</p>'
}
html += '</li>';
// Alternate row classes
if (row == 'odd') {
row = 'even';
}
else {
row = 'odd';
}
}
html += '</ul>' + '</div>'
$(e).html(html);
};
})(jQuery);
try change this:
html += '<li class="rssRow '+row+'">' +
'<'+ options.titletag +'>'+ entry.title +'</'+ options.titletag +'>'
to
html += '<li class="rssRow '+row+'">' +
'<'+ options.titletag +'>'+ entry.title +'</'+ options.titletag +'>'