submit form HTML using ajax and get json response - json

I am not able to insert data through ajax, I want to insert it and get JSON response too.Actually at the end i want to create an API of this total code.
<?php
error_reporting(1);
mysql_connect("localhost","root","");
mysql_select_db("behindtherock");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form >
<label>Country</label><br />
<input type="text" id="country" />
<br />
<label>First name</label><br />
<input type="text" id="first_name" />
<br />
<label>Last Name</label><br />
<input type="text" id="last_name" />
<br />
<input type="submit" id="save" value="post" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#save").click(function(){
var country=$("#country").val();
var first_name=$("#first_name").val();
var last_name=$("#last_name").val();
var address_line_1=$("#address_line_1").val();
var address_line_2=$("#address_line_2").val();
var city=$("#city").val();
var state=$("#state").val();
var zip=$("#zip").val();
var user_phone=$("#user_phone").val();
var user_email=$("#user_email").val();
var u_stream=$("#u_stream").val();
var referring_member=$("#referring_member").val();
var promotion_code=$("#promotion_code").val();
$.ajax({
url:"add.php",
type:"post",
async:false,
data:{
"done":1,
"country":country,
"first_name":first_name,
"last_name":last_name,
"address_line_1":address_line_1,
"address_line_2":address_line_2,
"city":city,
"state":state,
"zip":zip,
"user_phone":user_phone,
"user_email":user_email,
"u_stream":u_stream,
"referring_member":referring_member,
"promotion_code":promotion_code,
};
success:function(data){
}
});
});
});
</script>
</body>
</html>
<?php
error_reporting(1);
include("db.php");
if(isser($_POST['done'])){
$country=mysql_escape_string($_POST['country']);
$first_name=mysql_escape_string($_POST['first_name']);
$last_name=mysql_escape_string($_POST['last_name']);
$address_line_1=mysql_escape_string($_POST['address_line_1']);
$address_line_2=(int)$_POST['address_line_2'];
$city=mysql_escape_string($_POST['city']);
$state=mysql_escape_string($_POST['state']);
$zip=mysql_escape_string($_POST['zip']);
$user_phone=mysql_escape_string($_POST['user_phone']);
$user_email=mysql_escape_string($_POST['user_email']);
$u_stream=mysql_escape_string($_POST['u_stream']);
$referring_member=mysql_escape_string($_POST['referring_member']);
$promotion_code=mysql_escape_string($_POST['promotion_code']);
mysql_query("INSERT INTO user_details(country,first_name,last_name,address_line_1,address_line_2,city,state,zip,user_phone,user_email,u_stream,referring_member,promotion_code)
VALUES ('('', '$country','$first_name','$last_name','$address_line_1','$address_line_2','$city','$state','$zip','$user_phone','$user_email','$u_stream','$referring_member','$promotion_code')')");
exit();
}
?>
I am not able to insert data through ajax, I want to insert it and get JSON response too.Actually at the end i want to create an API of this total code.

Related

html automatic input detect and redirect

i want to enter names after the display with loading gif comes prompt me to enter my age.
i want after entering my age i get redirected to url. any url like stackoverflow.com
i have updated my question to above. but still same problem
<!DOCTYPE html>
<html lang="en">
<head>
<title>title</title>
<meta charset="utf-8">
</head>
<body>
<form method="post">
<p>
<input type="text" name="myname" />
</p
<label>
<input type="submit" name="submit" value="Enter your names" />
</label>
</form>
<div style="display:none;">
<p>enter your age to enter this site</p>
<p>mr.myname</p>
<div id="spinner">
<img src="js/ajax-loader.gif" alt="Loading" /> waiting for your age to enter site
</div>
<input type="text" name="age" />
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$('form').submit(function() {
$('#spinner').show(); //activate spinner on submit
$.ajax({
type: 'POST',
url: 'https://localhost',
dataType: 'json',
success: function(json) {
// $('#spinner').hide(); //not necessary because of redirect
window.location.href = "http://www.wdr.de";
},
error: function(){
$('#spinner').hide();
}
return false;
});
</script>
</body>
</html>
you can do something like this:
I have updated your code. Sure, you have to set style for your spinner.
Here is also a fiddle: https://jsfiddle.net/mattopen/pkb4xs7w/41/
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<title>title</title>
</head>
<body>
<form method="post">
<p>
<input type="text" name="myname" />
</p>
<label>
<input type="submit" name="submit" value="Enter your names" />
</label>
</form>
<div style="display:none;">
<p>enter your age to enter this site</p>
<p>mr.myname</p>
<div id="spinner">
<img src="js/ajax-loader.gif" alt="Loading" /> waiting for your age to enter site
</div>
<input type="text" name="age" />
</div>
<script>
$('form').submit(function() {
$('#spinner').show(); //activate spinner
$.ajax({
type: 'POST',
url: '/your_url/submit_username',
dataType: 'json',
success: function (json) {
alert('redirect');
// $('#spinner').hide(); //not necessary because of redirect
window.location.href = "https://jsfiddle.net/";
},
error: function () {
alert('something went wrong');
$('#spinner').hide();
window.location.href = "https://jsfiddle.net/";
}
});
})
</script>
</body>
</html>
edit:
it was not clear to me if op will use ajax call and submit data to server or only want`s to check a date input and then redirect to url.
If op will make use of ajax, then '/your_url/submit_username' has to be a valid url within your application.
This approach is without the use of an ajax call.
$('input[name="submit"]').click(function(event) {
event.preventDefault();
$('#spinner').show(); //activate spinner
// here goes your code for check input
// function check(){....; return 'ok'};
// now redirect if check was ok like if(check === 'ok')
window.location.href = "https://jsfiddle.net/";
})

How to save user inputs of html form to a single csv file

I am having a html form when the user submit the form it should save the file as csv and store and when the user again types/submits the form it should get updated in the same csv file.I have used the below code in which it creates a new csv file each time can anyone tell me how to do it.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Writing Data to CSV</title>
<script type="text/javascript">
function addToCSVFile() {
var csvData = new Array(); // To collect the names
// Collecting the names
csvData[0] = document.getElementById('firstName').value;
csvData[1] = document.getElementById('middleName').value;
csvData[2] = document.getElementById('lastName').value;
window.open('data:text/csv;charset=utf-8,' + csvData.join(','));
clearData();
alert("Data Added Successfully");
}
function clearData() {
document.getElementById('firstName').value = "";
document.getElementById('middleName').value = "";
document.getElementById('lastName').value = "";
}
</script>
</head>
<body>
<p>
First Name: <input type="text" id="firstName" />
<br />
Middle Name: <input type="text" id="middleName" />
<br />
Last Name: <input type="text" id="lastName" />
<br />
<input type="button" id="addButton" value="Add to CSV File" onClick="javascript: addToCSVFile()" />
</p>
</body>

How to send data from Html File To another one Using angular?

i try sample project which take some data in form in html file .. then pass it to spring service .. which return object successfully .. now i want to pass this object to another Html fie to Display
Form's Html File :
<!DOCTYPE html>
<html ng-app="phase2">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<head>
<title>Sign UP Page</title>
<script src="RigesterationController.js"></script>
</head>
<body >
<center>
<p>Enter Your User Name : <input type="text" , name="UserName" id ="UName" required /> </p>
<p>Enter Your Email : <input type="text" , name="Email" id ="email" required /> </p>
<p>Enter Your Password : <input type="password" , name="pass" id ="Pass" required/> </p>
<p>Choose Gender : <br> Male<input type="radio" name="gender" value="m" id="Gender" /> Female<input type="radio" name="gender" value="f" id="Gender"/> </p>
<p>Choose User Type :<br> Student<input type="radio" name="UserType" value="s" id="Utype" /> Teacher<input type="radio" name="UserType" value="t" id="Utype"/> </p>
<div ng-controller="SignUP">
<input type="button" name="signup" value="SignUP" ng-click="save()" />
</div>
</center>
</body>
</html>
RigesterationController.js file :
angular.module("phase2" , [])
.controller("SignUP" , function($scope , $http )
{
var dat ;
$scope.save = function() {
var email= document.getElementById("email").value;
var UName=document.getElementById("UName").value;
var Pass=document.getElementById("Pass").value;
var gender=document.getElementById("Gender").value;
var UserType=document.getElementById("Utype").value;
var Info ;
$http.get('http://localhost:8090/SignUp/'+email+'/'+UName+'/'+Pass+'/'+gender+'/'+UserType)
.then(function(response)
{
Info = response.data;
dat=Info ;
alert(dat.name) ;
window.location.href="http://localhost:8060/TheAngular_Project/StudentPage.html";
});
}
});
second Html file :
<!DOCTYPE html>
<html ng-app="phase2">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="RigesterationController.js"></script>
<head>
<title>Student Page</title>
</head>
<body>
<div ng-controller="SignUP">
<p><span class="name">Welcome {{dat.name}}</p>
</div>
</body>
</html>
now nothing appeared in dat.name in second html file ..
although .. in regestrationController.js ..I test dat.name in an allert and it appeared successfuly ..
thanks in advance
i found the answer by Wawy in this post..
[AngularJS - Passing data between pages
You need to create a service to be able to share data between controllers.
app.factory('myService', function() {
var savedData = {}
function set(data) {
savedData = data;
}
function get() {
return savedData;
}
return {
set: set,
get: get
}
});
In your controller A:
myService.set(yourSharedData);
In your controller B:
$scope.desiredLocation = myService.get();
Remember to inject myService in the controllers by passing it as a parameter.

DNN - Minimize Junk in Skin

In DotNetNuke(DNN) am trying to create a page template that will be used to create HTML for emails. Because the HTML is going to be used in emails, it needs to be strictly controlled. The user will create the page in DNN, then copy the HTML for the page and use it in MailChimp. I don't want anything extra in the HTML, it should be as minimized as possible.
The template will have placeholders for header body and footer. The user can put different modules into these areas depending on what they want to do with the email.
To accomplish this I created a Skin. It appears to me to be about as simple as it gets.
Here is the skin file:
<%# Control Language="C#" AutoEventWireup="false" Explicit="True" Inherits="DotNetNuke.UI.Skins.Skin" %>
<div id="HeaderPane" runat="server"></div>
<div id="ContentPane" runat="server"></div>
<div id="FooterPane" runat="server"></div>
Although the skin looks as simple as it gets, the output is nowhere near the level of simplicity that I require. To test, I have created a new page and selected this skin. Before adding anything to the page, I load it into a web browser. The page of course appears blank, but when I view the HTML I see the following source:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html lang="en-US">
<head id="Head">
<!--**********************************************************************************-->
<!-- DotNetNuke - http://www.dotnetnuke.com -->
<!-- Copyright (c) 2002-2013 -->
<!-- by DotNetNuke Corporation -->
<!--**********************************************************************************-->
<title>
PAGE TITLE HERE
</title><meta content="text/html; charset=UTF-8" http-equiv="Content-Type" /><meta content="text/javascript" http-equiv="Content-Script-Type" /><meta content="text/css" http-equiv="Content-Style-Type" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta id="MetaKeywords" name="KEYWORDS" content=",DotNetNuke,DNN" /><meta id="MetaCopyright" name="COPYRIGHT" content="Copyright © 2014 XXXX. All rights reserved.<br/>MY ADDRESS HERE" /><meta id="MetaGenerator" name="GENERATOR" content="DotNetNuke " /><meta id="MetaAuthor" name="AUTHOR" content="XXXXXXX" /><meta name="RESOURCE-TYPE" content="DOCUMENT" /><meta name="DISTRIBUTION" content="GLOBAL" /><meta id="MetaRobots" name="ROBOTS" content="INDEX, FOLLOW" /><meta name="REVISIT-AFTER" content="1 DAYS" /><meta name="RATING" content="GENERAL" /><meta http-equiv="PAGE-ENTER" content="RevealTrans(Duration=0,Transition=1)" /><style id="StylePlaceholder" type="text/css"></style><link href="/portals/_default/default.css?cdv=80" type="text/css" rel="stylesheet"/><link href="/portals/0/portal.css?cdv=80" type="text/css" rel="stylesheet"/><script src="/resources/shared/scripts/jquery/jquery.min.js?cdv=80" type="text/javascript"></script><script src="/resources/shared/scripts/jquery/jquery-migrate.min.js?cdv=80" type="text/javascript"></script><script src="/resources/shared/scripts/jquery/jquery-ui.min.js?cdv=80" type="text/javascript"></script>
<link rel='SHORTCUT ICON' href='/Portals/0/favicon.ico' type='image/x-icon' />
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'ACCOUNT_NUMBER']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body id="Body">
<form method="post" action="/PATH/TO/CURRENT_FILE/Demo2.aspx" id="Form" enctype="multipart/form-data">
<div class="aspNetHidden">
<input type="hidden" name="StylesheetManager_TSSM" id="StylesheetManager_TSSM" value="" />
<input type="hidden" name="ScriptManager_TSM" id="ScriptManager_TSM" value="" />
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="LONG VIEWSTATE ENCODED VALUE IS HERE" />
</div>
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['Form'];
if (!theForm) {
theForm = document.Form;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
<script src="/WebResource.axd?d=ENCODED_STRING&t=635195493660000000" type="text/javascript"></script>
<script src="/Telerik.Web.UI.WebResource.axd?LONG_QS_VARIABLE=XXXXXXXXX" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.');
//]]>
</script>
<script src="/js/dnn.js" type="text/javascript"></script>
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATEENCRYPTED" id="__VIEWSTATEENCRYPTED" value="" />
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="LONG ENCODED VALUE" />
</div><script type="text/javascript">
//<![CDATA[
Sys.WebForms.PageRequestManager._initialize('ScriptManager', 'Form', [], [], [], 90, '');
//]]>
</script>
<script src="/js/debug/dnn.modalpopup.js?cdv=80" type="text/javascript"></script><script src="/js/debug/dnn.servicesframework.js?cdv=80" type="text/javascript"></script><script src="/js/debug/dnncore.js?cdv=80" type="text/javascript"></script>
<div id="dnn_HeaderPane" class="DNNEmptyPane"></div>
<div id="dnn_ContentPane" class="DNNEmptyPane"></div>
<div id="dnn_FooterPane" class="DNNEmptyPane"></div>
<input name="ScrollTop" type="hidden" id="ScrollTop" />
<input name="__dnnVariable" type="hidden" id="__dnnVariable" autocomplete="off" value="`{`__scdoff`:`1`,`sf_siteRoot`:`/`,`sf_tabId`:`423`}" />
<script type="text/javascript" src="/Resources/Shared/scripts/initWidgets.js" ></script></form>
</body>
</html>
I am not using forms, I don't need any jQuery or Javascript functionality, all of the styles are going to be inline (or included in a <style> tag and won't be external references). I just want the HTML structure without all of the other stuff surrounding it.
Is this possible in DNN?
As DNN is a WebForms based application, some things like the ViewState and the WebResource.axd links, etc. are going to be next to impossible to get rid of.
For other items, review what modules are being loaded on the page. Ensure that you don't have modules that are marked to "include on every page".

trying to add to database using AJAX

I tried following a couple of examples on the web about adding to a mysql database using ajax but it isn't posting to the database but is executing the header at the bottom of the page.
This is the html document where you input the information
edit: Thank you for all your answers, This has now been fixed.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="message.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<title>Add a comment!</title>
</head>
<body id="bodymain">
Home
<br>
<div id="main">
<?=$blog_post_history?>
</div>
<br>
<br>
<form method="post" action="addreply.php">
<input type="hidden" name="blogid" value="<?php echo $_GET['id'] ?>">
Author: <input type="text" name="poster" size="60">
<br>
Email: <input type="text" name="email" size"60">
<br>
Comment: <textarea name='content' rows=10 cols=50 id='content'></textarea>
<input type="submit" value="send" />
</form>
</body>
</html>
This is the javascript
$(function(){
//Whenever the form submites, call this
$("form").submit(function()) {
//submit using ajax
submitMessage();
//prevent from submitting
return false;
}
};
var submitMessage = function (){
if($("#content").val().length > 0 && $("author").val.length > 0)
{
//start ajax request
$.post(
"addreply.php"
{
content: $("#message").val(),
author: $("#author").val(),
email: $("email").val(),
blogid: $("blogid").val()
},
);
}
};
And this is the php page adding to database
<?php
include("connect.php");
$add_comment_query = $db->prepare("
INSERT INTO `comments`
(`email`, `author`, `content`, `postid`)
VALUES
(:email, :author, :content, :postid)
");
$add_message_query->execute(array(
':email' => $_POST['email'],
':author'=> $_POST['author'],
':content' => $_POST['content'],
':postid' => $_POST['blogid']
));
// This calls for a '301' response code instead of '200', with a 'Location'
// sent to tell the browser where to redirect to.
header("Location: home.php");
?>
Can anyone see where I am going wrong. I am completely stumped.
$("author") and $("#author") should be $("#poster").
Also, all your <input> elements are midding id attributes. So:
<input type="text" name="poster" size="60">
should be:
<input type="text" name="poster" id="poster" size="60">
and similarly for all the other inputs.
Your selectors aren't correct.
Did you try debugging the javascript in your browser to see what the value of for instance $("#author") is?
The hash is the ID selector so you need the HTML for that element to have an id property:
<input type="text" name="poster" id="poster" size="60">
All of your other fields should be modified similarly so that each element you are going to use has an ID and each jquery selector is in the format "#" Currently author, email, and blogid have wrong selectors.
Make the HTML:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="message.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<title>Add a comment!</title>
</head>
<body id="bodymain">
Home
<br>
<div id="main">
<?=$blog_post_history?>
</div>
<br>
<br>
<form method="post" action="addreply.php">
<input type="hidden" id="blogid" name="blogid" value="<?php echo $_GET['id'] ?>">
Author: <input type="text" name="poster" id="poster" size="60">
<br>
Email: <input type="text" name="email" id="email" size"60">
<br>
Comment: <textarea name='content' rows=10 cols=50 id='content'></textarea>
<input type="submit" value="send" />
</form>
</body>
</html>
and your jquery:
var submitMessage = function (){
if($("#content").val().length > 0 && $("#poster").val.length > 0)
{
//start ajax request
$.post(
"addreply.php"
{
content: $("#message").val(),
author: $("#poster").val(),
email: $("#email").val(),
blogid: $("#blogid").val()
},
);
}
};