jquery:
$("document").ready(function(){
alert('This is working');
$(".add_new").click(function() {
$(".table").hide();
$("#frm").show();
});
$(".insert_form").submit(function(){
var sending_data = {
"action": "insert"
};
sending_data = $(this).serialize() + "&" + $.param(sending_data);
$.ajax({
type: "POST",
url: "test.php", //Relative or absolute path to response.php file
data: sending_data,
success: function(return_data) {
alert(return_data); //This is not working.
}
});
});
});
test.php
<?php
echo $_POST['action'];
?>
HTML:
<form method="post" id="frm" style="display:none;" class="insert_form">
<input type="text" value="" required="required" placeholder="Enter your Name" name="user_name" />
<input type="submit" value="Submit" />
<input type="reset" value="clear" />
</form>
After submitting i have to display message. I am just testing using alert() but the alert box is appearing.Please Help.
Related
I'm new to web development and stucked at sending data to server. I have registration form and i want to send this data to server. I can send data from form tag using action and method attribute but it will return response in next page. So i read somewhere i have to use ajax to send data. I tried but i cannot send and capture data using script.
This is my reponse
{"success":true}
Html code
<div class="form">
<div class="formdetail">
<h3>Individual Registration</h3>
<label for="fname"> Name</label><br>
<input type="text" size="40" id="name" name="name" placeholder="Enter your name.." required><br><br>
<label for="phonenumber">Mobile Number</label>
<br/>
<input id="mobileno" size="40" name="mobileno" type="tel" size="20" maxlength="13" placeholder="Enter your mobile number..." type="number" required><br><br>
<label for="email">Email-Id</label><br>
<input type="text" size="40" id="email" name="email" placeholder="Enter your email-id..." required><br><br>
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt" name="dob" onclick="mydate();" hidden />
<input type="button" Value="Date of Birth" onclick="mydate();" />
<script>
function mydate()
{
//alert("");
document.getElementById("dt").hidden=false;
document.getElementById("dob").hidden=true;
}
function mydate1()
{
d=new Date(document.getElementById("dt").value);
dt=d.getDate();
mn=d.getMonth();
mn++;
yy=d.getFullYear();
document.getElementById("dob").value=dt+"/"+mn+"/"+yy
document.getElementById("dob").hidden=false;
document.getElementById("dt").hidden=true;
}
</script>
<br><br>
<label for="address">Address</label><br>
<input type="text" id="address" size="40" name="address" placeholder="Enter your address..." required><br><br>
<label for="country">Country</label><br>
<input type="text" id="country" size="40" name="country" placeholder="Enter your country name....." required><br><br>
<label for="State">State</label><br>
<input type="text" id="state" size="40" name="state" placeholder="Enter your state name....." required><br><br>
<label for="city">City</label><br>
<input type="text" id="city" size="40" name="city" placeholder="Enter your city name....." required><br><br>
<input type="hidden" name="category" value="Individual">
<input type="submit" value="Submit" id="someInput" onclick="ajax_post()"><br>
<p class="small">Institute Registraion</p>
</div>
</div>
</form>
<script type="text/javascript">
function ajax_post(){
var hr = new XMLHttpRequest();
var url = "https://smilestechno.000webhostapp.com/Register.php";
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function(){
if (hr.readyState == 4 && hr.status == 200) {
var resp = console.log(response);
if (resp == "true") {
}
}
hr.send("name="+ name + "&mobileno=" + mobileno + "&email=" + email + "&dob=" + dob + "&address=" + address + "&city=" + city + "&state=" + state + "&country=" + country );
document.getElementById("status").innerhtml = "processing";
}
you can not send variable in this format.
var vars = name+mobileno+email+dob+address+city+state+country;
Params must have a format like:
hr.send("fname=Henry&lname=Ford");
Code you need:
hr.send("name=" + name + "&monbileno=" + mobileno + ... );
You can use jquery to use ajax in a simple way.
Reference:
xmlhttprequest https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp
jquery ajax https://www.w3schools.com/jquery/jquery_ref_ajax.asp
Use jquery, it makes it easier. This is how it should be using just the fname and email as an example with jquery ajax:
<form name="myForm" id="myForm" action="myActionUrl" method="POST">
<input type="text" name="fname" id="fname">
<input type="email" name="email" id="email">
<input type="submit" value="Submit">
</form>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
$("#myForm").on("submit", function(event){
event.preventDefault(); //this prevents the form to use default submit
$.ajax({
method: "POST",
url: $(this).attr("action"), //this will use the form's action attribute
data: {fname: $("#fname").val(), email: $("#email").val()},
success: function(responseData){
//do something here with responseData
}
});
});
</script>
Please replace the "myActionUrl" part with the url/file that processes your data.
The file can be some basic php file which stores the data into some database and returns or echoes something back so that you can use it within the "responseData" on the ajax success function.
Hope this helps!
Please call function like this
onclick="ajax_post()"
not
onclick="ajax_post"
You used getElementById but selected a name attribute
have to use
getElementById('fname').value;
not
getElementById('name').value;
hey i would recommend using jquery to accomplish this task.
this isthe client script
script type="text/javascript" src='jquery.js'></script>
<!-- download the lates version -->
<script type="text/javascript">
ajax_post(){
var url = "https://smilestechno.000webhostapp.com/Register.php";
var name = $("#name").val();
var mobileno = $("#mobileno").val();
var email = $("#email").val();
var dob = $("#dob").val();
var address = $("#address").val();
var city = $("#city").val();
var state = $("#state").val();
var country = $("#country").val();
var tmp = null;
$.ajax({
'async': false,
'type': "POST",
'global': false,
'dataType': 'json',
'url':url,
'data':{name:name,mobileno:mobileno,email:email,dob:dob,address:address,city:city,state:state,country},
'success': function (data) {
tmp = data;
}
});
return tmp; // you can access server response from this tmp variable
}
Server side
<?php
//get items as post inputs
print_r($_POST[]);
echo $_POST['name'];
?>
When I press on my edit button I call a webservice function and it return a list of question parameter and it's working the function return the right value for each edit button but after returning the value I have a post back and all my html input that I fill in this function they are clear again, why?
JavaScript and jQuery:
$(document).ready(function () {
$('.divPreview').on("click", ".editbtn", function () {
var idQ = 0;
idQ = $(this).val();
var Did = { 'Qid': idQ };
alert(idQ);
$.ajax({
type: "POST",
async: false,
url: "/WebService.asmx/GetQuestion",
data: JSON.stringify(Did),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: function (r) {
alert(r.responseText);
},
failure: function (r) {
alert(r.responseText);
}
});
function OnSuccess(response) {
var question = response.d;
$(".dropdown_fields").html('<select id="dplQuestionType" class="dropdown_selector"><option value="radio">Radio Button</option> <option value="checkbox">Check Box</option></select>');
$(".input_field").html('<p>Q1:<input id="txtQuestion" type="text" /></p> <p> Answer Choices:</p><div><input id="hdnC1" type="hidden" value="0" /><input id="txtC1"type="text" name="mytext[]" /><input id="cbActive1" type="checkbox" /></div><div><input id="hdnC2" type="hidden" value="0" /><input id="txtC2" type="text" name="mytext[]" /><input id="cbActive2" type="checkbox" /></div>');
$(".OtherOption").html('<input id="btnAddField" class="btnAddField" type="button" value="Add Choices"/><br>Page Number<input id="txtPageNumber" type="text" /> Question Order: <input id="txtOrder" type="text" /><br/><p><input id="cbCommonField" type="checkbox" />Add a Common Field</p><br/>Is Required<input id="cbIsRequire" type="checkbox" />Is Active<input id="cbIsActive" type="checkbox" /><br/>Hint:<textarea id="txtaHint" rows="2" cols="20"></textarea> ');
$(".ButtonField").html('<p><input id="btnSave" type="button" value="Save" onclick="GetQuestionInfo()" /> <input id="btnCancel" class="btnCancel" type="button" value="Cancel" /></p>');
document.getElementById("btnAddQuest").style.visibility = 'hidden';
document.getElementById("txtOrder").value = question.qst_Order;
document.getElementById("txtPageNumber").value = question.qst_PageNumber;
document.getElementById("cbIsRequire").value = question.qst_Order;
document.getElementById("cbIsActive").value = question.qst_Order;
document.getElementById("txtaHint").value = question.qst_Hint;
document.getElementById("dplQuestionType").value = question.qst_Type;
document.getElementById("hdnQuestionID").value = question.qst_Id;
alert(question.qst_txt);
}
});
});
You aren't actually doing a ajax request you are simply doing a normal post request from a form, to do a ajax request prevent the default submit using e.preventDefault();
$('.divPreview').on("click", ".editbtn", function (e) {
e.preventDefault();
In my abc.html I have the following code which will covert the form data(hard coded for now) to JSON format:
<body>
<form enctype='application/json' method="POST" name="myForm">
<p><label>Company:</label>
<input name='Company' value='TESTCOMPANY'> </p>
<p><label>User Id:</label>
<input name='User' value='TESTUSER'></p>
<p><label>Division:</label>
<input type="text" name='parameterMap[p1]' value='12345' ></p>
<p><label>From:</label>
<input type="text" name='parameterMap[p2]' value='20-MAR-2016'></p>
<p><label>To:</label>
<input type="text" name='parameterMap[p3]' value='22-MAR-2016'></p>
<input value="Submit" type="submit" onclick="submitform()">
</form>
</body>
From the code above I get *
{"Company":"TESTCOMPANY","User":"TESTUSER","parameterMap":{"p1":"12345","p2":"20-MAR-2016","p3":"22-MAR-2016"}}*
Now I need to assign the Json String formed by this data to variable 'FormData' so that FormData is like:
FormData = '{"Company":"TESTCOMPANY","User":"TESTUSER","parameterMap":{"p1":"12345","p2":"20-MAR-2016","p3":"22-MAR-2016"}}'
How do I do this assignment of data ?
The further code in abc.html will use this variable FormData in the following way:
function sendAjax() {
$.ajax({
url : "myurl",
type : 'POST',
dataType : 'json',
data : FormData,
contentType : 'application/json',
mimeType : 'application/json',
success : function(data) {
alert(data.uuid);
},
error : function(data, status, er) {
alert("error: " + data + " status: " + status + " er:" + er);
}
});
}
If you are not handling this in backend you can retrieve the data in Javascript in a variable then just appned it as JSON to your data using JSON.stringify().
This is a working snippet:
function submitform() {
var FormData = {
Company: myForm.Company.value,
User: myForm.User.value,
parameterMap: {
p1: myForm.p1.value,
p2: myForm.p2.value,
p3: myForm.p3.value
}
};
console.log(FormData);
$.ajax({
url: "myurl",
type: 'POST',
dataType: 'json',
data: JSON.stringify(FormData),
contentType: 'application/json',
mimeType: 'application/json',
success: function(data) {
alert(data.uuid);
},
error: function(data, status, er) {
alert("error: " + data + " status: " + status + " er:" + er);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form enctype='application/json' method="POST" name="myForm">
<p>
<label>Company:</label>
<input name='Company' value='TESTCOMPANY'>
</p>
<p>
<label>User Id:</label>
<input name='User' value='TESTUSER'>
</p>
<p>
<label>Division:</label>
<input type="text" name='p1' value='12345'>
</p>
<p>
<label>From:</label>
<input type="text" name='p2' value='20-MAR-2016'>
</p>
<p>
<label>To:</label>
<input type="text" name='p3' value='22-MAR-2016'>
</p>
<input value="Submit" type="submit" onclick="submitform()">
</form>
Notes:
Use Javascript naming conventions, for example FormData will better be formData.
Using the provided HTML structure you could get the data into the format using:
function submitform(){
var form = document.querySelector('form');
var result = {};
var input = form.getElementsByTagName('input');
for(var i = 0; i < input.length; i ++) {
var row = input[i];
var rowName = ((row.name || '').match(/(\w+)(\[(\w+)\])?/) || []);
var rowIndex = rowName[3];
rowName = rowName[1];
if(rowName) {
var typeOfRowIndex = typeof rowIndex;
var rowValue = row.value;
if(typeof result[rowName] === 'undefined') {
var rowToAdd = {};
rowToAdd[rowIndex] = rowValue;
result[rowName] = typeOfRowIndex === 'undefined' ? rowValue : rowToAdd;
} else if(typeOfRowIndex !== 'undefined') {
result[rowName][rowIndex] = rowValue;
}
}
}
document.getElementById('output').innerHTML = JSON.stringify(result)
console.log(result);
return false;
}
<body>
<form enctype='application/json' method="POST" name="myForm">
<p>
<label>Company:</label>
<input name='Company' value='TESTCOMPANY'>
</p>
<p>
<label>User Id:</label>
<input name='User' value='TESTUSER'>
</p>
<p>
<label>Division:</label>
<input type="text" name='parameterMap[p1]' value='12345'>
</p>
<p>
<label>From:</label>
<input type="text" name='parameterMap[p2]' value='20-MAR-2016'>
</p>
<p>
<label>To:</label>
<input type="text" name='parameterMap[p3]' value='22-MAR-2016'>
</p>
<input value="Submit" type="submit" onclick="return submitform()">
</form>
<p>JSON Output (after clicking submit button):</p>
<div id="output"></div>
<p>Can also check console to see JSON object (after clicking submit button)</p>
</body>
var FormData = $('form[name=myForm]').serializeArray();
FormData = JSON.stringify(FormData);
I don't like jQuery, but:
var $inputs = $('form[name="myForm"]').find('input');
var res = {};
Array.prototype.forEach.call($inputs, function($item, index) {
res[ $item.getAttribute('name') ] = $item.value;
});
var FormData = JSON.stringify(res);
alert(FormData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form enctype='application/json' method="POST" name="myForm">
<p><label>Company:</label>
<input name='Company' value='TESTCOMPANY'> </p>
<p><label>User Id:</label>
<input name='User' value='TESTUSER'></p>
<p><label>Division:</label>
<input type="text" name='parameterMap[p1]' value='12345' ></p>
<p><label>From:</label>
<input type="text" name='parameterMap[p2]' value='20-MAR-2016'></p>
<p><label>To:</label>
<input type="text" name='parameterMap[p3]' value='22-MAR-2016'></p>
<input value="Submit" type="submit" onclick="submitform()">
</form>
</body>
i have a form that i submit to a database using ajax, there a div on the page which has a database binding which counts the total number of records submit on page refresh. now what i want to do is onsubmit of the form, i should add 1 to the binding in the div which counts the total number of records submitted
<div id="count_div"></div>
<form id="form2" name="form2" method="POST" action="<%=MM_editAction%>">
<input name="comment" type="text" id="comment" size="50" />
<input name="imageField3" type="image" id="imageField3" src="imgs/buttons/comment.png" align="bottom" />
<input name="wardrobe" type="hidden" id="wardrobe" value="1" />
<input name="comme" type="hidden" id="comme" value="2" />
<input name="comfn" type="hidden" id="comfn" value="3" />
<input name="photo_id" type="hidden" id="photo_id" value="4" />
<input name="ctype" type="hidden" id="ctype" value="picture" />
<input name="resp_email" type="hidden" id="resp_email" value="4" />
<input type="hidden" name="MM_insert" value="form2" />
</form>
AJAX
<script>
$(document).ready(function(){
$("#form2").on('submit',function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "int_p_cmt.asp",
data: data
}).success(function() {
$("#msg_div").append("<div class='messages' style='border:1px purple solid; padding:2px; margin:5px;'>Your comment has been saved </div>");
setTimeout(function() {
$(".messages").fadeOut(function(){
$(".messages").remove();
});
}, 1000);
$("input[type=text]").val("");
});
});
});
</script>
if what I understood is correct: you want to increment th value of the "count_div" div then try this:
$(document).ready(function(){
$("#form2").on('submit',function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "int_p_cmt.asp",
data: data
}).success(function() {
$("#msg_div").append("<div class='messages' style='border:1px purple solid; padding:2px; margin:5px;'>Your comment has been saved </div>");
setTimeout(function() {
$(".messages").fadeOut(function(){
$(".messages").remove();
});
}, 1000);
$("#count_div").html(parseFloat($("#count_div").html())+1);
$("input[type=text]").val("");
});
});
});
UPDATED:
<script>
$(document).ready(function(){
$("#form2").on('submit',function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "int_p_cmt.asp",
data: data
}).success(function() {
window.counter=parseInt($('#count_div').html());
window.counter++;
$('#count_div').html(window.counter);
$("#msg_div").append("<div class='messages' style='border:1px purple solid; padding:2px; margin:5px;'>Your comment has been saved </div>");
setTimeout(function() {
$(".messages").fadeOut(function(){
$(".messages").remove();
});
}, 1000);
$("input[type=text]").val("");
});
});
});
</script>
I can't execute this jquery function properly. When I click on submit's form, only shows the two first alerts and then the page reloads. So I click again on the form's submit with the page reloaded and then shows the rest of the alerts (beginning by the third one) and then the function works fine.
In conclusion: I need to click on the form's submit two times instead of one to execute the function.
Any idea? Thank you.
JS Code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
alert("enters script");
$(function () {
alert("enters jquery function");
$(".submit").click(function () {
alert("enters click submit function");
var name = $("#name").val();
var date = $("#date").val();
var dataString = 'name=' + name + '&date=' + date;
alert("saved variables");
if (name == '' || date == '') {
alert("enters if");
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
} else {
alert("enters else");
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function () {
alert("enters success");
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
refresh();
}
});
}
return false;
});
});
</script>
HTML Code:
<form method="post" name="form">
<ul>
<li>
Name <input id="name" name="name" type="text" />
</li>
<li>
Date <input id="date" name="date" type="date" />
</li>
</ul>
<div >
<input type="submit" value="Submit" class="submit"/>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Registration Successfully</span>
</div>
</form>
use the event.preventdefault to stop the submission of the page
http://api.jquery.com/event.preventdefault/
Your problem is using submit buttons, they have some default behaviors other than what you add as a event to it.
replaced this:
<input type="submit" value="Submit" class="submit" />
with:
<input type="button" value="Submit" class="submit" />
this you working DEMO
other than changing the submit button to a regular button, you can fix your code by disabling that default behaviors, adding onsubmit to your form node:
<form method="post" name="form" onsubmit="return false;">
<!--your stuff-->
</form>
Try this:
<script type="text/javascript">
$( document ).ready(function() {
$(".submit").click(function(){
alert("entra en la funcion del clic del submit");
var nombre = $("#nombre").val();
var fecha = $("#fecha").val();
var dataString = 'nombre='+ nombre + '&fecha=' + fecha;
alert("variables guardadas");
if(nombre=='' || fecha=='')
{
alert("entra en el if");
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
alert("entra en el else");
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function()
{
alert("entra en el success");
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
refresca();
}
});
}
return false;
});
});
First of all, thank you to everybody for your help.
Finally the main problem comes from other part of the code. I was using pjax (https://github.com/thybag/PJAX-Standalone) to replace the form with other html document (in this case page1.html) after doing the mysql insert through "join.php". And I'm not calling the jquery function properly.
Explanation: You begin in page1.html, then click on "Go To Page 2" (This replace the div "content" with the body of page2.html). Then complete the form and submit it. When you click on submit, activates the jquery function (join.php mysql insert inside) and finally replace again the div "content".
Solution (this works):
page1.html
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" src="pjax-standalone.js"></script>
<script type="text/javascript">
pjax.connect({
'container': 'content',
'beforeSend': function(){console.log("before send");},
'complete': function(){console.log("done!");
if($("#button_pg_2").length)
{
$( document ).ready(function()
{
$(".submit").click(function()
{
var nombre = $("#name").val();
var fecha = $("#date").val();
var dataString = 'name='+ name + '&date=' + date;
if(name=='' || date=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax(
{
type: "POST",
url: "join.php",
data: dataString,
success: function()
{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
replace();
}
});
}
return false;
});
});
}
}
});
</script>
<script type="text/javascript">
function replace()
{
pjax.invoke('page1.html', 'content');
}
</script>
</head>
<body>
<div id="header">
This div never changes
</div>
<div id="content">
Go To Page 2
</div>
</body>
</html>
page2.html
<html>
<body>
<form method="post" name="form">
<ul>
<li>
Name <input id="name" name="name" type="text" />
</li>
<li>
Date <input id="date" name="date" type="date" />
</li>
</ul>
<div >
<input type="button" id="button_pg_2" value="submit" class="submit"/>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Registration Successfully</span>
</div>
</form>
</body>
</html>