My dad and I are working on a project where we'd like to create a script that calls in data when a number is submitted into a form. For example, when you type in your ID number then press ENTER or SUBMIT, the form will print/display information. This is a project for school, so when a student submits their ID number it will read their first period class, for example.
I have the following script code to set up the form:
<form id="firstPeriod" action="firstPeriod.html">
<p>Find your first period.</p>
<p><label>Student no.: <input type="text" name="studentNo"></label></p>
<p><input type="submit" value="Find it"></p>
<p id="result"></p>
</form>
<script type="text/javascript">
$(function() {
$('#firstPeriod').submit(function() {
$.ajax({ // Send the request behind the scenes
url: $(this).attr('action'), // Send it here
data: $(this).serialize(), // With this student no.
success: function(data) {
$('#result').html(data); // Display the resulting HTML
},
error: function(jqxhr, status, error) {
console.log(error);
$('#result').html('No results found. Please check your number and reenter'); // Notify an error
}
});
return false; // Prevent the normal form submission
});
});
My question is, what would be the best way to organize the data? An array, HTML, etc.? There are quite a lot of ID numbers and are currently set up in an HTML table, but that doesn't seem to work in calling the information. And I'd like for the data to be specific. So when a specific ID number is typed in, it reads a specific answer. Right now my problem is when I type in a number it reads several classes.
If there are any suggestions/advice/other posts that could help me, I'd be grateful. I have solid HTML, CSS experience but I'm still learning JS and jQuery so this is a little new for me. Thanks!
Edit, Updated
Note, added value attribute to input type="text" element
<input type="text" name="studentNo" value="" />
substituted .submit() for .on("click") at input type="submit" element
Two possible approaches could be 1) using HTML to store data, .load() to retrieve fragment identifier within html file; or 2) storing data using JSON, retrieving file using php
html at firstPeriod.html
<div id="0">data 0</div><div id="1">data 1</div>
javascript
$(function() {
var form = $("#firstPeriod");
$("input[type=submit]").on("click", function(event) {
event.preventDefault();
event.stopPropagation();
var data = form.serializeArray();
// where `data[0].value` is `id`; e.g.; `0`
var id = data[0].value;
$("#result").load(form.attr("action") +" #"+ id)
})
})
plnkr http://plnkr.co/edit/4onHf9jlJTyDei1zo9IC?p=preview
JSON
0.json
{
"0":"<div id='0'>data 0</div>"
}
1.json
{
"1":"<div id='1'>data 1</div>"
}
javascript
$(function() {
var form = $("#firstPeriod");
$("input[type=submit]").on("click", function(event) {
event.preventDefault();
event.stopPropagation();
var data = form.serializeArray();
// where `data[0].value` is `id`; e.g.; `0`
var id = data[0].value;
$.post("data.php", {id:id}, function(result) {
$("#result").html(result[id])
}, "json")
})
})
php
<?php
if (isset($_POST["id"])) {
$id = $_POST["id"];
$file = $id . ".json";
if (file_exists($file)) {
$jsondata = file_get_contents($file);
$id_data = json_decode($jsondata, true);
echo json_encode($id_data);
};
}
Related
I posted this question ealier today, however I recieved a fix (thank you) that works great against my RequestBin endpoint for testing, however when submitting to my AJAX script, its a different story.
Problem: I cant submit my jQuery toggle values to my PHP AJAX script because there is no form name associated with the POST request (so db never updates). I proven this by making a HTML form with the field names and the database updated right away. However this is not the case with this JS toggle method.
jQuery code
$(document).ready(function() {
$('.switch').click(function() {
var $this = $(this).toggleClass("switchOn");
$.ajax({
type: "POST",
url: "https://--------.x.pipedream.net/",
data: {
value: $this.hasClass("switchOn") ? 'pagination' : 'infinite'
},
success: function(data) {
console.log(data);
}
});
});
});
HTML
<div class="wrapper-toggle" align="center">
<label>
<div class="switch"></div>
<div class="switch-label">Use <b>Paged</b> results instead (Current: <b>Infinite</b>)</div>
</label>
</div>
PHP AJAX script
if (array_key_exists('pagination', $_POST)) {
$stmt = $conn->prepare("UPDATE users SET browse_mode = 'pagination' WHERE user_id = 1");
//$stmt->bindParam(":user_id", $account->getId(), PDO::PARAM_INT);
$stmt->execute();
} else if (array_key_exists('infinite', $_POST)) {
$stmt = $conn->prepare("UPDATE users SET browse_mode = 'infinite' WHERE user_id = 1");
//$stmt->bindParam(":user_id", $account->getId(), PDO::PARAM_INT);
$stmt->execute();
}
I cant figure out how to assign a field name to this, as it is not a traditional post form. This is driving me nuts. So the previous solution was applying hasClass() and calling var $this outside of $ajax(), great (and RequestBin receives both requests), but when submitting to PHP its a dead end (no form names).
Given the code above fixed and revised twice, where do I even start without a form ??
We need:
name="pagination"
name="infinite"
But this toggle JS doesn't allow for this. prop() has been removed to get toggle submitting values over (just not my AJAX script).
Any solution appreciated. Thank you again.
You can set your values as Form Data. So the PHP Function will get it just like a traditional form submission:
$(document).ready(function() {
$('.switch').click(function() {
var $this = $(this).toggleClass("switchOn");
var formdata = new FormData();
$this.hasClass("switchOn") ? formdata.append('pagination', 'name') : formdata.append('infinite', 'name');
$.ajax({
type: "POST",
url: "https://--------.x.pipedream.net/",
data: formdata,
success: function(data) {
console.log(data);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
More info on JS Form Data: https://developer.mozilla.org/en-US/docs/Web/API/FormData
I am adding a text area on click of a particular div. It has <form> with textarea. I want to send the jquery variable to my php page when this submit button is pressed. How can this be achievable. I am confused alot with this . Being new to jquery dizzes me for now. Here is my code,
`
<script type="text/javascript">
$(document).ready(function(){
$('.click_notes').on('click',function(){
var tid = $(this).data('question-id');
$(this).closest('ul').find('.demo').html("<div class='comment_form'><form action='submit.php' method='post'><textarea cols ='50' class='span10' name='notes' rows='6'></textarea><br><input class='btn btn-primary' name= 'submit_notes' type='submit' value='Add Notes'><input type='hidden' name='submitValue' value='"+tid+"' /></form><br></div>");
});
});
</script>`
Your code works fine in the fiddle I created here -> https://jsfiddle.net/xe2Lhkpc/
use the name of the inputs as key of $_POST array to get their values.
if(isset($_POST['submitValue'])) { $qid = $_POST['submitValue']; }
if(isset($_POST['notes'])) { $notes = $_POST['notes']; }
You should send your data after form submitted, something like this
:
$(".comment_form form").submit(function(e) {
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
you can assign event after insert your form.
// handling with the promise
$(this).closest('ul').find('.demo').html("<div class='comment_form'><form action='submit.php' method='post'></form><br></div>").promise().done(function () {
// your ajax call
});;
I have a form with a button that can add dynamic input fields, and it's creating an ajax issue. My ajax post is giving me 500 errors
But My console log for data right now is this:
but I need to insert these as
insert into ticker_content (ticker_id, content)
values (1, 'one'), (1, 'two');
If that makes sense.
So basically, the problem is i have multiple inputs at any given time (containing text values) and a hidden input in the form that gives me my correct ticker ID.
However, I need to make my array contain elements that each have the input text value and the ticker ID. So for every input that's created and filled, I need to assign the value of that form's hidden input to it as well so I can sent them as pairs to my foreach loop and insert.
Here's my addticker.php that's being called for the insert:
$items = $_POST['Items'];
$tickerID = $_POST['tickerID'];
foreach ($items as $item){
$addTicker = "
INSERT INTO ticker_content (tickerID, content)
values ('$tickerID', '$item');
"
$mysqlConn->query($addTicker);
}
So basically for every Items[] value, I need to insert with the same hidden field.
Here's my form and JS code for reference. The first JS block is mainly for the functionality of dynamically adding inputs, but the last JS block is the ajax using serializeArray();
<?php foreach($tickerDisplays as $key => $ticker):?>
<form id="Items" method="post">
<label id="ItemLabel">Item 1: </label>
<input type="text" name="Items[]"><br/> <!--form starts with one input-->
<button type="button" class="moreItems_add">+</button> <!--button dynamically adds input, up to 10 per form-->
<input type="hidden" name="tickerID" id="tickerID" class="tickerIdClass" value="<?php echo $ticker['ticker'] ?>"><!--hidden input used for tickerID-->
<input type="submit" name="saveTickerItems" value="Save Ticker Items"> <!--submit button-->
</form>
<?php endforeach;?>
<!-- This is the functionality for each form to click the '+' button and create new inputs -->
<script type="text/javascript">
$("button.moreItems_add").on("click", function(e) {
var tickerID = $(this).closest('form').find('.tickerIdClass').val(); //get value of hidden input for form
var numItems = $("input[type='text']", $(this).closest("form")).length;
if (numItems < 10) {
var html = '<label class="ItemLabel">Item ' + (numItems + 1) + ': </label>';
html += '<input type="text" name="Items[]"/><br/>';
$(this).before(html);
console.log(tickerID);
}
});
</script>
<!-- This is the ajax call to send all filled out and created inputs from form along with the hidden input -->
<script type="text/javascript">
$("#Items").submit(function(e) {
e.preventDefault();
var data = $("#Items").serializeArray();
console.log(data);
$.ajax({
type: "POST",
url: "addticker.php",
data: $("#Items").serializeArray(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
</script>
Firstly, you are missing a semicolon in your code (which is likely causing your 500 error).
Secondly, if you want to bundle all the fields from the form as a single query, the following will build out a query similar to what you noted earlier in your question as:
INSERT INTO ticker_content (ticker_id, content) VALUES(1, 'one'), (1, 'two'), ...
$items = $_POST['Items'];
$tickerID = $_POST['tickerID'];
$addTicker = "INSERT INTO ticker_content (tickerID, content) values";
foreach ($items as $item){
$addTicker .= "('$tickerID', '$item'),";
}
$addTicker = substr($addTicker, 0, -1); // Eat that last comma
$mysqlConn->query($addTicker);
Your HTML also needs some work because the id attribute should be unique on the page. Since you are duplicating the form, you should do something like the following:
<form id="Items<?php echo $ticker['ticker']?>" class="tickerform" method="post">
And then update your javascript:
// Using $(this) in Jquery allows you to access the
// element that is making the method call (in this case, the form)
$(".tickerform").submit(function(e) {
e.preventDefault();
var data = $(this).serializeArray();
console.log(data);
$.ajax({
type: "POST",
url: "addticker.php",
data: data, // Don't need to serialize again, 'var data' is still in scope.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
I have a textarea in which user enter url and link is extracted successfully and appended to a div. How can I store that extracted data into database as the extracted data is in a div not in any input?
<textarea id="get_url" placeholder="Enter Your URL here" class="get_url_input" spellcheck="false" ></textarea>
<input type="button" value="Share">
<div id="results">
</div>
Extracted data is shown in result div, do I need to store the response into any hidden input and check if it is empty while clicking on share button?
There are several ways to do this but I would recommend using:
Ajax and JQuery
In your JavaScript file add:
var data = $('#div id').text();
$.ajax ({
url: "www.websitename.com/addurl.php",
type: 'POST',
data: { urltoadd: data},
success: function (response){
If (response = 'successful'){
return true;
}else {
return false;
}
}
});
Now in your addurl.php file:
<?php
$urltoadd = $_POST ['urltoadd'];
... add Code to save $urltoadd in your database.
If (file was added successfully){
echo 'successful';
}else {
echo 'failed';
}
? >
On form submit you can bind a function and in that functiom
using jquery you can do $('#result').text()
I have an issue I can't seem to solve, I have a form with a bunch of text-fields but I need to extract their information through AJAX or just through a simple JavaScript function. I need this data to be extracted, string by string into an array which should then be passed to PHP. If understood this correctly, AJAX can be used with JQuery or JavaScript, now I'm not sure I understand JQuery very well. Anyway I've been searching google for good examples, and I really can't find anything good.
<form class="registration" method="POST">
<ul class="registration">
<li><label>Nombre de Usuario:</label></li>
<li><input type="text" name="username" title="Nombre de Usuario"/></li>
<li><label>Contraseña:</label></li>
<li><input type="text" name="password" title="Contraseña"/></li>
<li><label>Correo Electrónico:</label></li>
<li><input type="text" name="email" title="Correo Electrónico"/></li>
<li><label>Nombre:</label></li>
<li><input type="text" name="name" title="Nombre"/></li>
<li><label>Primer Apellido:</label></li>
<li><input type="text" name="first last name" title="Primer Apellido"/></li>
<li><label>Segundo Apellido:</label></li>
<li><input type="text" name="second last name" title="Segundo Apellido"/></li>
<li><input type="submit" name="create user" title="Crear Usuario" value="Crear Usuario"></input></li>
</ul>
</form>
This is my form, some of the values are in Spanish, the website I'm supposed to make has to be in that language. If I understood things right, I should call the function I want with an "OnClick" through my submit input button. This is the first time I've done web development, and understanding CSS and HTML was difficult for me. I was wondering if someone could help me out with an example or something. I'm basically using MVC to organize this, with HTML and JavaScript as the View, PHP as the control and Oracle SQL as the model. I'm using PHP precisely for that reason, I need to connect to the database, and send the information through PHP.
I'm not looking for anyone to fix my thing or anything of the sort, all I need is an example and small explanation if possible.
You need to figure out $.ajax function. It easy to implement, and posting the values into your php file, then from there you can processing inserting data into database. Here is sample of code :
$('input[type=submit]').on('click',function(e)
{
e.preventDefault();
var my_username = $('input[name=username]').val();
.....
..... more here
$.ajax({
type : 'POST', //<--- GET or POST
url : 'url_of_insert_process.php',
data : {
username: my_username,
.....
..... more here
}
success : function(data){
// Here you can populate the view whatever you want
// like showing message success
}
});
});
That is the illustration sending the data. You also can use $("form" ).serialize(); to fetch all the form element value using the name that you provided on each html form element. So many sources out there that you can put into your table.
Please try
$(document).ready(function(){
$('input[type="submit"]').click(function(e){
e.preventDefault();
$.ajax({
url: "YOUR_URL",
type: 'POST',
data:$("form#registration").serialize(),
success: function( response ) {
console.log(response);
}
});
});
});
//jsfile.js
//THIS METHOD RETURN THE name : value PAIR FROM
//A SPECIFIED FORM ID OR FORM IN THE CURRENT SPHERE
function formHandler(formID="") {
try {
if (formID === "") {
//PICK UP THE FORM IN THE CURRENT SPHERE
formElms document.querySelectorAll("input,select,textarea");
} else if(formID !== "") {
//PICK UP THE NAMED FORM
var formsElms = document.querySelectorAll("form");
formsElms.forEach(function(formElm) {
if (formElm.id === formID) {
formElms = document.querySelectorAll("#"+formID+" input, #"+formID+" select, #"+formID+" textarea");
}
});
}
if (formElms) {
var retObjs = new Array();
if (formElms) {
formElms.forEach(function(param) {
retObjs.push({name : param.name, value: param.value});
});
}
}
return retObjs;
} catch (e) {
console.log(e);
}
}
serverSideHandler(inda={}) {
try {
indata = inda;
complUrl = "url.php";
$.ajax({
method: "POST",
url: complUrl,
data: indata
})
.done(function(retData) {
serverResponseHandler(retData);//Function To Callback
});
} catch(ev) {
console.log(ev);
}
}
//url.php
<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: text/json');
ini_set('memory_limit','1024M');
if (!empty($_POST)) {
//Extract your form Inputs as follow
$name = doSomeValidation($_POST['name']);
//Do DB connections
//Do your CRUD
//DO OTHER ACTIONS
}