Dynamic form on website - javascript

Hi I'm trying to show a form when the edit button is pressed and then once the save button for the form is pressed I'd like to edit my database and show the new information. I need to do this without refreshing the page as well. I'm new to jquery but below is what I've written so far, however, the event.preventDefault(); function isn't working for some reason and the forms action is run. Any help as to why my code is failing would be greatly appreciated thanks!
<!doctype html>
<html lang="en">
<head>
<!-- Irrelevant scripts from the site go here -->
</head>
<body>
<!-- Lots of other code from the site is here -->
<div id="jqueryFunction"></div>
<script text="text/javascript">
function checkEdit(ID){
//Check the fields make sure they're not empty
return true;
}
</script>
<script text="text/javascript">
function editV(ID, titleOld, descOld){
document.getElementById("divForm" + ID).innerHTML =
"<form name=\"editDiv" + ID + "\" id=\"editDiv" + ID + "\" onsubmit=\"return checkEdit(" + ID + ");\" action=\"editvid.php\" method=\"POST\">" +
"<input type=\"hidden\" name=\"divID\" id=\"divID\" value=\"" + ID + "\"/>" +
"<input type=\"text\" name=\"titleNew" + ID + "\" id=\"titleNew" + ID + "\" value=\"" + titleOld + "\"/><br>" +
"<textarea name=\"descNew" + ID + "\" id=\"descNew" + ID + "\">" + descOld + "</textarea><br>" +
"<input type=\"submit\" value=\"Save\" class=\"alt_btn\">" +
"</form>";
document.getElementById("jqueryFunction").innerHTML =
"<script src=\"js/jquery-1.5.2.min.js\" type=\"text/javascript\"><\/script>" +
"<script>" +
"$(function(){" +
"$('form[name=\"editDiv" + ID + "\"]').on('submit', function(event){" +
"event.preventDefault();" +
"var form = this;" +
"$.ajax({" +
"url: $(form).attr('action')," +
"type: \"POST\"," +
"data: {divID:$(form.divID).val(), titleN:$(form.titleNew).val(), descN:$(form.descNew).val()}," +
"success: function (response) {" +
"alert('response');" +
"}" +
"});" +
"});" +
"});" +
"<\/script>";
}
</script>
</body>

There are many cleaner solutions.
I just would hide the form and then display it by clicking edit.
Here is an example with fetching your parents id.
<!DOCTYPE HTML>
<html>
<head>
<title>Test</title>
<style>
.editForm {
display:none;
}
</style>
<script>
</script>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('.edit').click(function() {
$('.editForm').fadeIn();
});
$('a.submit').click(function() {
// get parents id
var parentId = $(this).parent().parent().parent().attr('id');
$.ajax({
type: "POST",
url: "some.php",
data: { divId: parentId, aName: $('.aName').val() }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
</script>
<body>
<div id="anId">
<a class="edit">edit</a>
<form class="editForm">
<div>
<input type="text" class="aName" />
Submit
</div>
</form>
</div>
</body>
</html>

Related

try to get data fro json

I will try to get data from url json but nothing append
this is my code vere simple:
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#driver").click(function(event){
$.getJSON('http://api.walmartlabs.com/v1/items/54732749?format=json&apiKey=fc5cku3vruymkhxhvtenm9bk', function(jd) {
$('#stage').html('<p> Name: ' + jd.item.name + '</p>');
$('#stage').append('<p>Age : ' + jd.item.itemId+ '</p>');
$('#stage').append('<p> Sex: ' + jd.item.salePrice+ '</p>');
});
});
});
</script>
</head>
<body>
<p>Click on the button to load result.html file:</p>
<div id = "stage" style = "background-color:#cc0;">
STAGE
</div>
<input type = "button" id = "driver" value = "Load Data" />
</body>
</html>
some can know why I don't see nothing?
Your data is not contained in item object you need to access it directly.
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#driver").click(function(event){
$.getJSON('http://api.walmartlabs.com/v1/items/54732749?format=json&apiKey=fc5cku3vruymkhxhvtenm9bk', function(jd) {
$('#stage').html('<p> Name: ' + jd.name + '</p>');
$('#stage').append('<p>Age : ' + jd.itemId+ '</p>');
$('#stage').append('<p> Sex: ' + jd.salePrice+ '</p>');
});
});
});
</script>
The problem is with a cross domain Request.
You could make an ajax with dataType: "jsonp" to solve your issue.
Look here for better explanation.
note
as already pointed out, you should access to your response data without the .item, so jd.item.name become jd.name
$(document).ready(function() {
$("#driver").click(function(event) {
$.ajax({
url: 'http://api.walmartlabs.com/v1/items/54732749',
data: {
format: 'json',
apiKey: 'fc5cku3vruymkhxhvtenm9bk'
},
dataType: 'jsonp',
success: function(jd) {
console.log(jd);
$('#stage').html('<p> Name: ' + jd.name + '</p>');
$('#stage').append('<p>Age : ' + jd.itemId + '</p>');
$('#stage').append('<p> Sex: ' + jd.salePrice + '</p>');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Click on the button to load result.html file:</p>
<div id="stage" style="background-color:#cc0;">
STAGE
</div>
<input type="button" id="driver" value="Load Data" />

jQuery Mobile Open individual json object on new page

I'm working on a news mobile app and so far I've been able to pull the JSON string and display on my page however I'm not sure how to open each individual news item on a new jquery mobile page.
Here's my code below.
Thanks for your help.
$.getJSON("http://kyivcool.veedoogroup.com/?json=11", function(data){
$(data.posts)
$('#cont').append("<div>");
$(data.posts).each(function(key, post){
$('#cont').append( "<div class='img-thumb'><a href='#fullText'><img src='" + post.thumbnail+ "'></a></div>" );
$('#cont').append( "<div class='title-post'><a href='"+ post.url+ "'><h4>" + post.title + "</h4></a></div>" );
$('#cont').append( "<div class='author-post'>" + post.author.name + "</div>" );
$('#cont').append( "<div class='excerpt-post'>" + post.excerpt + "</div>" );
$('#cont').append( "<hr>" );
alert(data.posts[0].title_plain)});
})
You could save the json array of posts to a global javascript variable.
Then put the post id in the link as a data-attribute.
Then handle the click event of the links, get the post id, and find the content in the global array. finlly put the content in a DIV in the separate page.
var thePosts;
$(document).on("pagecreate","#page1", function(){
$.ajax({
url: 'http://kyivcool.veedoogroup.com/?json=11',
dataType : 'jsonp',
success : function (data) {
thePosts = data.posts; //SAVE TO GLOBAL VARIABLE
$('#cont').append("<div>");
$(data.posts).each(function(key, post){
$('#cont').append( "<div class='img-thumb'><a data-postid='"+ post.id+ "' href='#fullText' class='fullTextLink'><img src='" + post.thumbnail+ "'></a></div>" );
$('#cont').append( "<div class='title-post'><a href='"+ post.url+ "'><h4>" + post.title + "</h4></a></div>" );
$('#cont').append( "<div class='author-post'>" + post.author.name + "</div>" );
$('#cont').append( "<div class='excerpt-post'>" + post.excerpt + "</div>" );
$('#cont').append( "<hr>" );
});
}
});
$(document).on("click", ".fullTextLink", function(){
var id = $(this).data("postid");
for (var i=0; i<thePosts.length; i++){
if (thePosts[i].id == id) {
$("#fullTextDiv").html(thePosts[i].content);
break;
}
}
});
});
DEMO

JQuery Form Submission with enter key AJAX API

I've tried various solutions, but none are suitable for my particular case!
How can I make it so that when the user presses 'Enter' the form submits & searches.
I also want to try and remove the JavaScript from the HTML document, and move it to the ajax.js document & select it.
I'm unsure of the correct syntax to do so.
I am using rotten tomatoes API with AJAX by the way.
search.php
<form name="myform" action="" method="GET"><h3>Search for a movie here:</h3><br>
<input type="text" id="inputbox" value="">
<input type="button" id="button" value="Go!" onClick="filmlist(this.form)">
</form>
ajax.js
function filmlist (form) {
$('#films table').empty(); //removes previous search results before adding the new ones.
var apikey = "frceg2d5djxezaedgm3qq94h";
var baseUrl = "http://api.rottentomatoes.com/api/public/v1.0";
var moviesSearchUrl = baseUrl + '/movies.json?apikey=' + apikey;
var query = form.inputbox.value; //uses the value from the input box as the query search
// sends the query
$.ajax({
url: moviesSearchUrl + '&q=' + encodeURI(query),
dataType: "jsonp",
success: searchCallback
});
// receives the results
function searchCallback(data) {
$('#films table').append('Found ' + data.total + ' results for ' + query);
var movies = data.movies;
$.each(movies, function(index, movie) {
$('#films table').append('<tr><td width="70" rowspan="2"><a href="' + movie.links.alternate +
'" title="Click here to view film information for ' + movie.title + '."><img class="ajaximage" src="'
+ movie.posters.thumbnail + '" /></a></td><td class="ajaxfilmlisttitle"><h3><a href="' + movie.links.alternate +
'" title="Click here to view film information for ' + movie.title + '.">' + movie.title + '</a></h3>Release year: '
+ movie.year + '</td></tr><tr><td class="ajaxfilmlistinfo">Audience Score: ' + movie.ratings.audience_score +
'%<br>' + 'Cinema Release Date: ' + movie.release_dates.theater +
'<br>Runtime: ' + movie.runtime + ' minutes</td></tr>');
});
}
}
$("form").submit(function(){
$.ajax({
url: moviesSearchUrl + '&q=' + encodeURI(query),
dataType: "jsonp",
success: searchCallback
});
return false;
});
or you can just return false at the end of your filmlist function.
You can detect an enter keypress in the #inputbox element with the following jQuery code:
$('#inputbox').keyup(function(e)
{
if(e.keyCode == 13)
{
//do your stuff
}
});
You can also use $('#inputbox').change() to directly load movies when the user is typing.
Do not forget that some old or mobile browser do not have JavaScript support. Always build an server side solution as fallback.

jquery to append a table to div

i have a div id.i have to append a table with values to the div.
<div id="testResult" style="padding-left: 120px; "></div>
am doing follwing steps but it is not working.
$.ajax({
url: '/getReports',
cache: false
}).done(function (html) {
if (html != "") {
$('#testResult').show();
var htm = "";
var string1 = '<table border="1"><tr><td>No</td><td>Testcase</td> <td>OS</td> <td>Browser</td> <td>Result</td></tr></table>';
$.each(html, function (i, data) {
string1 + = '<tr><td rowspan="3">1</td><td rowspan="3">' + data.status.test + '</td><td rowspan="3"><!--OS--></td><td>' + data.status.bwser + '</td> <td> ' + data.status.report + ' </td></tr>';
});
$('#testResult ').append(string1);
$("#testResult").html("<br/><br/>");
$("#testResult").html("<p>" + htm + "</p>");
}
}).fail(function () {
$("#testResult").html("Failed to run the test");
$('#edit ').removeAttr("disabled");
});
$("#testResult").html("<br/><br/>") and $("#testResult").html("<p>" + htm + "</p>") will overwrite contents of your "testResult" DIV. So, replace this
$('#testResult ').append(string1);
$("#testResult").html("<br/><br/>");
$("#testResult").html("<p>" + htm + "</p>");
}
with
$('#testResult ').append(string1);
$("#testResult").append("<br/><br/>");
$("#testResult").append("<p>" + htm + "</p>");
}
.append(): Will add or append extra strings to the existing contents of the DIV
where as
.html(): Will removes or overwrite the existing contents of the DIV with newer one.
This is the main difference between .append() and .html().
edit this part
$("#testResult").append("<br/><br/>");
Remove this part-->
$("#testResult").html("<p>" + htm + "</p>");
htm is empty string, as you never concatenate any string to it

javascript Alert isn't working from inside getjson function

I have this script that creates a table from a json file. Each row has a clickale element that loads another json file. When the second json file loads I want to alert the user, but with the script I have the alert isnt working. What am I doing wrong? I am very new to javascript so it might just be a simple mistake.
$.each(result["auctionInfo"], function(i, player){
$("#curAuctions").append('<tr id="row'+i+'"><td>' + player["sellerName"] + "</td><td>" + style[player["itemData"]["playStyle"]] + "</td><td>" + player["itemData"]["preferredPosition"] + "</td><td>" + player["itemData"]["injuryType"] + "</td><td>" + player["itemData"]["contract"] + "</td><td>" + player["startingBid"] + '</td><td>' + player["buyNowPrice"] + '</td><td><div id="countdown'+i+'"></div></td><td style="text-align:center;" ><a id="buy'+i+'" data-id="'+ player["tradeId"] +'" data-price="'+ player["buyNowPrice"] +'" title="" class="button greenB" style="margin: 5px;"><span>Buy</span></a></td></tr>');
$('#countdown'+i).countdown({until: +player["expires"], format: 'HMS', compact: true});
$("#activeTable").tablesorter();
$( "#buy"+i ).bind( "click", function() {
$(this).replaceWith('<img src="images/loaders/loader.gif" alt="" style="margin: 14px;">');
$.getJSON("auction.php?action=buy&player=" + player["tradeId"] +"&value="+ player["buyNowPrice"], function(result){
alert("request finished");
});
});
});

Categories

Resources