I have a popup modal that displays on page load that has the following form in it:
<form class="enterForm">
<label class="modalFields" id="userName" style="display: none;">
<span>user Number :</span>
<input type="text" name="userNum" placeholder="User Number" required/>
</label>
</form>
<label>
<span> </span>
<input type="submit" value="Submit" class="submitButton">
<input type="hidden" id="hiddenInput">
</label>
And on user submission of the form, I want to hit a certain API via an AJAX call, which returns a JSON that looks like:
{
"results":[
{
"person":{
"firstName":"John",
"lastName":"Smith"
},
"userNumber":"12345"
}
]
}
If the userNumber matches the value that the user submitted, I then want to update the nav bar to say the person's first name. In terms of process flow I want it to go: user types in user number -> submits form -> AJAX call hits API -> checks to see if user input matches userNumber value in JSON --> if match, selects the firstName value and updates it in the nav bar. How could I go about achieving this?
Considering you know how to do AJAX calls and you're using an API, integrating jQuery to facilitate the thing shouldn't be too hard (if it is, I included additional information after the solution).
Solution
JavaScript
//On form submit
$('#enterForm').submit(function(){
var userNum = $('[name="userNum"]').val();
//AJAX call to your API
$.ajax({
url: 'myAPICall.php',
/* data: {userNumber: userNum}, //If necessary */
success: function(data) {
// Note: this code is only executed when the AJAX call is successful.
if(data.results.userNumber == userNum){
$('#navBarFirstName').text(data.results.person.firstName);
}
},
error: function (err) {
//If the AJAX call fails, this will be executed.
console.error(err);
}
dataType: 'JSON'
});
return false; //Prevents the page refresh if an action is already set on the form.
});
Explanation
You use jQuery to bind a function (event listener) to the submit event of your form.
When the submit event is triggered, the function runs:
It gets the value of your DOMElement with the name attribute "userNum"
It makes an AJAX call to your API (with/without the userNum value, you choose if you want to check that on the server side or not)
On success, (when the call is done successfully), it updates the navbar content using .text() with the firstName attribute of your JSON response.
Including jQuery
You can integrate jQuery by including the script within your HTML page. You can either download it or use a CDN:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js">
/* Don't put your code in here it won't be parsed */
</script>
<!-- the following tag could also be <script src="link/to/your/script.js"></script> -->
<script>
/* Your actual script */
</script>
Make sure to put this line before your actual javascript file containing the script written above, otherwise jQuery won't be initialized and the script won't work.
Related
Ok so I have a script that layers data throughout the process (an online test, data is kept for up to 50 questions). I have recently found that my Ajax and jquery code is not stopping all users from getting a secondary page that is meant to be reloaded in place of a DIV currently on the page. All information is passed through the jquery and ajax and works great, but sometimes on a users very first visit and first question it loads the page that is just meant to replace the DIV information currently and is not meant to be visible.
Here is my Ajax & jquery code:
<script>
$("#quizForm").submit(function(event){
event.preventDefault(); //prevent default action
var post_url = $(this).attr("action"); //get form action url
var form_data = $(this).serialize(); //Encode form elements for submission
$.post( post_url, form_data, function( response ) {
$("#prntqst").html( response );
dataLayer.push({"event" : "formSubmitted", "formName" : "'.$this->quizID.'"});
});
});
</script>
Here is the HTML:
<div id="prntqst"> <!-- this is DIV set to be reloaded -->
<font class="prntqst-text">Question Goes Here</font>
<form id="quizForm" action="ajax.php" method="post"> <!-- Script setup to handle submitted data -->
<input type="hidden" id="next_question" name="next_question" value="2">
<input type="hidden" id="quiz_type" name="quiz_type" value="learning">
<input type="hidden" id="quiz_name" name="quiz_name" value="knowledge-1">
<label class="container" for="a">Ans A
<input type="radio" name="answers[1]" id="a" value="a">
<span class="checkmark"></span>
</label>
<label class="container" for="b">Ans B
<input type="radio" name="answers[1]" id="b" value="b">
<span class="checkmark"></span>
</label>
<label class="container" for="c">Ans C
<input type="radio" name="answers[1]" id="c" value="c">
<span class="checkmark"></span>
</label>
<div class="subbtn_contain">
<div class="submitbtn">
<input id="submit" type="submit" class="button" value="Next Question">
</div>
</div></div>
</form>
<!-- currently this is the location of Ajax and jquery script -->
<div>
So when the form is submitted it processes the data through the ajax.php page, and then page reloads the next question into the "prntqst" DIV, after the first page load every request is sent to the ajax.php location, and all subsequent reloads carry all of the data needed for the test to work properly. However I find that if I use a new computer, or clear the cache the very first request can sometimes result in the user be pushed to the location of the ajax.php instead of them staying at the current URL with a DIV reload.
I have verified this issue through my analytics account, 99% of the time a user still shows at the correct URL as if the ajax is properly reloading the DIV, however sometimes it does show a user directly at the ajax.php script.
Any ideas or comments would be appreciated,
Thanks again!
Okay, I see now.
If you can have "some garbage" inside a code block and, as you say
works with or without that line...
That's because that code block is not even running at all.
The processData: false is a value assignation to an object property. It is ouside any object, in the code you provided. Then it seems like you tried to comment it like this: <!-- removed from code processData: false; -->, which also should throw an error. That is the HTML way to comment lines. in JS, it would be // removed from code processData: false;.
So... It seems that the form submits anyway. That just can the the "normal" form submit where the whole page reloads. As a test. Please try your page with that script completely removed. You should see no difference.
There is something else to explain here. You are playing with "dynamic" elements. Those are elements that didn't exist on page load and were added after... Or element that were there and were removed/replaced.
You have to write the script in such that this situation is handled.
In $("#quizForm").submit(function(event){ an event handler is attached to the element #quizForm. If there is no such element in the page when the page first load... Or there is a parsing error... The function won't run. So the event.preventDefault() won't be called either.
Then, assuming you fixed all errors in that code block and it runs. It squarely replaces all the HTML inside #prntqst. So for the second submit, the element on which the event handler was attached is not there anymore and the function won't run again.
The solution for that is to use event delegation to attach the event handler to the document and "delegate" it to the #quizForm (if exist when the handler is called).
That is $(document).on("event", "delegated_element_selector", function(){
So when the "event" fires within the "document", a lookup is made to find the "delegated_element_selector" and if found, the handler is executed.
That way is the way to have some event handler for the dynamic elements in a page.
Additionnally, about your question where to place the code, I added a $(document).ready() handler, which ensures the initial page load is complete before trying any jQuery lookup on some elements. So you can place that script where you want.
$(document).ready(function () {
$(document).on("submit", "#quizForm", function (event) {
console.log("Custom submit")
event.preventDefault(); //prevent default action
var post_url = $(this).attr("action"); //get form action url
var form_data = $(this).serialize(); //Encode form elements for submission
$.post(post_url, form_data, function (response) {
console.log(response)
$("#prntqst").html(response);
dataLayer.push({ event: "formSubmitted", formName: "'.$this->quizID.'" });
});
});
});
Now you should see "Custom submit" in the console on each form submit. And you should see what is the response too.
About post_url , I didn't any action attribute to the <form>... Maybe you just did not post it here on SO. Make sure there is one. Also make sure that the response $.post() should receive only is the necessary HTML and not a whole page (with <head>, <body>, etc...).
I have the following JS code:
<script>
$('#mpxModalEdit').on('show.bs.modal', function(e) {
var editId = $(e.relatedTarget).data('edit-id');
$(e.currentTarget).find('input[name="editId"]').val(editId);
});
</script>
This places the CORRECT edit-id value into a form text box name=editIdas I wish.
I would like to add another line of JS so that it ALSO places the value into a PHP variable since I need to make a subsequent
$query = "select * from playlists where id='editId'
I don't know any PHP syntax, but what I can tell you is that PHP is executed on the server and JavaScript is executed on the client (on the browser).
if on your page you had:
<form method="get" action="blah.php">
<input name="test"></input>
</form>
Your $_GET call would retrieve the value in that input field.
So how to retrieve a value from JavaScript?
Well, you could stick the javascript value in a hidden form field...
That could be the best solution only.
<script type="text/javascript" charset="utf-8">
var test = "tester";
// find the 'test' input element and set its value to the above variable
document.getElementByID("test").value = test;
</script>
... elsewhere on your page ...
<form method="get" action="blah.php">
<input id="test" name="test" visibility="hidden"></input>
<input type="submit" value="Click me!"></input>
</form>
Then, when the user clicks your submit button, he/she will be issuing a "GET" request to blah.php, sending along the value in 'test'.
Or the another way is to use AJAX.
PHP-Scripts are only run, when you load your page before any js is run or make an AJAX. In addition, PHP runs on the server, while JS is client-side.
My first suggestion would be, to really think, whether you need to do this (or even tell us, why you think it is).
If you really need it, you can perfom an AJAX and send your variable as data to the Server.
Using AJAX call you can pass js values to PHP script. Suppose you are passing editId js value to logtime.php file.
$(document).ready(function() {
$(".clickable").click(function() {
var userID = $(this).attr('id');
//alert($(this).attr('id'));
$.ajax({
type: "POST",
url: 'logtime.php',
data: { editId : editId },
success: function(data)
{
alert("success!");
}
});
});
});
<?php //logtime.php
$editId = isset($_POST['editId']);
//rest of code that uses $editId
?>
Place the AJAX call after
$(e.currentTarget).find('input[name="editId"]').val(editId);
line in your js script.
then you can assign to your desired PHP variable in logtime.php file
I am having an issue with this login system, when ever I click the log in button, or the sign up button it re-directs me to a white page with writing on it, That being said it is interfering with my log in action.
Here is the code that I think is causing the issue,
<form method="POST" action="" accept-charset="UTF-8">
on line 16 of the HTML code, I tried to take that code out and it stopped the re-directing but the text boxes went out of place, and the white background/background-box was not there either,
Link, HERE
You want to use preventDefault() if this is a purely Javascript: you should be able to pass the button press event into the listener when you create it:
$('.login').on('click', function(e) {
e.preventDefault();
// Will be executed on press
}
<form method="POST" class="login" accept-charset="UTF-8">
If there's no JS involved in this scenario, then you want to get rid of the action parameter entirely – leaving it as the empty string will still cause it to redirect in some cases.
As Jonathan Lonowski explained above, when the log in / sign up button is clicked, the form will post the data to the page mentioned in the action= attribute. Since this attribute is empty in your form tags, it will re-load the same page, posting the data to itself.
The data will arrive in key=value variable pairs. The variable value will be the contents of the field, the variable name will be the value of the name="" attribute on the element.
For e.g., for this field:
<input id="fname" name="first" value="Bobby" />
The data will be received like this:
$fn = $_POST['first']; //value is Bobby, or whatever user enters
On your page containing the form, add a section at the top like this:
<?php
if (isset($_POST['fname']) == true){
$fn = $_POST['fname'];
echo "Received First Name: " . $fn;
die();
}else{
?>
//Your current page, in its entirety, goes here
<?php
} //close the PHP if statement
?>
That is how you deal with a normal HTML <form> construct.
However, if you wish to use AJAX to communicate with a PHP file without changing the page, then:
(1) There is no need to use a <form> construct, just use a DIV with an input button: <input type="button" id="sub_btn" value="Submit" />
(2) Trap the button press using standard js/jQuery:
$('sub_btn').click(function(){
var fn = $('#first').val();
//etc.
$.ajax(function(){
type: 'post',
url: 'my_php_processing_file.php',
data: 'fname=' +fn+ '&lname=' etc
});
});
In your PHP processor file, the data will be received thus:
<?php
$fn = $_POST['fname'];
$ln = $_POST['lname'];
//Do your MySQL lookup here...
echo 'Received ' .$fn. ' ' .$ln;
(3) IF you do use the form construct, you can still do everything as above, but you will need to suppress the default form action of navigating to the page specified in the action= attribute (an attribute setting of action="" will post data to and reload the same page you are on).
To suppress navigating to the page specified in action= (involves page refresh, even if just action=""), use event.preventDefault(), as follows:
$('#buttonID').click(function(event){
event.preventDefault();
//remainder of button click code goes here
});
I'm developing a project of "prettifying" of a part of an existing web application. There is a need of putting the existing code: search criteria form in one div, and search results in another div (forming a kind of tabs, but that's another story).
Using jQuery I was able to manage that, but right now I am struggling with the results page, which by itself is yet another form that auto-submits to another file (using document.form.submit()), which is the final search results view. This auto-submit causes that the final view quits the destination div and loads as a new page (not new window).
So, the flow is like that:
First file, let's call it "criteria.html" loads the search criteria form (inside of a div) + another div (empty) destined to be filled with search results.:
<div id="criteria">... form with search criteria here...</div>
<div id="results"></div>
On submit, using jQuery's "hide()" method, I hide the first div (surrounding the search criteria form), and make Ajax call to the second file, let's call it "results.php":
<script>
$("#criteria").hide();
$.ajax({
...,
url: "results.php",
success: function(data){
$("#results").html(data);
},
...
});
</script>
results.php searches according to given criteria, and displays an "intermediary form" (which returns as a data result of the ajax query above) with a lot of hidden fields, and at the end executes:
<script>document.form.submit();</script>
which submits to another file, let's call it "resultsView.php"
This line causes that a result page shows outside the div "results", as a new page.
As there is a lot of logic in those files (more than 700 lines each), the idea of rewriting this monster just gives me creeps.
And now the question: is this a normal behavior (opening the result outside div)?
I tried removing the document.form.submit() code and everything works fine (well, without showing the results from "resultsView.php"). It's this line that causes the viewport to reset. I also tried with empty pages (to eliminate the possibility of the interaction with contents of the pages) - still the same result.
I hope there is not too much text and the problem is clearly stated. Every suggestion of how to fix this will be greatly appreciated.
If I understand your question correctly, you need to process the final submit using ajax instead of <script>document.form.submit();</script> so that you can handle the results on-page. Traditional form submits will always reload/open the action page. If you want to avoid that you'll have to control the form submit response via ajax and handle the results accordingly... like you are doing with the first submit.
The only alternative I can think of is to make div id="results" an iframe instead, so that it contains the subsequent form submit. Of course, that unleashes further restrictions that may cause other troubles.
I am not sure if I understood your question, but maybe u can do something like this.
This is my JQuery script: [I just wait for the submission search. When it happens, I use the $.Post method to call a function that should return the Html results (You can include somenthing to hide any field you want using JQuery or css)].
<script type="text/javascript" src="http://code.jquery.com/jquery-1.3.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("form#searchForm").submit(function() {
var theCity = $("select#chooseCity").val();
var theName = $("input#searchInput").val();
$.post("callProvideSearchResults.php", {theCity: theCity, theName: theName}, function(data) {
$("div#searchResults").html(data);
});
return false
});
});
</script>
This is my Body: {it consists of the choice of a city, the a form to provide the name of the person you are lookng for and the place to provide the results.
<body>
<FORM id="searchForm">
<h2>Select the city: </h2>
<select id="chooseCity">
<?php
$theCitiesOptionsHTML = "cityOptions.html";
require($thePathDataFiles.$theCitiesOptionsHTML); / A large list of cities
?>
</select>
<h2> What is the name of the person </h2>
<P> <INPUT id="searchInput" TYPE="TEXT" SIZE=50></P>
<P><INPUT TYPE="submit" VALUE="search"></P>
</FORM>
<div id="searchResults">
<!-- Here: Search results -->
</div>
</body>
// Function callProvideSearchResults.php // Just call the function that makes all the job and echo the $Html page
<?php
include "provideSearchResults.php";
$theName=$_POST['theName'];
$theCity=$_POST['theCity'];
echo provideSearchResults($theName, $theCity);
?>
// provideSearchResults.php // Database connection and search
<?php
function provideSearchResults($theName, $theCity) {
include "databaseConnection.php";
//database Queries
// Generate $theHtml using strings or ob_start, for instance
return $theHtml;
}
?>
I have a HTML form in a Mason component(A.m) that uses the post method to call another Mason component(B.m). I want this Mason component(B.m) to return a value to the HTML form in the Mason component(A.m). Then I want to pass this returned value to a Javascript function.
How can I do this? I'm new to web development.
You need to make an AJAX request. Although not strictly necessary, I would suggest you to use jQuery, it will make things a lot easier. Please also have a look at this question: jQuery AJAX submit form
Here's a little example in Mason, it's very simplified of course, you should add some error checking and some escaping also, but I think it could be a good start. Your A.mc component could look like this:
<html>
<head>
<title>This is A</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#myform").submit(function() { // intercepts the submit event
$.ajax({ // make an AJAX request
type: "POST",
url: "B", // it's the URL of your component B
data: $("#myform").serialize(), // serializes the form's elements
success: function(data)
{
// show the data you got from B in result div
$("#result").html(data);
}
});
e.preventDefault(); // avoid to execute the actual submit of the form
});
});
</script>
</head>
<body>
<form id="myform">
<input type="text" name="mytext" />
<input type="submit" />
</form>
<div id="result"></div>
</body>
</html>
it's just an HTML page that loads jQuery library and that contains your form, and that contains some code to instruct the form to make an AJAX request to B component when the user clicks the Submit button and then to show the contents returned by B component in your result div.
And this could be your B.mc component:
<%class>
has 'mytext';
</%class>
I got this text <strong><% $.mytext %></strong> from your form,
and its length is <strong><% length($.mytext) %></strong>.
Result will be like this: