XML request from ajax form - javascript

Hello everyone I am newbie in java-script so i hope you can help me with my issue. So I have the form, it look something like this:
<form method="post">
Field1: <input type="text" name="field1"><br>
Field2: <input type="text" name="field2"><br>
<input type="submit" value="Submit">
</form>
I need to take data from the form and make xml request, the xml request should look like this
<root>
<header section>
<section>data</section>
</header section>
<data section>
<field1>data</field2>
<field2>data</field2>
</data section>
</root>
After that i have to display xml response on the page.
I made xml request
<script>
$('.button').click( function() {
$(".results").append("<ul></ul>");
$.ajax({
type: "GET",
dataType: 'xml',
url: 'response.xml',
success: function(xml) {
$(xml).find('root').each(function(){
var sField1 = $(this).find('field1').text();
var sField2 = $(this).find('field2').text();
$("<li></li>").html(sTitle + ", " + sPublisher).appendTo(".results ul");
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
});
</script>
But I don't know how to take data from the form and make request. Can you help me with it? Thanks a lot.

// You can use jQuery to build XML document:
function buildXmlFromForm(form) {
var xml = $('<XMLDocument />');
xml.append (
$('<header-section />').append(
$('<section />').text('data')
)
).append (
$('<data-section />').append(
$('<field1 />').text(form.find("input[name='field1']").val())
).append(
$('<field2 />').text(form.find("input[name='field2']").val())
)
);
return xml.html();
}
// you should use POST or PUT method (not GET) to post xml-data to server side
$( "#form1" ).submit(function(event) {
event.preventDefault();
$("#results").append("<ul></ul>");
var xmlString = buildXmlFromForm($(this));
$("#xmlSrc").val(xmlString);
$.ajax({
type: "POST",
dataType: 'xml',
url: 'response.xml',
data: xmlString,
success: function(respData) {
$("<li></li>").html("ok: "+respData).appendTo("#results ul");
console.log(respData);
},
error: function(errorData) {
$("<li></li>").html("error: "+errorData.statusText).appendTo("#results ul");
console.log(errorData);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="form1">
Field1: <input type="text" name="field1" value="***v1***"><br/>
Field2: <input type="text" name="field2" value="***v2***"><br/><br/>
<input type="submit" value="Submit">
</form>
<hr/>
<textarea id="xmlSrc" cols="70" rows="5"></textarea>
<div id="results"/>

Try this:
serialize will return formData of current form
You must have unique identifier for your form to be used as querySelector
$('#myForm').on('submit', function(e) {
e.preventDefault();
var formData = $(this).serialize();
$(".results").append("<ul></ul>");
$.ajax({
type: "GET",
dataType: 'xml',
url: 'response.xml',
data: formData,
success: function(xml) {
$(xml).find('root').each(function() {
var sField1 = $(this).find('field1').text();
var sField2 = $(this).find('field2').text();
$("<li></li>").html(sTitle + ", " + sPublisher).appendTo(".results ul");
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="myForm">
Field1:
<input type="text" name="field1">
<br>Field2:
<input type="text" name="field2">
<br>
<input type="submit" value="Submit">
</form>

Related

How do I detect submitted button with ajax and php?

I have a form on my front-end and when the submit button is clicked I want to send the details to my get-emp.php file without page reload.
The code looks like this:
index.html
<form class="form-emp-details hide" action="">
<div class="form-group">
<label for="">First name:</label>
<input type="text" class="form-control input-emp-firstname" name="input_emp_firstname">
</div>
<div class="form-group">
<label for="">Last name:</label>
<input type="text" class="form-control input-emp-lastname" name="input_emp_lastname">
</div>
<div class="form-group">
<label></label>
<button type="submit" class="btn btn-default btn-submit-1" name="submit_emp_details">Save</button>
</div>
</form>
custom.js
$(".form-emp-details").("submit", function(e) {
var input_first_name = $(".input-emp-firstname").val();
$.ajax({
type: "POST",
url: "get-emp.php",
data: {
input_emp_firstname:input_first_name,
},
success: function(data) {
console.log(data)
},
error: function(xhr,status,error) {
console.log(error);
}
});
});
get-emp.php
if(isset($_POST['submit_emp_details'])) {
$firstname = $_POST['input_emp_firstname'];
echo $firstname;
}
I want to display the submitted form data on get-emp.php file but it seems that I am not able to detect the submitted button and echo the form data on.
My goal is to capture all form data with a single request variable or identifier $_POST['submit_emp_details']
Any help is greatly appreciated. Thanks
$("#MyformId").submit(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(),
success: function(data)
{
// success..
}
});
});
You passing the POST data of firstname and lastname by:
input_emp_firstname
input_emp_lastname
so, you need to change the $_POST['submit_emp_details'] to $_POST['input_emp_firstname'] on file get-emp.php to
<?php
if(isset($_POST['input_emp_firstname'])) {
$firstname = $_POST['input_emp_firstname'];
echo $firstname;
}
Edit 2:
$.ajax({
type: "POST",
url: "get-emp.php",
cache: false,
data: {
submit_emp_details: {
input_emp_firstname:input_first_name,
input_emp_lastname:input_last_name
}
},
success: function(data) {
console.log(data)
},
error: function(xhr,status,error) {
console.log(error);
}
});

Can't ajax reload without page reloading

I want it to only "reload" into the #searchuserc. I have searched so much information but I can't solve the problem.
$(document).ready(function() {
$("#onlineusers").load("online.php");
$("#searchuserc").show();
setInterval(function() {
$("#onlineusers").load("online.php");
}, 5000);
$(".search").click(function() {
$("#onlineusers").hide();
e.preventDefault(); // Prevent Default Submission
$.ajax({
url: 'searchuser.php',
type: 'POST',
data: $(this).serialize(), // it will serialize the form data
dataType: 'html'
})
.done(function(data) {
$('#searchuserc').fadeOut('slow', function() {
$('#searchuserc').fadeIn('slow').html(data);
});
})
.fail(function() {
alert('Ajax Submit Failed ...');
});
});
});
this is my HTML file
<form method="POST">
<input type="text" id="searchuser" name="searchuser" placeholder="Sök efter en användare..." />
<input type="submit" class="search" name="searchbtn" value="Sök" />
</form>
<div id="searchuserc">
</div>
Instead of
$(".search").click(function() {
...
use
$(".search").closest("form").submit(function(e) {
...
Code inside the handler can stay the same.

How to validate data in an AJAX call

I am trying to call data from a PHP file where it takes the data entered and tells if it is validated or not. How do you do this in the javascript file using an AJAX call?
$("#PersonForm").submit(function()
{
$.ajax({
url: 'backend.php', type: 'post', data: { act:'validate'},
dataType: 'json',
function(result) {
if($validateData==1){
$('#success').html('validated');
}
else{
$('#errors').html('Not Correct');
}
}
//});
});
return false;
});
Here is the PHP file
<?php
if ($_REQUEST['act'] == 'validate')
{
$validateData = array();
if (preg_match("/^[A-Za-z]{3,20}$/",$_REQUEST['name'])) $validateData['name'] = 1;
else $validateData['name'] = 0;
if (preg_match("/^[0-9]{10}$/",$_REQUEST['phone'])) $validateData['phone'] = 1;
else $validateData['phone'] = 0;
if (preg_match("/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/",
$_REQUEST['postal'])) $validateData['postal'] = 1;
else $validateData['postal'] = 0;
if (preg_match("/^[0-9]{3} [A-Za-z]{3,10} Street$/",
$_REQUEST['address'])) $validateData['address'] = 1;
else $validateData['address'] = 0;
echo json_encode($validateData);
}
else echo "Should not happen";
?>
HTML file:
<html>
<body>
<h1>Form Validation</h1>
<form id="PersonForm">
Name: <input type="text" id="name" name="name"> <br>
Postal Code: <input type="text" id="postal" name="postal"> <br>
Phone Number: <input type="text" id="phone" name="phone"> <br>
Address: <input type="text" id="address" name="address"> <br>
<input id="sub" type="submit">
</form>
Refresh
<a id="InsertDefault" href="">Insert Default Data</a>
<br>
<ul id="errors"></ul>
<p id="success"></p>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>
</html>
First, you're not sending the any of the inputs in your data: parameter. So $_REQUEST['name'], $_REQUEST['phone'], etc. won't exist.
Second, you can't access PHP variables in Javascript. The JSON that the PHP echoes at the end will be decoded into the result variable in the success: callback function.
Third, your syntax is wrong, the callback function needs to be in the success: option.
So it should be:
$("#PersonForm").submit(function()
{
$.ajax({
url: 'backend.php',
type: 'post',
data: 'act=validate&' + $(this).serialize(),
dataType: 'json',
success: function(result) {
if(result.name && result.phone && result.post && result.address){
$('#success').html('validated');
}
else{
$('#errors').html('Not Correct');
}
}
});
return false;
});
You should use the success and error callbacks so that you are waiting for the promise from the ajax call to come back. I am assuming you are trying to figure out how to get to the data that comes back. If you need further assistance with then validating the real data, I can help with that as well.
$.ajax({
url: 'backend.php', type: 'post', data: { act:'validate'},
dataType: 'json',
success: function (data) {
if($validateData==1){
$('#success').html('validated');
}
else{
$('#errors').html('Not Correct');
}
},
error: function (request, status, error) {
// Error occurred calling API
}
});

AJAX call display response from php script in html

I have a html file where users can input a value.
I wrote a script in PHP that checks if this value is present in the databse. If it's present it returns
{"active":true}
Now my goals is that when the user inputs their value and submit they will be redirected to a certain page if this active is true. If it's false they should see an error message.
So here's what I've tried with my AJAX call:
$("document").ready(function(){
$(".checkform").submit(function(e){
e.preventDefault();
$.ajax({
type: "GET",
dataType: "json",
url: "api/check.php",
data: data,
success: function(data) {
if(data.active=="true"){
alert("success");
location.href="where_you_want";
}else{
alert("failure");
}
}
});
return false;
});
});
Here is my HTML:
<form action="api/check.php" id="requestacallform" method="GET" name="requestacallform" class="formcheck">
<div class="form-group">
<div class="input-group">
<input id="#" type="text" class="form-control" placeholder="Jouw subdomein" name="name"/>
</div>
</div>
<input type="submit" value="Aanmelden" class="btn btn-blue" />
</form>
For some reason I get an error:
Uncaught ReferenceError: data is not defined
I am new to AJAX and I am not sure if what I am trying is correct.
Any help would be greatly appreciated!
Thanks in advance.
Can you try:
$(".aanmeldenmodal").submit(function(e){
e.preventDefault();
I am updating my answer in whole
<html>
<body>
<form action="api/check.php" id="requestacallform" method="GET" name="requestacallform" class="formcheck">
<div class="form-group">
<div class="input-group">
<input id="txt1" type="text" class="form-control" placeholder="Jouw subdomein" name="name"/>
</div>
</div>
<input type="submit" value="Aanmelden" class="btn btn-blue checkform" />
</form>
</body>
</html>
jQuery part is like
$("document").ready(function () {
$("body").on("click", ".checkform", function (e) {
e.preventDefault();
var request = $("#txt1").value;
$.ajax({
type: 'GET',
url: 'ajax.php',
data: {request: 'request'},
dataType: 'json',
success: function (data) {
if(data.active==true){
alert("success");
}else{
alert("failure");
}
}
});
});
});
ajax.php should be like this
if(isset($_GET['request'])){
//check for the text
echo json_encode($arr);
}
In api/check.php
You can pass data in json format
$json = json_encode($data);
retrun $json;
You can also not share any data so You can remove data from jQuery.
data:data
Your Jquery look like this:
$("document").ready(function(){
$(".checkform").submit(function(e){
e.preventDefault();
$.ajax({
type: "GET",
dataType: "json",
url: "api/check.php",
success: function(data) {
if(data.active=="true"){
alert("success");
location.href="where_you_want";
}else{
alert("failure");
}
}
});
return false;
});
});

I'm trying to send multiple data using jquery and ajax to another page to check if a value is present in database or not

function checkAvailability() {
$("#loaderIcon").show();
jQuery.ajax({
url: "check_availability.php",
data:'flatno='+$("#flatno").val(),
type: "POST",
success:function(data){
$("#flatno-availability-status").html(data);
$("#loaderIcon").hide();
},
error:function (){}
});
}
<div>
<input name="block_id" type="hidden" id="block_id" value="somevalue">
</div>
<div id="frmCheckflatno">
<label>Flat Number:</label>
<input name="flatno" type="text" id="flatno" onBlur="checkAvailability()"><span id="flatno-availability-status"></span>
</div>
<p><img src="LoaderIcon.gif" id="loaderIcon" style="display:none" /></p>
Script sends the value flatno to check_availability.php and queries info from database. Now I need to send two values - flatno and blockno to check_availability.php so that I can check database using 2 constraints.
function checkAvailability() {
var flatnoValue = $("#flatno").val();
var blocknoValue = $("#block_id").val();
$("#loaderIcon").show();
jQuery.ajax({
url: "check_availability.php",
data:'{flatno:flatnoValue,blockno:blocknoValue},
type: "POST",
success:function(data){
$("#flatno-availability-status").html(data);
$("#loaderIcon").hide();
},
error:function (){}
});
}
<div>
<input name="block_id" type="hidden" id="block_id" value="somevalue">
</div>
<div id="frmCheckflatno">
<label>Flat Number:</label>
<input name="flatno" type="text" id="flatno" onBlur="checkAvailability()"><span id="flatno-availability-status"></span>
</div>
<p><img src="LoaderIcon.gif" id="loaderIcon" style="display:none" /></p>
Send an array to your backend:
<script>
function checkAvailability() {
$("#loaderIcon").show();
var fn = $("#flatno").val();
var bn = $("#blockno").val();
jQuery.ajax({
url: "check_availability.php",
data: {flatno: fn, blocno: bn},
type: "POST",
success: function (data) {
$("#flatno-availability-status").html(data);
$("#loaderIcon").hide();
},
error: function () {}
});
}
</script>
Of course is better to check is there any values in both fields before calling php script.

Categories