Have you seen?
submit a form inside another form
Submitting form data to two locations using Javascript and PHP?
None of them actually answer the question.
Let me explain the scenario. I have a form that asks for Name, Email and Phone Number and it needs to be submitted to TWO locations on two different vendors.
1) Aweber
2) The Company
One possibility is to create a Javascript piece of code that when people click 'submit' it sends it to two form calls in two different browser windows (that would be my preferred method)
The second possibility would be to send it first to Aweber (autorespnder) and then pass the variables to a custom PHP page. Fetch the variables with $_GET and then pass those into an automatic form submit that passes those on to the 2nd form that goes to the company.
For example - I can submit the form to Aweber first and then pass the results back to form.php:
$name = $_get['name'];
$email = $_get['email'];
$phone = $_get['phone'];
What would the rest of the form look like with Curl or javascript?
I tried passing the variables into the company post form. It won't accept any GET commands - it only accepts a POST command, so CURL is probably not going to work, (unless there's a way to POST a form via CURL?)
Anyone have an elegant solution that doesn't look bad to end users?
What ideas do you have? Thanks in advance!
Without any real data to go on or real forms to call, this should give a basic idea of how to do it with AJAX and jQuery.
*Updated
I updated the answer to show how to pass the form variables as a post rather than a get.
HTML
<form id="test-form">
<input type="text" id="name" name="name"/>
<input type="submit" value="submit"/>
</form>
<p class="response1">
Response 1 goes here
</p>
<p class="response2">
Response 2 goes here
</p>
jQuery
$("#test-form").on("submit", function(e) {
e.preventDefault(); //stops the form from actually submitting
var root = 'https://jsonplaceholder.typicode.com';
$.ajax({
url: root + '/posts/1',
method: 'POST',
data: $("#test-form").serialize()
}).then(function(data) {
if(data) {
$(".response1").text(data.title);
$.ajax({
url: root + '/posts/2',
method: 'POST',
data: $("#test-form").serialize()
}).then(function(data) {
if(data) {
$(".response2").text(data.title);
}
});
}
});
})
Obviously you'd have to set the URL's correctly and pass the post data, which isn't happening here because I don't have an API to query that accepts post data. After the first form submits, it sends the data to the second form. How you handle the data is going to depend on what the responses are from the servers.
Fiddle: https://jsfiddle.net/calder12/t0fos3kk/1/
Related
I have html and css code for a basic quiz template. I want to give the user the ability to make their own custom quiz.
Example: I have created my own math quizzes, science quizzes, etc, that the user can take. I am looking for the ability that Users can make their own personal quiz.
You don't append users input to your code. You should have your quiz as a data and let the user update the data by adding their quiz.
The structure of a form looks like this:
<form method = 'post' action='./handleSubmission/'>
<label>Question 1: </label>
<input type='text' class='question' name='question1'>
<label>Answer 1: </label>
<input type='text' class='answer' name='answer2'>
<label>Question 2: </label>
<input type='text' class='question' name='question2'>
<label>Answer 2: </label>
<input type='text' class='answer' name='answer2'>
<button>Submit</button>
</form>
(You can find all the different input types here. You might want another type for multiple choice questions.
When the user clicks on submit, the default behaviour is that the content of the form will be sent as an http request to the action url. if you set post as method, the method will be POST. If you set get as method, the method will be GET.
Now, in order to do something useful with it, there needs to be a server-side script at './handleSubmission/' or whatever url you put in here, that can read the sent data and upload it to some place where you store the data for your quizzes. This can be either a database or a repository containing some files.
I'd go for json files. Because json files can very easily be decoded and used in any web scripting language.
In PHP for example you'd get the content of the form through a special array called $_GET (or $_POST depending on the method).
You'd then have access to 'question1' with $_GET['question1'].
You'd then have to find a way to put that data into a json file.
To use the content of the json files, you can either use a backend script or a frontend script like javascript.
Are you already using a scripting language for the backend such as PHP or Python? Or do you focus on frontend?
If you want to focus on javascript and frontend, this is the alternative:
<form>
//...
<button id='btn-submit'>Submit</button>
</form>
As you can see, i ommited action and method because in this alternative we don't want to send the form to the server. What we'll do is, when the button is clicked, we'll capture the content of the form without refreshing the page, and then send it a Backend-as-a-service like Google Firebase.
const submitButton = document.querySelector('#btn-submit');
submitButton.addEventListener('click', (e) => {
/* important! prevents the default behaviour which is to submit the form */
e.preventDefault();
const data = [];
/* do stuff here to retrieve the data from form like: */
const questionInputs = document.querySelector('.question');
const answerInputs = document.querySelector('.answer');
for(let key in questionInputs){
data[key] = {
question: questionInputs[key].value;
answer: answerInputs[key].value;
}
}
sendToFirebase(data);
});
You'd then have to write the sendToFirebase function.
Firebase requires making an account, starting a project by giving a name etc. Then it gives you the code to put in your app and you can read the documentation about how to upload data to the Realtime Database.
I strongly prefer the first option however. Because i think in this case the Firebase Realtime Database would be a bit cumbersome to use compared to just setting up a small backend script that generates json files.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have never been working with JS so im very lost here.
How do I save the values of countries and states into the db with php?
How do I set selected in < option > on the values that is in the db for current user?
http://jsfiddle.net/bdhacker/eRv2W/
<script language="javascript">
populateCountries("country", "state");
populateCountries("country2");
</script>
Been trying to do it but i cant.
thanks
What you are asking is not a single question but is an easy task. Its 101 in web-technology. You should read some articles first or take a web lesson before asking questions. You have not asked a specific question and so I am pretty sure this question will be marked as "too broad".
The comments you got in your question are very accurate and way to go. I will too try and get your ball rolling. Please understand that since the question is too broad, there is no way we can give you a full code that you can just copy paste and run. Instead I will give you pointers and then you can work things on your own.
Understand this first:
Server and Client are two different things. They both need to exchange data. PHP is server side and JS is client side.
In client side, you have some data (SELECT BOX in your case) and you want to send this data to the server because only server has access to the database.
Create a page in PHP called savedata.php in your app. This page will be responsible for saving the data to database once it has got the data.
Create a page called getdata.php in your app. This page will be responsible for getting the data from database if you request.
Then you need to create two "AJAX" functions in your client code i.e. in javascript that sends the data to savedata.php to save the data and getdata.php to get the data.
First let's code the client side:
Enclose your select tags with a <form> tag.
<form id="country-form" method="POST" action="">
<br/>Select Country (with states):
<select id="country" name="country"></select>
<br />State:
<select name="state" id="state"></select>
<br/>
<br />Select Country (without states):
<select id="country2" name="country2"></select>
<input type="submit" name="submit" id="submit" value="Save"></input>
</form>
Now lets code in javascript. We will use jquery and write an ajax request to save the data if the "Save" button is clicked.
//save data.
$(document).ready(function() {
$("#country-form").submit(function(event) {
event.preventDefault();
$.ajax({
method: "POST",
url: "http://localhost:80/myapp/savedata.php",
data: {
country: $("#country").val(),
state: $("#state").val(),
country2: $("#country2").val()
}
success: function(result) {
alert(result);
}
});
});
});
Let us understand what we have done here:
We have registered jquery so that when the document is loaded, it starts listening for "submit" of your form. When your form is submitted, we first prevent the default behaviour so that it does not submit the request and refresh the page.
We tell the ajax method to send the data via the post method to the given url and to send the given data. Once the data is submitted, the your PHP file returns some data to confirm the client that the operation was success or not. This is called a callback function. Read about it. Its awesome.
Now lets code up how to get the data.
//get data.
$(document).ready(function() {
$.ajax({
method: "POST",
url: "http://localhost:80/myapp/getdata.php",
success: function(result) {
$("#country").val(result['country']);
$("#state").val(result['state']);
$("#country2").val(result['country2']);
}
});
});
What this code does is:
It sends an ajax request to your given URL and when the server returns the data, the callback function is called. The server will return the an array with all the values. In client side you just extract these values and set these values in the HTML via jQuery.
Now lets code server side. Since you did not say you are uncomfortable with server side code, I am gonna assume you know PHP and database well. So lets skim this part quickly.
In your savedata.php function, catch the data explained in this post. You do this using the $_POST variable. e.g. $_POST['country'];
In your getdata.php code. E.g.:
$data = array();
$data['country'] = 1;
$data['state'] = 2;
echo json_encode($data);
One of our customers has a new requirement to dynamically capture the page/screen title and the labels of all the controls(textboxes, checkboxes, radio buttons, normal buttons,link,images,menu/menu items) on the page the users interacts with and then push them to an excel file.
If customer navigates/opens a page A and sets a value in the textbox Name = John , enables the checkboxChBox/radio button Rbutton and then finally clicks save/submit button, then the following output is being expected. User Action and Results being the first 2 columns of the Excel file.
**User Action** **Result**
Open Page/Screen A Page/Screen A is displayed
Set textbox Name = John Field Name is set successfully
Set ChBox = true ChBox is enabled successfully
Set Rbutton = true Rbutton is enabled successfully
Click Submit button Page B is displayed
Just wondering if it is possible to accomplish this and generic way of capturing the user interactions of any page.
Just an idea : you could listen all events (with jquery, for example), and then post an ajax request for each 'interesting' event (you have to filter...), store it in a database, and then add an 'export' function in csv or excel format.
Maybe some performance issues, it depends on the amount of pages, events and users...
The idea to use class name to filter is good, thanks to Hasan Iqbal Anik.
Javascript doesn't have access to writing files in hard drive. However you can capture the data, make a model and then store it in the server using ajax calls.
Some ideas:
Use a layout or master page that is rendered throughout the application views.
Give same class name for all the page labels, buttons, checkboxes and anything you need to store information about.
Use some jquery magic in the master/layout page to get the values of those elements and make an array.
Send that array through ajax call to the server.
Now you can get tons of examples of how to get element values using jquery. I'm saving you from giving all that. Hope that helps... :D
//edit: i'm trying to extend my answer as per steve requested.
<form action="someAction" id="myForm">
Name: <input type="text" class="Name">
Checkbox: <input type="checkbox" class="ChBox"/>Click this box
RButton: <input class="Rbutton" type="radio" />
Submit: <input type="submit" class="submit"/>
</form>
Now some jquery:
$(function() {
$(".submit").click(function(){
var dataToSend = new Object();
dataToSend.pageUrl = window.location.pathname + " is displayed";
if ($(".Name").val().length > 0) {
dataToSend.Name = "Field Name is set successfully";
}
else {
dataToSend.Name = "Field Name is empty";
}
if($(".ChBox").is(':checked')){dataToSend.ChBox = "ChBox is enabled successfully";}
else{dataToSend.ChBox = "ChBox is not enabled";}
if($(".Rbutton").is(':checked')){dataToSend.Rbutton = "Rbutton is enabled successfully";}
else{dataToSend.Rbutton = "Rbutton is not checked";}
dataToSend.Submit = $("#myForm").attr['action'] + " is displayed";
});
//now send it to the server via ajax
$.ajax({
type: "POST",
url: "your server action url that would make excel file with these data",
data: dataToSend,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
//do as you wish
}
});
});
Is it possible to run a MySQL query using jQuery? I'm trying to emulate the functionality of voting on SE sites.
The vote counter on SE automatically updates without the need to reload the page (which is what I currently have, a hidden form that re-submits to the current page but runs a small block on PHP that updates the score of a question in the database). I'm assuming that is being done using Javascript/jQuery seeing as it is dynamic.
How can I do this? Is there a library which makes it easy and simple (like PHP)?
You can use ajax to call a server page (PHP / ASP /ASP.NET/JSP ) and in that server page you can execute a query.
http://api.jquery.com/jQuery.ajax/
HTML
<input type='button' id='btnVote' value='Vote' />
Javascript
This code will be excuted when user clicks on the button with the id "btnVote". The below script is making use of the "ajax" function written in the jquery library.It will send a request to the page mentioned as the value of "url" property (ajaxserverpage.aspx). In this example, i am sending a querystring value 5 for the key called "answer".
$("#btnVote").click(function(){
$.ajax({
url: "ajaxserverpage.aspx?answer=5",
success: function(data){
alert(data)
}
});
});
and in your aspx page, you can read the querystring (in this example, answer=5) and
build a query and execute it againist a database. You can return data back by writing a Response.Write (in asp & asp.net )/ echo in PHP. Whatever you are returning will be coming back to the variable data. If your query execution was successful, you may return a message like "Vote captured" or whatever appropriate for your application. If there was an error caught in your try-catch block, Return a message for that.
Make sure you properly sanitize the input before building your query. I usually group my functionalities and put those into a single file. Ex : MY Ajax page which handles user related stuff will have methods for ValidateUser, RegisterUser etc...
EDIT : As per your comment,
jQuery support post also. Here is the format
$.post(url, function(data) {
alert("Do whatever you want if the call completed successfully")
);
which is equivalent to
$.ajax({
type: 'POST',
url: url,
success: function(data)
{
alert("Do whatever you want if the call completed successfully")
}
});
This should be a good reading : http://en.wikipedia.org/wiki/Same_origin_policy
It's just a few lines in your favorite language.
Javascript
$.post('script.php', { id: 12345 }, function(data) {
// Increment vote count, etc
});
PHP (simplified)
$id = intval($_POST['id']);
mysql_query("UPDATE votes SET num = num + 1 WHERE id = $id");
There are many different ways to accomplish this.
I'm working on a jQuery function that forwards form data to page without interfering with the normal submission. I can do it without any issues as long as I capture the submit using .submit(), but I would have to run my own validation on the data because it operates independently of the regular submission. Is there a way for jQuery (or any Javascript) to detect that form data has been posted and validated?
cheers,
Mike
Edit:
Workflow looks like this:
1. User enters data
2. Clicks submit
3. Site runs validation and accepts input
4. Submits data to new page
5. jQuery function detects new data was submitted and accepted so it runs.
More Edits for Clarity
I think you guys are missing the issue. I know how to detect a form is being submited (which is fine and dandy)
This is NOT what I want:
$(this).each(function(){
$(this).submit(function(){
*** Code ***
}
}
Suppose I have a validation script running independent of the code I am currently writing. How can I detect that this ran, and then go to the submit code above?
Use onsubmit="" on your <form> element, but return false. i.e.:
<form action="?" method="post" onsubmit="validate_and_submit(this);return false;">
The return false prevents the form from actually submitting so you can do stuff with AJAX.
Hope this helps!
What you need is AJAX here . So make a XHR request that goes to your server and posts data . The server's response would now go to a callback function ( your jquery function ) . If the data was validated and fine , you proceed further , else you stop .
What you are trying to do is not possible via the normal HTTP POST request .
EDIT: for the original clarification
If you want the server to only received validated data, then just make sure its not submitted to prior to the client-side validation occuring. You can do this with selectively calling event.preventDefault() based on the result of the validation.
$("#form").submit(function(event) {
//some stuff
if (validate(formdata) == false) {
event.preventDefault();
}
});
If you want a server to do the validation and submit to itself or another service, you should make that part of the server-side workflow. So it'd be like
1.) client submits to Service1
2.) Service1 validates
3.) Services1 submits to Service2 (such that service2 never receives code from elsewhere)