Pass ID of button to a form - javascript

I found this pass id to jquery modal form but seeing as I'm not too jQuery-savvy and I don't know PhP I'm not sure how I would implement this in my example.
My goal is to be able to pass the ID of a button, upon being pressed, to a form. Something like this:
<button id="dynamic_id">
<form id="time_form" action="{% url 'event' pk='button_id' %}" method="post">
# Lots of stuff
</form>
The button_id is where I'd like the button's ID to be.
I thought of something like
function getId(button_id) {
document.getElementById('time_form').action = "{" + "%" + "url " + "event" + ' pk="' + button_id + '" %" + "}"';
}
<button id="dynamic_id" onClick="getId(this.id);">
<form id="time_form" action=""> (...)
</form>
But this does not work. I get an error message
400 Bad Request: Your browser semt a request this server cannot understand
UPDATE
I'm not trying this:
function getId(button_id) {
var vk_input = document.CreateElement("input");
vk_input.name = "vk_id";
vk_input.value = button_id;
vk_input.type = "hidden";
document.getElementById("time_form").appendChild(vk_input);
}
But it does not work for some reason. What's wrong with it?

look this:
<script>
$(document).ready(function(){
$('#dynamic_id').click(function(){
var id=$(this).attr('id');
var array_ids = [];
$('.dinamics').each(function(){
//console.log('gdfg');
array_ids.push($(this).attr('id'));
});
for(var i = 0; i < array_ids.length; i++){
$('#time_form').append('<input type="hidden" name="your_button_id_'+i+'" value="'+array_ids[i]+'"/>')
}
$('#time_form').submit();
})
})
</script>

How aboout this with jquery.
<button id="dynamic_id">
<form id="time_form" action="" method="post">
</form>
<script>
$(document).ready(function(){
$('#dynamic_id').click(function(){
var id=$(this).attr('id');
$('#time_form').append('<input type="hidden" name="your_button_id" value="'+id+'"/>')
$('#time_form').submit();
})
})
</script>

Button id passed correctly to getId() but generated string does not seems valid, here is some issue with quotes. See reduced example on jsfiddle
try this:
document.getElementById('time_form').action = "{" + "%" + "url " + "event" + ' pk="' + button_id + '" ' + "%" + "}";

i recommend you to use jquery, is better an clean.
this is what you want?
<button id="dynamic_id" class="dinamics">Lots of stuff</button>
<button id="dynamic_id_1" class="dinamics">1</button>
<button id="dynamic_id_2" class="dinamics">2</button>
<button id="dynamic_id_3" class="dinamics">3</button>
<button id="dynamic_id_4" class="dinamics">3</button>
<button id="dynamic_id_5" class="dinamics">3</button>
<button id="dynamic_id_6" class="dinamics">3</button>
<button id="dynamic_id_7" class="dinamics">3</button>
<form id="time_form" action="" method="post">
</form>
<script>
$(document).ready(function(){
$('#dynamic_id').click(function(){
var array_ids = [];
$('.dinamics').each(function(){
array_ids.push($(this).attr('id'));
});
for(var i = 0; i < array_ids.length; i++){
$('#time_form').append('<input type="hidden" name="your_button_id_'+i+'" value="'+array_ids[i]+'"/>')
}
$('#time_form').submit();
})
})
</script>

Related

JSON get data using post-method

I want to get a JSON file from another server xyz.com (not writhing here original site name for safety) for my HTML page but the problem is that the website xyz.com only supports HTTP POST requests.
To check if my HTML code is working fine I use HTTP GET method and upload JSON data on another site that supports HTTP GET request. And I found that it is working fine. But when I try for HTTP POST method it is not working. Can you help me?
I am using currently and working fine
<script>
$(function() {
var people = [];
$.get('https://api.myjson.com/bins/c307c',function(data) {
$.each(data.video, function(i, f) {
HTML CODE FOR xyz.com and it also return a .json file
<html>
<head>
<form action="https://www.xyz.php" method="POST" >
<div class="container" style="width:100%;">
<center></center>
</div>
<div class="container" style="width:100%;">
<label for="userId"><b>UserId</b></label>
<input type="number" placeholder="Enter Your User Id" name="userId" autofocus required>
<label for="Passkey"><b>Passkey</b></label>
<input type="number" placeholder="Enter Passkey" name="Passkey" required>
<button type="submit" >GET Json File From Server</button>
</div>
</form>
This is i tried but not working
<script>
$(function() {
var people = [];
$.post('https://xyz.php', usedId=5&passkey=55, function(data) {
$.each(data.video, function(i, f) {
Try this way code
$.post( "https://xyz.php", { usedId: 5, passkey: 55},
function(data) {
//your code
} );
Please make necessery change so that when i click on button it take data from server and show in a table format
<html>
<head>
<form action="https://xyz.php" method="POST" >
<div class="container" style="width:100%;">
<center></center>
</div>
<div class="container" style="width:100%;">
<label for="userId"><b>UserId</b></label>
<input type="number" placeholder="Enter Your User Id" name="userId" autofocus required>
<label for="passKey"><b>Passkey</b></label>
<input type="number" placeholder="Enter Passkey" name="passKey" required>
<button type="submit" >GET DATA</button>
</div>
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
<script>
$(function() {
var people = [];
$.post( "xyz.php",function(data) {
$.each(data.video, function(i, f) {
var link = "https://www.youtube.com/embed/"+ f.video;
var tblRows = "<tr>" +
"<td>" + f.videoName + "</td>" + "<td>" + f.date + "</td>" + "<td>" + f.time + "</td>" +
"<td>" + f.videoDuration + "</td>" + "<td>" + f.liveStatus + "</td>" + "<td><a target='_blank' href='"+link+"'>"+link+"</a></td>" + "</tr>";
$(tblRows).appendTo("#userdata tbody");
});
});
});
</script>
</head>
<body>
<div class="wrapper">
<div class="profile">
<table id= "userdata" width="50%" border="2">
<thead>
<th>VIDEO NAME</th>
<th>DATE</th>
<th>TIME</th>
<th>DURACTION</th>
<th>LIVE STATUS</th>
<th>LINK</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</html>
Some changes I suggest:
Give the form an ID, in this case login seems like an appropriate ID
Standardize your capitalization for form fields
Here's some code to get you started. You'll notice I'm creating your data twice. Decide if you want to build your data by hand or use jQuery's serialization to do it for you. Since this is a simple form, the latter is probably fine.
I'm also getting the AJAX endpoint right from the form so you aren't repeating yourself there.
// when the document has loaded...
$(document).ready(function () {
// if the user is already logging in
var login = false;
// when the form is submitted...
$('#login').on('submit', function (event) {
// block the form if it's already been submitted
if (login) {
event.stopPropagation();
event.preventDefault();
return;
}
// lock the form
login = true;
// get a handle on the form
// I use $ as a prefix to differentiate jQuery objects
// currentTarget is the subject of the event
var $form = $(event.currentTarget);
var url = $form.prop('action');
/*
* MANUAL
*/
// form fields are added to the form object as properties by name attribute
// note that they are not jQuery objects
var data = {
userId: $form.userId.value,
passKey: $form.passKey.value
};
/*
* AUTOMATIC
*/
// uses jQuery's form serialization to automatically create an object mapping names to values
var data = $form.serialize();
$.post(url, data)
// on success
.done(function (data, status, request) {
$.each(data.video, function (i, f) {
var link = "https://www.youtube.com/embed/"+ f.video;
// backslash at the end of a string means to continue the string on the next line
var $row = $('<tr>\
<td>' + f.videoName + '</td>\
<td>' + f.date + '</td>\
<td>' + f.time + '</td>\
<td>' + f.liveStatus + '</td>\
<td><a target="_blank" href="' + link + '">' + link + '</a></td>\
</tr>');
$row.appendTo('#userdata tbody');
})
// on failure
.fail(function (request, status, error) {
window.alert('Failed with a status of ' + status + ': ' + error);
})
// executes after either of the above
// parameters are inconsistent and use either done's or fail's
.always(function () {
// do cleanup, i.e. unlock form submission, close modal dialogs, etc.
login = false
});
// stop default form submission
event.stopPropagation();
event.preventDefault();
});
});

HTML Page being cleared after run

Here I am practicing using jQuery with my html. I have a form that is asking questions about your car. The problem is everything works but after it does the form reset it deletes everything that was just added.
I debugged the program and it is doing exactly what I want but once it stops executing "writeHtml" everything it just did gets cleared.
<!DOCTYPE HTML>
<html>
<head>
<title> Sabio Practice </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
function writeHtml(){
var model = $("#Model").val();
var make = $("#Make").val();
var year = $("#Year").val();
var vin = $("#VIN").val();
$("#pp").html("<ul>")
$("#pp").html("<li>Make: " + make + "</li>" +
"<br/><li>Model: " + model + "</li>" +
"<br/><li>Year: " + year + "</li>" +
"<br/><li>VIN: " + vin + "</li>");
$("#pp").html("</ul>")
}
console.log("got here");
$("#Register").click(function(){
writeHtml();
$("#myForm")[0].reset();
});
});
</script>
</head>
<body>
<div>
<form id = "myForm" method = "get">
<input id = "Model" placeholder = "Model"><br>
<input id = "Make" placeholder = "Make"><br>
<input id = "Year" type = "number" placeholder = "Year"><br>
<input id = "VIN" placeholder = "VIN"><br>
<button id = "Register" name = "Register"> Register</button>
<button id = "Cancel" name = "Cancel">Cancel</button>
</form>
<p id = "pp">
</p>
</div>
</body>
</html>
I just want the edits made to the DOM to be permanent.
You override with html() your content, better is to use append()
$("#pp").append("<ul>")
$("#pp").append("<li>Make: " + make + "</li>" +
"<br/><li>Model: " + model + "</li>" +
"<br/><li>Year: " + year + "</li>" +
"<br/><li>VIN: " + vin + "</li>");
$("#pp").append("</ul>")
And set the type of your button to button. Otherwise the form is submitted.
<button type="button"></button>
You should also prevent the default behavior, your event subscription should look like this:
$("#Register").click(function(e) {
e.preventDefault();
writeHtml();
$("#myForm")[0].reset();
});
when you don't set the type in a form, it's a submit;
so you should set the button type button;like this:
<button id = "Register" name = "Register" type="button"> Register</button>
So I had two problems. One was I was overwriting my innerhtml again after I overwrote it the first time.
The second problem was I did not specify a type for the button. The default type for button is "submit" since my form was therefore being submitted it was redirecting me to a fresh page of my page.
<!DOCTYPE HTML>
<html>
<head>
<title> Sabio Practice </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
function writeHtml(){
var model = $("#Model").val();
var make = $("#Make").val();
var year = $("#Year").val();
var vin = $("#VIN").val();
var htmlText = "<ul>";
htmlText += `<li>Make: ${make}</li>
<br/>
<li>Model: ${model}</li>
<br/>
<li>Year: ${year}</li>
<br/>
<li>VIN: ${vin}</li>`;
htmlText += "</ul>"
$("#pp").append(htmlText);
}
console.log("got here");
$("#Register").click(function(e){
e.preventDefault();
writeHtml();
$("#myForm")[0].reset();
});
});
</script>
</head>
<body>
<div>
<form id = "myForm" >
<input id = "Model" placeholder = "Model"><br>
<input id = "Make" placeholder = "Make"><br>
<input id = "Year" type = "number" placeholder = "Year"><br>
<input id = "VIN" placeholder = "VIN"><br>
<button id = "Register" name = "Register"> Register</button>
<button id = "Cancel" name = "Cancel">Cancel</button>
</form>
<p id = "pp">
</p>
</div>
</body>
</html>

Can't pass list items as session variables in php

I have an order page. I choose an item then add to the order list with javascript. The list can contain many items. I want to pass these items as session variables into the order confirmation page.
Here is what I did;
This is javascript code to add items to the orderlist, there is no problem in that part. I append the selected item when button clicked.
$('#addToCartButton').click(function(){
var toAdd=$("#chooseItem option:selected").text();
var itemNbr1=$("#itemNbr1").val();
var cupSize=$("#cupSize option:selected").text();
var milkType=$("#milkType option:selected").text();
var cafein="";
if ($("#cafein").is(':checked')==true){
var cafein="Kafeinsiz";
};
if(toAdd !== defaultSelectFormText && itemNbr1 >=1){
$('#defaultText').remove();
$('.orderList').append('<p id="items">' + itemNbr1 + ' Adet ' + cafein + ' ' + cupSize + ' ' + milkType + ' ' + toAdd + '<span class="extra">Sipariş listesinden çıkarmak için tıklayın!</span>' + '</p>');
};
});
This is html part, when I push the firstConfirmButton it works, no problem. But in the php part I can't pass the items as session variables.
<form method="post" action="">
<div class="col-md-5">
<h3 align="center">Sipariş Listesi</h3>
<ul class="orderList" name="orderList"></ul>
</div>
</form>
<form role="form" method="post" action="">
<div id="firstConfirmButton">
<button type="submit" name="firstConfirmButton" class="btn btn- primary btn-lg">Onayla</button>
</div>
</form>
This is php part, I saw "I'm here" . $_SESSION['FirstName'] part but $_SESSION['OrderList'] don't work;
<?php
require("includes/db.php");
require("includes/functions.php");
session_start();
if (isset($_POST['firstConfirmButton'])) {
$_SESSION['OrderList'] = $_POST['orderList'];
echo "I'm here" . $_SESSION['FirstName'] . $_SESSION['OrderList'];
}
?>
What is the problem, I stuck in that point.

How do pass the id of a form onKeyUp?

There's plenty of questions on how to get the value onKeyUp, but I want to pass the id of the form onKeyUp as well.. I tried something like this, but it's telling me getId is not defined.
function getId(x){
$('.not').append(x);
}
var word = 'HELP';
$('.why').html("<form class='questions'><input type='text' id='"+word+"'
name='"+word+"' onkeyup='getId("+word+")'></form> ");
http://jsfiddle.net/evs3A/
Also is putting something like "+variable+" bad practice, because I'm using it quite a lot ;)? Thank u.
Use jQuery to hook up the event and avoid the problem altogether. Try this:
var word = 'HELP';
$('.why').html("<form class='questions'><input type='text' id='" + word + "'
name='" + word + "'></form> ");
$('.questions input').on('keyup', function(e) {
$('.not').append(this.id);
});
Example fiddle
you can change it into this:
$('.why').html("<form class='questions'><input type='text' id='"+word+"'
name='"+word+"'></form> ");
and in jquery:
$(document).ready(function(){
var word = 'HELP';
$(document).on('keyup', '#' + word, function(){
$('.not').append(word); //or $(this).attr('id'); if the id is the argument that you want to pass
});
});
if you want to change a variable to pass you can use data value like this:
<input type='text' id='"+word+"' name='"+word+"' data-something="new_value">
and take it in this mode:
$(document).on('keyup', '#' + word, function(){
$('.not').append(word);
var value = $(this).data('something');
});
Here's a sample without any jQuery.
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
window.addEventListener('load', mInit, false);
function mInit()
{
byId('myFormId').addEventListener('keyup', onFormKeyUp, false);
byId('myFormId2').addEventListener('keyup', onFormKeyUp, false);
}
// this function was attached to the form in the mInit function.
// as a consequence, 'this' reffers to the form itself.
// this.id should give us the id of the form
function onFormKeyUp(e)
{
alert("Keyup detected in the form with the id: '" + this.id + "'");
}
</script>
<style>
</style>
</head>
<body>
<form id='myFormId'>
<input id='textField1'/>
<br>
<button>Some button</button>
</form>
<form id='myFormId2'>
<input id='textField2'/>
<br>
<button>Some button</button>
</form>
</body>
</html>

JQuery Variable Script

I have the code:
<script type="text/javascript" charset="utf-8">
var hash = "fifa";
$(document).ready(function() {
console.log("I am ready");
$('#trigger_but').click(function() {
console.log("Click Performed");
$.getJSON("http://search.twitter.com/search.json?rpp=100&callback=?&q=%23" + $('#hash_tag_input').val(), function(data) {
for (var i = 0; i < data.results.length; i++) {
$('#result').prepend('<div class="tweet"><img src="' + data.results[i].profile_image_url
+ '" width="50" height="60"/><span id="tweetText">' + data.results[i].text + '</span></div>');
}
});
});
});
</script>
</head>
<body>
<input type="text" id="hash_tag_input" size="40"/>
<input type="button" id="trigger_but" value="Fetch Tweets"/>
<div id="result"></div>
</body>
How would I make it so that I can use the variable hash, instead of the inputted contents of hash_tag_input as the search term. And make it so that it fetches the tweets automatically without the click of a button.
For part 1, replace $('#hash_tag_input').val() with hash.
For part 2, just put the getJSON call directly in $(document).ready, like this:
var hash = "fifa";
$(document).ready(function(){
$.getJSON("http://search.twitter.com/search.json?rpp=100&callback=?&q=%23"+hash,function(data){
for(var i=0;i<data.results.length;i++){
$('#result').prepend('<div class="tweet"><img src="'+data.results[i].profile_image_url + '" width="50" height="60"/><span id="tweetText">'+data.results[i].text+'</span></div>');
}
});
});

Categories

Resources