POSTING form contents using AJAX/JSON/JAVASCRIPT to a PHP script - javascript

I've been looking around for an explanation on how to do this for a while but haven't found a decent explanation yet, so apologies if this is a repeat.
I don't have any problem retrieving JSON using GET but I'm confused as to how to use POST to send JSON and have it interpreted at the far end by a PHP script
I'm trying to do this on localhost for now.
Form is as follows:
<div class="row">
<div class="col-sm-2 spacer"> </div>
<div class="col-sm-8 topSpaceNeeded"><h4>Select Currencies to Exchange</h4></div>
<div class="col-sm-2 spacer"> </div>
</div>
<div class="row">
<div class="col-sm-1"> </div>
<div class="col-sm-10">
<form id="formSendDataWithAjax" method="POST" action="./postedJsonData">
<div id="formSection1">
<div class="row">
<div class="col-sm-12"> </div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="userId">User ID</label>
<select class="form-control" id="userId" name="userId">
<option value="123456">123456</option>
<option value="654321">654321</option>
<option value="134256">134256</option>
<option value="652431">652431</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="originatingCountry" id="countryLabel">Country of Origin</label>
<select class="form-control" id="originatingCountry" name="originatingCountry">
<option value="IE">IRELAND</option>
<option value="EN">ENGLAND</option>
<option value="FR">FRANCE</option>
<option value="PL">POLAND</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="currencyFrom">Base Currency</label>
<select class="form-control" id="currencyFrom" name="currencyFrom" >
<option value="AUD">AUD</OPTION>
<option value="CAD">CAD</OPTION>
<option value="CHF">CHF</OPTION>
<option value="CZK">CZK</OPTION>
<option value="DKK">DKK</OPTION>
<option value="EUR" SELECTED>EUR</OPTION>
<option value="GBP">GBP</OPTION>
<option value="HKD">HKD</OPTION>
<option value="HUF">HUF</OPTION>
<option value="NOK">NOK</OPTION>
<option value="NZD">NZD</OPTION>
<option value="PLN">PLN</OPTION>
<option value="SEK">SEK</OPTION>
<option value="USD">USD</OPTION>
<option value="ZAR">ZAR</OPTION>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="currencyTo">Buy Currency</label>
<select class="form-control" id="currencyTo" name="currencyTo">
<option value="AUD">AUD</OPTION>
<option value="CAD">CAD</OPTION>
<option value="CHF">CHF</OPTION>
<option value="DKK">DKK</OPTION>
<option value="EUR" SELECTED>EUR</OPTION>
<option value="GBP">GBP</OPTION>
<option value="HKD">HKD</OPTION>
<option value="HUF">HUF</OPTION>
<option value="NOK">NOK</OPTION>
<option value="NZD">NZD</OPTION>
<option value="PLN">PLN</OPTION>
<option value="SEK">SEK</OPTION>
<option value="USD">USD</OPTION>
<option value="ZAR">ZAR</OPTION>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12"> </div>
</div>
</div>
<div id="formSection2">
<div class="row">
<div class="col-sm-12"> </div>
</div>
<div class="row">
<div class="col-sm-4"> </div>
<div class="col-sm-4">
<div class="form-group">
<label for="rate" id="rateLabel"> </label>
<input type="hidden" id="rate" name="rate" value="" >
</div>
</div>
<div class="col-sm-4"> </div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="amountSell">You Sell:</label>
<input type="number" class="form-control" step="0.10" id="amountSell" name="amountSell" value="1.00" >
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="amountBuy">You Buy:</label>
<input type="number" class="form-control" step="0.01" id="amountBuy" name="amountBuy" value="1.00" >
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12"> </div>
</div>
<div class="row">
<div class="col-sm-4"> </div>
<div class="col-sm-4">
<input type="submit" id="transfer" class="btn btn-primary btn-block" id="transfer" name="transfer" value="TRANSFER NOW">
</div>
<div class="col-sm-4"> </div>
</div>
</div>
</form>
</div>
<div class="col-sm-1"> </div>
</div>
I know it's probably easier to use JQuery, but Javascript is what I know so I'd like to stick with that if possible.
The Javascript is as follows:
document.getElementById('formSendDataWithAjax').onsubmit =submitDataWithAjax;
function submitDataWithAjax(e)
{
// intercept form submission by preventing the script from following the url of the form
e.preventDefault();
var f = e.target,
formData= new FormData(f),
xhr = new XMLHttpRequest();
xhr.open("POST", f.action);
xhr.setRequestHeader("Content-Type","application/json; charset=utf-8");
xhr.send(formData);
}
What I believe this script should do is prevent the postedJsonData page from loading when the form is submitted. Instead, the data is converted to JSON and should then be sent via AJAX to the postedJsonData PHP script
If this is correct, how do I get postedJsonData script to listen for the data?
Is it enough to do this to extract it to an array?
$dataArr = file_get_contents("php://input");

jQuery is much easier, I'd highly recommend it.
To use jQuery, just include this at the top of your page:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
Then, to do AJAX/JSON/PHP requests, replace what you currently have in your Javascript file with:
$(document).ready(function() {
$("#formSendDataWithAjax").submit(function() { //Whenever form with ID="formSendDataWithAjax" is submitted
$.ajax({ //Make AJAX POST call
type: "POST", //POST, instead of GET
url: "postedJsonData.php", //Location of PHP script
dataType: "JSON", //JSON
data: {
userid: $("#userId").val(), //These values will be JSON-encoded automatically
country: $("#originatingCountry").val(), //Magically JSON-encoded
etc.
}
}).done(function(returnValue) { //returnValue could be any JSON string: "{ "result" : "success" }, { "result" : "error" }, etc.
alert("Your PHP script returned this value: "+returnValue);
});
}
return false;
}
Then in your PHP script, simply calling $_POST['userid'] or $_POST['country'] will give you the value POSTed by the AJAX call. E.g.
<?php
$userid = (int) $_POST['userid'];
$country = $_POST['country'];
//Do stuff
?>

Related

how to apply reset button selected value

code is php dynamic, how to aplly reset button i am applying many more step please help me this right or wrong and how to right way say me.
code is php dynamic, how to aplly reset button i am applying many more step please help me this right or wrong and how to right way say me.
<div style="margin-top:2%;display:none; " id="filt_box" id="reset">
<div class="col-md-12">
<div class="form-group col-sm-4">
<label for="filter_seller_user">Sellers</label>
<select class="form-control-dropdown" id="filter_seller_user" name="filter_seller_user[]"
multiple="multiple">
#foreach($seller_user as $key=>$value)
<option value="{{$value->id}}">{{$value->name}}</option>
#endforeach
</select>
</div>
<div class="form-group col-sm-4">
<label for="filter_generated_by_user">Generated By</label>
<select class="form-control-dropdown" id="filter_generated_by_user"
name="filter_generated_by_user[]" multiple="multiple">
#foreach($clients_user as $key=>$value)
<option value="clients_user-{{$value->id}}">{{$value->name}}</option>
#endforeach
#foreach($main_clients_user as $key=>$value)
<option value="main_clients_user-{{$value->id}}">{{$value->name}}</option>
#endforeach
</select>
</div>
<div class="form-group col-sm-4">
<label for="filter_generated_by_user">Business Name</label>
<input type="tetx" name="filter_business_name" id="filter_business_name" class="form-control">
</div>
</div>
<div class="col-md-12 div_btn">
<div id="err_date" class="text-danger"></div>
<button class="btn" id="btn_filter_submit" onclick="show_report_data();">Go</button>
<button class="btn" id="btn_filter_submit" onclick="show_reset_data();">Clear</button>
</div>
</div>
using multiple try javascript code but not apply any changes
<script src="{{asset('assets/js/jquery.min.js')}}"></script>
<script>
function show_reset_data() {
$("reset").each(function() { this.selectedIndex = 0 });
}
function show_reset_data() {
document.getElementById("reset").reset();
}
function show_reset_data() {
document.getElementById("reset").value="";
}
</script>
I inserted class="reset" in each selected field means input field and button clear Id="reset" create and simple write javascript code.
<div style="margin-top:2%;display:none; " id="filt_box">
<div class="col-md-12">
<div class="form-group col-sm-4">
<label for="filter_seller_user">Sellers</label>
<select class="form-control-dropdown reset" id="filter_seller_user" name="filter_seller_user[]" multiple="multiple">
#foreach($seller_user as $key=>$value)
<option style = "font-size:13px;" value="{{$value->id}}">{{$value->name}}</option>
#endforeach
</select>
</div>
<div class="form-group col-sm-4">
<label for="filter_generated_by_user">Generated By</label>
<select class="form-control-dropdown reset" id="filter_generated_by_user" name="filter_generated_by_user[]" multiple="multiple">
#foreach($clients_user as $key=>$value)
<option style = "font-size:13px;" value="clients_user-{{$value->id}}">{{$value->name}}</option>
#endforeach
#foreach($main_clients_user as $key=>$value)
<option style = "font-size:13px;" value="main_clients_user-{{$value->id}}">{{$value->name}}</option>
#endforeach
</select>
</div>
<div class="form-group col-sm-4">
<label for="filter_generated_by_user">Business Name</label>
<input type="tetx" name="filter_business_name" id="filter_business_name" class="form-control reset">
</div>
</div>
<div class="col-md-12 div_btn">
<div id="err_date" class="text-danger"></div>
<button class="btn" id="btn_filter_submit" onclick="show_report_data();">Go</button>
<button class="btn" id="reset" style="background-color: #ae3029; color:white;">Clear</button>
</div>
javascript code
$("#reset").on('click', function () {
$('.reset').val('');
});

Get selected value from drop down and pass selected value into submit button in php

I have two drop down from two different array.
i want to get/store selected value from drop down. so that i can pass/send selected value in submit button (href)
Example:supoose user select email as 123 and center as "training",so i need to pass thoes two value in submit button like below-
<main role="main">
<div class="row">
<div class="col-md-12">
<h4 class="heading-theme page-header pdt">Create Email Template</h4>
<span class="border-bottom display-block mb-20"></span>
</div>
</div>
<div class="row mb-3">
<div class="col-lg-3 col-md-12 mb-1">
<select class="custom-select" id="status" title="Status">
<option value="" selected>Select Template</option>
<?php
foreach ($emailTemplate as $row) {
?>
<option value="<?= $row['temp_desc'] ?>"><?= $row['temp_desc'] ?></option>
<?php
}
?>
</select>
</div>
<div class="col-lg-3 col-md-12 mb-1">
<select class="custom-select" id="status" title="Status">
<option value="" selected>Select Center</option>
<?php
foreach ($trainingCenter as $row) {
?>
<option value="<?= $row['organization_name'] ?>"><?= $row['organization_name'] ?></option>
<?php
}
?>
</select>
</div>
<div class="col-lg-4"></div>
</div>
<div>
<div class="row">
<div class="col-md-12">
<div class="mt-2"><a href=" /Mycenter/testmailtemplate/value1/value2" class="text-default btn btn-sm pri-btn pt-2 mr-3 ">
Submit
</a>
</div>
</div>
</div>
</main>
You can get both selected values using each loop inside some variable then split that values and finally add them to href of your tag.
Demo Code :
$("select").on("change", function() {
var values = "";
//traverse through all selects
$(".status").each(function() {
//separate values using "."
values += $(this).val() + ".";
})
//split values
var new_values = values.split(".");
var select_text= $('#status :selected').text();//getting selected text
$new_href = "/Mycenter/testmailtemplate/" + new_values[0] + "/" + new_values[1]+"/"+ select_text;
//add value to your href
$(".pri-btn").attr("href", $new_href)
console.log($new_href)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<main role="main">
<div class="row">
<div class="col-md-12">
<h4 class="heading-theme page-header pdt">Create Email Template</h4>
<span class="border-bottom display-block mb-20"></span>
</div>
</div>
<div class="row mb-3">
<div class="col-lg-3 col-md-12 mb-1">
<!--added class="status"-->
<select class="custom-select status" id="status" title="Status">
<option value="" selected>Select Template</option>
<option value="1">1th</option>
<option value="2">2th</option>
<option value="3">3th</option>
</select>
</div>
<div class="col-lg-3 col-md-12 mb-1">
<!--added class="status"-->
<select class="custom-select status" title="Status">
<option value="" selected>Select Center</option>
<option value="1">
1</option>
<option value="2">
2</option>
<option value="3">3
</option>
</select>
</div>
<div class="col-lg-4"></div>
</div>
<div>
<div class="row">
<div class="col-md-12">
<div class="mt-2"><a href=" /Mycenter/testmailtemplate/value1/value2" class="text-default btn btn-sm pri-btn pt-2 mr-3 ">
Submit
</a>
</div>
</div>
</div>
</main>
$(".custom-select").on("change", function() {
var value1 = $("#status1").val();
var value2 = $("#status2").val();
var url = '/Mycenter/testmailtemplate/'+value1+'/'+value2;
$(".pri-btn").attr("href", url );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<main role="main">
<div class="row">
<div class="col-md-12">
<h4 class="heading-theme page-header pdt">Create Email Template</h4>
<span class="border-bottom display-block mb-20"></span>
</div>
</div>
<div class="row mb-3">
<div class="col-lg-3 col-md-12 mb-1">
<!--added class="status"-->
<select class="custom-select status" id="status1" title="Status">
<option value="" selected>Select Template</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<div class="col-lg-3 col-md-12 mb-1">
<!--added class="status"-->
<select class="custom-select status" id="status2" title="Status">
<option value="" selected>Select Center</option>
<option value="1">
1</option>
<option value="2">
2</option>
<option value="3">3
</option>
</select>
</div>
<div class="col-lg-4"></div>
</div>
<div>
<div class="row">
<div class="col-md-12">
<div class="mt-2"><a href=" /Mycenter/testmailtemplate/value1/value2" class="text-default btn btn-sm pri-btn pt-2 mr-3 ">
Submit
</a>
</div>
</div>
</div>
</main>

How to add <div> in <form> on button click html and jquery

I want to add the following div structure whenever the '+' button [the addMore() function] is clicked. Although i am able to add the div structure, but the alignment of the input text are not equal as compared to the hard coded.
html file:
<form class="align-center">
<p class="6u 12u$(medium)">
Start Date: <input type="date" name="startdate" id="startdate" />
End Date: <input type="date" name="enddate" id="enddate" />
</p>
<p>
<div class="6u$ 12u$(xsmall)"><input type="text" name="numParticipants" id="numParticipants" value="" placeholder="Number of Participants"/></div>
</p>
<p>
<div class="row">
<div class="3u 12u$(medium)">
<div class="select-wrapper">
<select>
<option value="">-Select Programme-</option>
<option value="1">Yogalates</option>
<option value="2">Pilates</option>
<option value="3">Kick Boxing</option>
<option value="4">K-Pop Dance</option>
<option value="5">Hip Hop</option>
<option value="6">Jazz Aerobics</option>
<option value="7">Zumba</option>
<option value="8">Fitball</option>
</select>
</div>
</div>
<div>OR</div>
<div class="3u 12u$(medium)">
<div class="12u$">
<input type="text" value="" placeholder="Customize your own programme" />
</div>
</div>
<div class="2u 12u$(medium)">
<div class="12u$">
<input type="text" value="" placeholder="Venue" />
</div>
</div>
</div>
</p>
<p>
<div class="row" id="newProg">
</div>
<div class="row">
<div class="2u 12u$(medium)">
<a class="button" onclick="addMore()"><div style="font-size: 35px">+</div></a>
<a class="button" style="margin:0 0 0 1em" onclick="removeProg()"><div style="font-size: 35px">-</div></a>
</div>
</div>
<div class="2u 12u$(medium); image right">
Submit
</div>
</p>
</form>
main.js
var counter = 0;
function addMore() {
counter++;
var objNewDiv = document.createElement('div');
objNewDiv.setAttribute('id', 'addProg' + counter);
objNewDiv.setAttribute('class', 'row');
objNewDiv.innerHTML = '<div class="5u 12u$(medium)"> <div class="select-wrapper"> <select> <option value="">-Select Programme-</option> <option value="1">Yogalates</option> <option value="2">Pilates</option> <option value="3">Kick Boxing</option> <option value="4">K-Pop Dance</option> <option value="5">Hip Hop</option> <option value="6">Jazz Aerobics</option> <option value="7">Zumba</option> <option value="8">Fitball</option> </select> </div> </div> <div>OR</div> <div class="5u 12u$(medium)"> <input type="text" value="" placeholder="Customize your own programme"/> </div> <div class="3u$ 12u$(medium)"> <input type="text" value="" placeholder="Venue" /> </div> ';
document.getElementById('newProg').appendChild(objNewDiv);
}
Result when page is loaded:
when page loaded
Actual and Expected result:
actual and expected outcome
You have differenc in the class names of the div tags which you are appending in jquery.
Make it same as the Static HTML content, And the expected result will be achieved.
Differences I see is as below.
Static HTML has - <div class="3u 12u$(medium)"> ,Your Jquery HTML has - <div class="5u 12u$(medium)">
Static HTML has - <div class="3u 12u$(medium)">, Your jquery HTML has - <div class="5u 12u$(medium)">
Static HTml has - <div class="2u$ 12u$(medium)">, Your Jquery HTML has <div class="3u$ 12u$(medium)">
Because of the differences in the class names you find the differences in the way its rendered in the UI.
You missed one of your divs in JavaScript inner HTML string. I think it should be like this:
objNewDiv.innerHTML = '<div class="5u 12u$(medium)"> <div class="select-wrapper"> <select> <option value="">-Select Programme-</option> <option value="1">Yogalates</option> <option value="2">Pilates</option> <option value="3">Kick Boxing</option> <option value="4">K-Pop Dance</option> <option value="5">Hip Hop</option> <option value="6">Jazz Aerobics</option> <option value="7">Zumba</option> <option value="8">Fitball</option> </select> </div> </div> <div>OR</div> <div class="5u 12u$(medium)"> <div class="12u$"> <input type="text" value="" placeholder="Customize your own programme"/> </div> </div> <div class="3u$ 12u$(medium)"> <div class="12u$"> <input type="text" value="" placeholder="Venue" /> </div> </div> ';

How to append child div into a parent div using jquery on the click of a button

<div class="addMore">
<div class="row addPlus">
<p class="emergencyTitle">Child 1</p>
<div class="col-xs-6">
<form role="form">
<div class="form-group">
<label for="name">Student Name</label>
<input type="text" class="form-control" name="ch1_name">
</div>
<div class="form-group">
<label for="name">Class</label><br>
<select name="ch1_class">
<option value=""> 1 </option>
<option value=""> 2</option>
<option value=""> 3 </option>
</select>
</div>
</form>
</div>
<div class="col-xs-6">
<form role="form">
<div class="form-group">
<label for="name">DOB</label>
<input type="text" class="form-control" name="ch1_dob" id="datepicker">
</div>
<div class="form-group">
<label for="name">Section</label><br>
<select name="ch1_secion">
<option value=""> A </option>
<option value=""> B </option>
<option value=""> C </option>
</select>
</div>
</form>
</div>
</div>
</div>
On the click of a button I am doing this ..
$child = $('.addPlus')
$('.addMore').append($child)
But I cannot seem to add the addPlus div, how over $('.addMore').append("hi") works fine. Can anyone help me out where I am going wrong.
if you want to clone the item - you can use
$('.addPlus').first().clone().appendTo('.addMore')
.addPlus is already appended to .addMore, so your jQuery would work but have no effect.
Assuming you want to copy the existing instance of .addPlus you should call clone() on it before appending it to the parent, like this:
var $newChild = $('.addPlus').first().clone()
$('.addMore').append($newChild)

The selected option must shown after the function of onchange

I have 2 dropdowns, just like the title.. The selected option must shown after the function of onchange meaning when it automatically refreshes the selected option must stay and show the selected options . The problem is when I select an option from the 2nd dropdown which has onchange function it refreshes and it gets back to the default option.
Here's the code
<div id="page-wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<div class="col-lg-10">
<h1 class="page-header">
BRANCHES
</h1>
</div>
<div class="col-lg-2">
<a class="btn btn-default bad-marg" href="index.php?act=abr" role="button">Add Branch</a>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div id="form">
<form action="func_vbrs.php" method="POST" class="form-horizontal">
<fieldset>
<div class="row">
<div class="col-lg-4">
<div class="form-group">
<label for="bl" class="control-label col-xs-3"><p class="left">Branch</p></label>
<div class="col-xs-8">
<div class="req">
<select name="bid" class='form-control'>
<option value='' default style='color:gray;'>Branch</option>
<?php
include_once "config.php";
$sql="select branchID, b, bl from branch where b!='HOK'";
$stmt=$con->prepare($sql);
$stmt->execute();
$stmt->bind_result($bid, $b, $bl);
$stmt->store_result();
while($stmt->fetch()){
echo '<option value="'.$bid.'">'.$b.'-'.$bl.'</option>';
}
?>
</select>
</div>
</div>
<div class="col-xs-1">
</div>
</div>
</div>
<div class="col-lg-4">
<div class="form-group">
<label for="cat" class="control-label col-xs-3"><p class="left">Category</p></label>
<div class="col-xs-8">
<div class="req">
<select name="brcat" class="form-control" onchange='this.form.submit()'>
<option value="" default style="color:gray;">Category</option>
<option value="Stock">Stock</option>
<option value="Sales">Sales</option>
<option value="Stock Transfer">Stock Transfer</option>
</select>
</div>
</div>
<div class="col-xs-1">
</div>
</div>
</div>
<div class="col-lg-4">
</div>
</div>
<noscript><input type="submit" value="Submit"></noscript>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
As you can see the 2nd drop down is category, If a user already selects an option after the automatic refresh or onchange function, it gets back to default option.
You need to cross check against post on page load, and add a selected tag appropriately. There are more elegant solutions with less bulky code if you use a loop to create your options, but that's another question.
<?PHP
if (!empty($_POST['brcat'])){
$selected_item = $_POST['brcat'];
} else { $selected_item = Null; }
function selcheck($item1, $item2){
if ($item1 == $item2){
$ret = " selected=\"selected\" ";
} else {
$ret = "";
}
return($ret);
}
?>
<select name="brcat" class="form-control" onchange='this.form.submit()'>
<option value="" default style="color:gray;">Category</option>
<?PHP
$sel = selcheck("Stock",$selected_item);
?>
<option value="Stock"<?=$sel?>>Stock</option>
<?PHP
$sel = selcheck("Sales",$selected_item);
?>
<option value="Sales"<?=$sel?>>Sales</option>
<?PHP
$sel = selcheck("Stock Transfer",$selected_item);
?>
<option value="Stock Transfer"<?=$sel?>>Stock Transfer</option>

Categories

Resources