Submit form refresh the page - javascript

I have an index.html
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>League of Legends Straw Poll</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="css/styles.css" />
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h1 class="text-center">Game Straw Poll</h1>
</div>
</div>
<br>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-default">
<div class="panel-body">
<!-- FORM -->
<form name="submitForm" id="submitForm" action="process.php" method="post">
<div class="row">
<div class="col-md-12">
<!-- GAME -->
<select class="form-control" id="game-group" name="game" onchange="ChangeBackground();">
<option selected disabled>Select your Game...</option>
<option value="League_of_Legends">League of Legends</option>
<option value="Heartstone">Hearthstone</option>
</select>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12">
<!-- QUESTION -->
<div class="input-group" id="question-group">
<input type="text" class="form-control" name="question" id="question" placeholder="Start typing your question...">
<span class="input-group-addon">
<i class="glyphicon glyphicon-question-sign"></i>
</span>
</div>
</div>
</div>
<br>
<div class="row">
<!-- OPTIONS -->
<div class="form-group form-group-options col-md-12 col-sm-12 col-xs-12">
<div class="input-group input-group-option col-md-12 col-sm-12 col-xs-12" id="options-group">
<input type="text" name="option[]" id="option" class="form-control" placeholder="Options...">
<span class="input-group-addon input-group-addon-remove">
<span class="glyphicon glyphicon-remove"></span>
</span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<!-- CHOICE -->
<div class="checkbox" id="choice-group">
<label>
<input type="checkbox" id="choice" name="choice" value="Yes">Allow multiple choice
</label>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<button type="submit" class="btn btn-primary btn-lg pull-left" name="submit_button" id="submit_button" data-toggle="modal" data-target="#myModal">Create Poll</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Poll created</h4>
</div>
<div class="modal-body">
<p>Share it: http://gamepoll.net/<?php echo $rand_value; ?></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Chiudi</button>
<button type="button" class="btn btn-primary">Invia</button>
</div>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
<script type='text/javascript' src='js/addfield.js'></script>
<script type='text/javascript' src='js/changebackground.js'></script>
<script type='text/javascript' src='magic.js'></script>
</body>
</html>
An AJAX function into a js script
// magic.js
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
$('.form-group').removeClass('has-error'); // remove the error class
$('.help-block').remove(); // remove the error text
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'game' : $('input[name=game]').val(),
'question' : $('input[name=question]').val(),
'option' : $('input[name=option[]]').val(),
'choice' : $('input[name=choice]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
if ( ! data.success) {
// handle errors for game ---------------
if (data.errors.game) {
$('#game-group').addClass('has-error'); // add the error class to show red input
$('#game-group').append('<div class="help-block">' + data.errors.game + '</div>'); // add the actual error message under our input
}
// handle errors for question ---------------
if (data.errors.question) {
$('#question-group').addClass('has-error'); // add the error class to show red input
$('#question-group').append('<div class="help-block">' + data.errors.question + '</div>'); // add the actual error message under our input
}
// handle errors for option ---------------
if (data.errors.option) {
$('#option-group').addClass('has-error'); // add the error class to show red input
$('#option-group').append('<div class="help-block">' + data.errors.option + '</div>'); // add the actual error message under our input
}
// handle errors for choice ---------------
if (data.errors.choice) {
$('#choice-group').addClass('has-error'); // add the error class to show red input
$('#choice-group').append('<div class="help-block">' + data.errors.choice + '</div>'); // add the actual error message under our input
}
} else {
// ALL GOOD! just show the success message!
$('form').append('<div class="alert alert-success">' + data.message + '</div>');
// usually after form submission, you'll want to redirect
// window.location = '/thank-you'; // redirect a user to another page
}
})
// using the fail promise callback
.fail(function(data) {
// show any errors
// best to remove for production
console.log(data);
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
And a process.php
<?php
//Include configuration file
include('includes/config.php');
//Define variables
$question=$_POST['question'];
$game=$_POST['game'];
$option=$_POST['option'];
$choice=$_POST['choice'];
//Generate random number
$rand_value=rand();
//Create temporary folder
mkdir($rand_value);
//Copy page of Ask Poll
copy('page.php', $rand_value . '/page.php');
rename($rand_value . '/page.php', $rand_value . '/index.php');
//Add data into database
mysql_connect($db_host, $db_username, $db_password) or die ("Errore di connessione!");
mysql_select_db($db_name) or die ("Impossibile selezionare database!");
$sql1="CREATE TABLE `" . $rand_value . "` (Question VARCHAR(200), Options VARCHAR(200), Choice INT(11))";
mysql_query($sql1) or die ("Impossibile eseguire la query!");
//Count number of Options available
$count=count($option);
for ($i=0; $i<($count-1); $i++)
{
${$sql . $i}="INSERT INTO `" . $rand_value . "` (Question, Options, Choice) VALUES ('$question', '$option[$i]', '$choice')";
mysql_query(${$sql . $i});
}
?>
But when i send the form, the page redirect me to process.php
I don't want that the site refresh the page
EDIT
Werner, I followed your suggestion adding preventDefault but it doesn't work :(

You have an syntax error in your magic.js file. You should start by enabling your console and watch it for errors.
Uncaught Error: Syntax error, unrecognised expression: input[name=option[]]
That is what I could read when pressing the submit button and then Escape just after that to stop the submit.
The problem lies the part where you create your formData. (Which you can actually create a lot easier with http://api.jquery.com/serialize/)
You have a typo on line 15. Notice the extra brackets? You are not supposed to add the brackets even though they are in the name of the field. I recommend you to use the Serialize solution or at least select the fields using their IDs (that's what they are basically for).
$('input[name=option[]]') // Not valid
$('#option') // Better way to select a field
Hope this will get you in the right direction.

Related

Laravel 7 dynamic "add fields" form. foreach() argument must be of type array|object, null given

This my first post here, but by no mean my first time visiting. I'm an amateur coder and I'm working on something that has stumped me for passed day or two...
I'm building a site using Laravel 7. One of the pages includes a dynamic form that allows the user to add addition for fields as needed.
I'm am generating the dynamic form fields and a tinymce editor as well as submitting the form using javascript.
The issue I'm running into is this:
Upon clicking the 'Submit' button the page does not transition or show any signs of having been submitted. The first portion of the form data is successfully submitted and added to the appropriate database table but the dynamic fields are not added to their table and an error is thrown in the browser console.
The believe the relevant issue is message "foreach() argument must be of type array|object, string given" as this seems to be where the code stops running and things go wrong.
This function applies to the dynamic image_id[] portion of the form.
The full error info is:
XHR POST https://www.mydomainname.com/create
[HTTP/1.1 500 Internal Server Error 479ms]
Request:
format "galleries"
title "This+is+the+title+of+the+content"
short "This+is+the+short+description+for+the+content."
thumb "https://www.mydomainname.com/storage/giraffe1.jpg"
category "funny"
image_id […]
0 "Image+1"
1 "Image+2"
2 "Image+3"
Response:
message "foreach() argument must be of type array|object, string given"
exception "ErrorException"
file "/home/user/site/app/Http/Controllers/ContentController.php"
line 149
trace [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
Line 149:
foreach($request->input('image_id[]') as $key => $image) {
This is my Blade View, including the Javascript:
#extends('layouts.app')
#section('title', 'Post New Content')
#section('content')
<script src="https://cdn.tiny.cloud/1/arx09ivbx1ikchqgcvc6558h9sx2crokpd2c1152g667mh0c/tinymce/6/tinymce.min.js"></script>
<script src="/vendor/laravel-filemanager/js/stand-alone-button.js"></script>
<div class="container">
<div class="row">
<div class="col-md-8">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
<div class="alert alert-danger print-error-msg" style="display:none">
<ul></ul>
</div>
<div class="alert alert-success print-success-msg" style="display:none">
<ul></ul>
</div>
<div class="card shadow">
<h2 class="card-header">
Post a New Gallery
<a class="btn btn-danger" style="float: right" href="{{ url()->previous() }}" onclick="return confirm('Are you sure? All progress will be lost!')">Go Back</a>
</h2>
<div class="card-body">
<form name="add_name" id="add_name">
<input type="hidden" name="format" value="galleries" class="form-control" required>
<div class="form-group row mb-0">
<div class="col-md-12">
<strong>Title:</strong>
<input type="text" name="title" class="form-control" required>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-12">
<strong>Description:</strong>
<input type="text" name="short" class="form-control" required>
</div>
</div>
<div class="col-md-12">
<div class="row">
<div class="col-md-6">
<strong>Thumbnail:</strong>
<div class="input-group">
<div class="col-md-10">
<input type="text" id="thumb" class="form-control" name="thumb" aria-label="thumb" aria-describedby="button-image" required>
</div>
<div class="col-md-2">
<div class="input-group-append">
<button class="btn btn-primary" type="button" id="button-image">Browse</button>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<strong>Category: </strong>
<select name="category" class="form-control" required>
<option value="" disabled selected>Select content category...</option>
#foreach($allCategories as $category)
<option value="{{ $category->name }}">{{ ucfirst(trans($category->name)) }}</option>
#endforeach
</select>
</div>
</div>
</div>
<br>
<!-- Dynamic Fields -->
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><input type="text" name="image_id[]" class="form-control name_list" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</table>
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
<!-- End Dynamic Fields -->
</form>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
var postURL = "<?php echo url('create'); ?>";
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'" class="dynamic-added">' +
'<td><input type="text" name="image_id[]" class="form-control name_list" /></td>' +
'<td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td>' +
'</tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#submit').click(function(){
$.ajax({
url:postURL,
method:"POST",
data:$('#add_name').serialize(),
type:'json',
success:function(data)
{
if(data.error){
printErrorMsg(data.error);
}else{
i=1;
$('.dynamic-added').remove();
$('#add_name')[0].reset();
$(".print-success-msg").find("ul").html('');
$(".print-success-msg").css('display','block');
$(".print-error-msg").css('display','none');
$(".print-success-msg").find("ul").append('<li>Record Inserted Successfully.</li>');
}
}
});
});
function printErrorMsg (msg) {
$(".print-error-msg").find("ul").html('');
$(".print-error-msg").css('display','block');
$(".print-success-msg").css('display','none');
$.each( msg, function( key, value ) {
$(".print-error-msg").find("ul").append('<li>'+value+'</li>');
});
}
});
</script>
<script>
document.addEventListener("DOMContentLoaded", function() {
document.getElementById('button-image').addEventListener('click', (event) => {
event.preventDefault();
window.open('/file-manager/fm-button', 'fm', 'width=1400,height=800');
});
});
// set file link
function fmSetLink($url) {
document.getElementById('thumb').value = $url;
}
</script>
#endsection
And here is my Controller:
public function createPost(Request $request)
{
$post = new Content();
$post->title = $request->get('title');
$post->short = $request->get('short');
$post->long = $request->get('long');
$post->thumb = $request->get('thumb');
$post->format = $request->get('format');
$post->category = $request->get('category');
$post->author = Auth::user()->id;
$post->save();
$order = 0;
foreach($request->input('image_id[]') as $key => $content) {
$contentImg = new ContentImages();
$contentImg->content_id = $post->id;
$contentImg->image_id = $content->image_id;
$contentImg->image_order = $order+1;
$contentImg->save();
}
return response()->json(['success'=>'done']);
}
And, finally, my Routes:
Route::get("create","ContentController#create");
Route::post("create","ContentController#createPost");
Things I Have Tried
I've tried several variations of the image_id syntax and nothing seems to be working...
As posted above:
foreach() argument must be of type array|object, null given
Using $request->input('image_id'):
"Attempt to read property \"image_id\" on string"
I tried $request('image_id') and got:
Object of type Illuminate\Http\Request is not callable
Then I tried $request->input(['image_id']) which just gave
foreach() argument must be of type array|object, null given
The output from dd($request->input('image_id') is:
array:2 [
0 => "Name 1"
1 => "Name 2"
]
and dd($request->input('image_id[]')) gave null.
Output of dd($request->all()):
array:6 [
"format" => "galleries"
"title" => "Thoughtless Driver Ruins Everyone's Day at the Wildlife Park"
"short" => "This lady made a mess at the West Midland Safari Park. The Giraffe was not injured."
"thumb" => "https://www.mydomainname.com/storage/photos/1/6317a2b460c98.jpg"
"category" => "oops"
"image_id" => array:3 [
0 => "Name 1"
1 => "Name 2"
2 => "Name 3"
]
]
I'm really lost on this one.
Any guidance here would be GREATLY appreciated, as well as any recommendations on better ways to handle this scenario.
I'm a marginally talented amateur with this stuff but nowhere near expert and I'm always looking to learn.
Much thanks in advance!!
SMR
Okay, so I figured out what I was doing wrong.
$request->input('image_id') was the correct solution.
My issue was further down. Once I corrected to $request->input('image_id'), this lead to another error, "Attempt to read property \"image_id\" on string", but this was actually due to a syntax error further down the page.
Fixed that, and all is now well!
Thank you to those who helped!

How do I insert Data Into database with many Input which has same name?

hello friends I have a form field in which I want to insert data which has four field which are customer_id , field_name1 ,field_name2, field_name3 ,
The question is I want to insert data which has many inputs but same input name like field_name1 field_name2 field_name3 , firstly there is no input but when I click on a button add partner details then these inputs shows by javascript .
like field_name1,field_name2,field_name3 ten times can repeat , I want to insert data in database according to there numbers with same customer_id , but different field name , below is my code , hope you understand it .
here is my code
<?php
$conn=mysqli_connect("localhost","root","","satya");
if(isset($_POST['submit'])){
$customer_id=$_POST['customer_id'];
for ($ix=0; $ix<count($_POST['field_name1']); $ix++)
{
$field_data = array(
'field_name1' => $_POST['field_name1'][$ix],
'field_name2' => $_POST['field_name2'][$ix],
'field_name3' => $_POST['field_name3'][$ix],
);
$sql="INSERT INTO customer(customer_id,details1,details2,details3) VALUES('$customer_id','$field_name1','$field_name1','$field_name1')";
$result=mysqli_query($conn,$sql);
if($result){
echo "data has been inserted";
}
else{
echo "data could not be inserted";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<form action="" method="post">
<div class="form-group">
<div class="row" style="margin-top: 20px">
<div class="col-md-4" ></div>
<div class="col-md-4">
<label for="customer_id">Customer ID </label>
<input type="text" class="form-control" name="customer_id" placeholder="customer_id">
</div>
<div class="col-md-4"></div>
</div>
<div class="row" style="margin-top: 20px;">
<div class="col-md-3">
<label for="details1">details1 </label>
</div>
<div class="col-md-3">
<label for="details2">details2</label>
</div>
<div class="col-md-3">
<label for="details3">details3</label>
</div>
<div class="col-md-3">
<div>
Add Partner Details
</div>
</div>
<div class="partner_wrapper" >
</div>
</div>
<div class="col-md-4"></div>
<div class="col-md-4">
<button type="submit" class="btn btn-primary" name="submit">Submit</button>
</div>
<div class="col-md-4"></div>
</form>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>
<script>
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_partner'); //Add button selector
var wrapper = $('.partner_wrapper'); //Input field wrapper
var fieldHTML = '<span class="row"><div class="col-md-3"><input type="text" class="form-control" name="field_name1[]" value=""/></div><div class="col-md-3"><input type="text" class="form-control" name="field_name2[]" value=""/></div><div class="col-md-3"><input type="text" class="form-control" name="field_name3[]" value=""/></div><button type="button" href="javascript:void(0);" class="remove_button btn btn-primary" title="Remove field">Remove</button></span>'; //New input field html
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
}
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('span').remove(); //Remove field html
x--; //Decrement field counter
});
});
</script>
Give the repeating fields array-style names:
<input type="text" name="field_name1[]">
PHP will collect the inputs into arrays, so $_POST['field_name1'] will be an array. Then you can loop over them:
foreach ($_POST['field_name1'] AS $index => $field1) {
$field2 = $_POST['field_name2'][$index];
$field3 = $_POST['field_name3'][$index];
// now you can insert all these values into the DB
}

HTML not processing correctly

We are working on a dApp that is giving us problems. The site loads OK and the button to open the subform ("Post My Rental") works. When I fill out the subform and click the 'submit' button, nothing happens. I have confirmed that I am connected to Metamask and Ganache, but no transaction goes through. Checking inspect in Chrome, no errors there. I suspect there is something missing in this code, but I can't find it. If you could help out, we would really appreciate it. Here is the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Rent My Place</title>
<!-- Title will appear as a tab in browser on webpage -->
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- Application -->
<link href="css/app.css" rel="stylesheet">
<!-- stylesheet refers to the look of the page, Font, color-->
</head>
<body>
<div class="container">
<!-- container that contains title panel-->
<div class="jumbotron text-center">
<p style="font-size:80px;padding: 1em;padding-top: 10px;padding-bottom: 10px; border:10px;border-style:solid;border-color:#c3c3c3;">
<font color = "#880015" >Rent My Place</font></p>
</div>
<div class="col-md-12" id="article-list">
<div class="row">
<div class="col-lg-12">
<!--<p id="account" class="welcome pull-right"></p>
<p id="accountBalance" class="welcome pull-left"></p>-->
</div>
</div>
<div class="row panel panel-default">
<div class="panel-heading clearfix">
<div class="panel-title">
<p style="font-size:24px;padding: 1em;padding-top: 10px;padding-bottom: 10px; border:5px;border-style:solid;border-color:#c3c3c3;">
<font color = "#880015">Renter's Tip: </font><font color = "#000000">Inspect the property before you send money.</font><br><font color = "#880015">Landlord's Tip: </font><font color = "#000000">Meet prospective tenants in person.</font></p>
<!-- Button that opens second window to a form to fill out-->
<button class="btn btn-info btn-lg pull-right" data-toggle="modal" data-target="#sellArticle">Post a Rental</button>
</div>
</div>
<!-- when the event button gets click, it will show the list-->
<ul id="events" class="collapse list-group"></ul>
</div>
<div id="articlesRow" class="row">
<!-- ARTICLES with pertinent item information LOAD HERE -->
</div>
</div>
</div>
<!--Result that is displayed after input-->
<div id="articleTemplate" style="display: none;">
<div class="row-lg-12">
<div class="panel panel-default panel-article">
<div class="panel-heading">
<h3 class="panel-title"></h3>
</div>
<div class="panel-body">
<strong>Beds</strong>: <span class="beds"></span><br/>
<strong>Baths</strong>: <span class="baths"></span><br/>
<strong>Address</strong>: <span class="propaddress"></span><br/>
<strong>Rental Price</strong>: <span class="rental_price"></span><br/>
<strong>Description</strong>: <span class="article_description"></span><br/>
<strong>Property is available for showing</strong>: <span class="available"></span><br/>
<strong>Contact Email</strong>: <span class="contact_email"></span><br/>
<!--<strong>Sold by</strong>: <span class="article-seller"></span><br/>-->
</div>
<div class="panel-footer">
<button type="button" class= "btn btn-primary btn-success btn-buy" onclick="App.buyArticle(); return false;">Buy</button>
</div>
</div>
</div>
</div>
<!-- Modal form to sell an article -->
<div class="modal fade" id="sellArticle" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Rent Your Place</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-lg-12">
<form>
<div class="form-group">
<!--NOTE: For radio buttons to work, 'name' field must match-->
<label for="property_type">Property Type</label>
<input type="radio" name="property" id="property_type" value="house" > House
<input type="radio" name="property" id="property_type" value="apartment" > Apartment
<input type="radio" name="property" id="property_type" value="duplex" > Duplex
</div>
<div class="form-group">
<label for="propaddress">Address</label>
<input type="text" class="form-control" id="propaddress" placeholder="Enter the address">
</div>
<div class="form-group">
<label for="beds">Beds</label>
<input type="radio" name="beds" id="beds" value="0"> Studio
<input type="radio" name="beds" id="beds" value="1"> One
<input type="radio" name="beds" id="beds" value="2"> Two
<input type="radio" name="beds" id="beds" value="3"> Three +
</div>
<div class="form-group">
<label for="baths">Baths</label>
<input type="radio" name="baths" id="baths" value="1"> One
<input type="radio" name="baths" id="baths" value="2"> Two
<input type="radio" name="baths" id="baths" value="3"> Three +
</div>
<div class="form-group">
<label for="rental_price">Rent (in USD)</label>
<input type="text" class="form-control" id="rental_price" placeholder="$" pattern="[0-9]+([\.,][0-9]+)?">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea type="text" class="form-control vresize" id="article_description" placeholder="Describe your property" maxlength="255"></textarea>
</div>
<div class="form-group">
<label for="available"></label>
<input type="checkbox" name="available" value="available" id="available"> Property is available for showing
</div>
<div class="form-group">
<label for="contact_email">Contact Email</label>
<input type="text" class="form-control" id="contact_email" placeholder="Enter your contact email">
</div>
</form>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary btn-success" data-dismiss="modal" onclick="App.sellArticle(); return false;">Submit</button>
<button type="button" class="btn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div id="footer" class="container">
<nav class="navbar navbar-default navbar-fixed-bottom">
<div class="navbar-inner navbar-content-center text-center">
<p class="text-muted" credit>AXbean - © 2018</a></p>
</div>
</nav>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/OurRentalManualInputDataInitWeb3appMay22.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/web3.min.js"></script>
<script src="js/truffle-contract.js"></script>
</body>
</html>
Here is the app.js that is called:
App = {
web3Provider: null,
contracts: {},
account: 0x0,
loading: false,
init: function() {
return App.initWeb3();
},
initWeb3: function() {
// initialize web3
if(typeof web3 !== 'undefined') {
//reuse the provider of the Web3 object injected by Metamask
App.web3Provider = web3.currentProvider;
} else {
//create a new provider and plug it directly into our local node
App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
}
web3 = new Web3(App.web3Provider);
App.displayAccountInfo();
return App.initContract();
},
displayAccountInfo: function() {
web3.eth.getCoinbase(function(err, account) {
if(err === null) {
App.account = account;
$('#account').text(account);
web3.eth.getBalance(account, function(err, balance) {
if(err === null) {
$('#accountBalance').text(web3.fromWei(balance, "ether") + " ETH");
}
})
}
});
},
initContract: function() {
$.getJSON('OurRentalTestFromClassMay24.json', function(chainListArtifact) {
//added May24 to json file name
// get the contract artifact file and use it to instantiate a truffle contract abstraction
App.contracts.OurRentalTestFromClassMay24 = TruffleContract(chainListArtifact);
// set the provider for our contracts
App.contracts.OurRentalTestFromClassMay24.setProvider(App.web3Provider);
// listen to events
App.listenToEvents();
// retrieve the article from the contract
return App.reloadArticles();
});
},
reloadArticles: function() {
//avoid reentry bugs
if(App.loading){
return;
}
App.loading = true;
// refresh account information because the balance might have changed
App.displayAccountInfo();
var chainListInstance;
App.contracts.OurRentalTestFromClassMay24.deployed().then(function(instance) {
chainListInstance = instance;
return chainListInstance.getArticlesForSale();
}).then(function(articlesIds) {
// retrieve the article placeholder and clear it
$('#articlesRow').empty();
for(var i = 0; i < articlesIds.length; i++){
var articleId = articlesIds[i];
chainListInstance.articles(articleId.toNumber()).then(function(article){
App.displayArticle(article[0], article[1], article[3], article[4], article[5]);
});
}
App.loading = false;
}).catch(function(err) {
console.error(err.message);
App.loading = false;
});
},
displayArticle: function(id, seller, beds, baths, propaddress, rental_price, description, available, contact_email){
var articlesRow = $('#articlesRow');
var etherPrice = web3.fromWei(price, "ether");
var articleTemplate = $("#articleTemplate");
//articleTemplate.find('.panel-title').text(name);
articleTemplate.find('.beds').text(beds);
articleTemplate.find('.baths').text(baths);
articleTemplate.find('.propaddress').text(propaddress);
articleTemplate.find('.rental_price').text(rental_price);
articleTemplate.find('.description').text(description);
articleTemplate.find('.available').text(available);
articleTemplate.find('.contact_email').text(contact_email);
// articleTemplate.find('.article_price').text(etherPrice + " ETH");
articleTemplate.find('.btn-buy').attr('data-id', id);
articleTemplate.find('.btn-buy').attr('data-value', etherPrice);
//seller
if(seller == App.account){
articleTemplate.find('.article-seller').text("You");
articleTemplate.find('.btn-buy').hide();
}else{
articleTemplate.find('.article-seller').text(seller);
articleTemplate.find('.btn-buy').show();
}
//add this new article
articlesRow.append(articleTemplate.html());
},
sellArticle: function() {
// retrieve the detail of the article
// var _article_name = $('#article_name').val();
var _description = $('#description').val();
var _beds = $('#beds').val();
var _baths = $('#baths').val();
var _propaddress = $('#propaddress').val();
var _rental_price = $('#rental_price').val();
var _property_type = $('#property_type').val();
var _available = $('#available').val();
var _contact_email = $('#contact_email').val();
// var _article_price = $('#article_price').val();
// var _price = web3.toWei(parseFloat($('#article_price').val() || 0), "ether");
//if((_article_name.trim() == '') || (_price == 0)) {
// nothing to sell
// return false;
// }
App.contracts.OurRentalTestFromClassMay24.deployed().then(function(instance) {
return instance.sellArticle(_description, _beds, _baths, _propaddress, _rental_price, _property_type, _available, _contact_email, {
from: App.account,
gas: 500000
});
}).then(function(result) {
}).catch(function(err) {
console.error(err);
});
},
// listen to events triggered by the contract
listenToEvents: function() {
App.contracts.OurRentalTestFromClassMay24.deployed().then(function(instance) {
instance.LogSellArticle({}, {}).watch(function(error, event) {
if (!error) {
$("#events").append('<li class="list-group-item">' + event.args._name + ' is now for sale</li>');
} else {
console.error(error);
}
App.reloadArticles();
});
instance.LogBuyArticle({}, {}).watch(function(error, event) {
if (!error) {
$("#events").append('<li class="list-group-item">' + event.args._buyer + ' bought ' + event.args._name + '</li>');
} else {
console.error(error);
}
App.reloadArticles();
});
});
},
buyArticle: function() {
event.preventDefault();
// retrieve the article price and data
var _articleId = $(event.target).data('id');
var _price = parseFloat($(event.target).data('value'));
App.contracts.OurRentalTestFromClassMay24.deployed().then(function(instance){
return instance.buyArticle(_articleId, {
from: App.account,
value: web3.toWei(_price, "ether"),
gas: 500000
});
}).catch(function(error) {
console.error(error);
});
}
};
$(function() {
$(window).load(function() {
App.init();
});
});

jQuery incrementing a cloned elements instead of cloned div

I had this HTML script which contains a drop list and a text box, and I just need to clone those two instead of the whole div, and then send the data to AJAX, and each drop list with text box will form an array that should be add as a single row in a table, that's what I have now:
<div class="col-sm-4 rounded" style="background-color: #D3D3D3">
<div class="row clonedInput" id="clonedInput1">
<div class="col-sm-6 ">
<label for="diagnosis_data">Medication</label>
<fieldset class="form-group">
<select class="form-control select" name="diagnosis_data" id="diagnosis_data">
<option value="choose">Select</option>
</select>
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<div class="col-sm-6">
<label for="medication_quantity">Quantity</label>
<fieldset class="form-group">
<input type="number" class="form-control" name="medication_quantity" id="medication_quantity">
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<!-- End class="col-sm-6" -->
</div>
<div class="actions pull-right">
<button class="btn btn-danger clone">Add More</button>
<button class="btn btn-danger remove">Remove</button>
</div>
<!-- End class="col-sm-4" -->
</div>
And here is the jQuery Script:
$(document).ready(function()
{
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
})
var regex = /^(.+?)(\d+)$/i;
var cloneIndex = $(".clonedInput").length;
function clone(){
$(this).closest(".rounded").clone()
.insertAfter(".rounded:last")
.attr("id", "rounded" + (cloneIndex+1))
.find("*")
.each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = id.split('-')[0] +'-'+(cloneIndex);
}
})
.on('click', 'button.clone', clone)
.on('click', 'button.remove', remove);
cloneIndex++;
}
function remove(){
$(this).parent().parent(".rounded").remove();
}
The problem is that the whole div is being cloned and just the div id is being changed:
Here is the id of each div is being incremented:
I need to clone the 2 elements only not the whole div and buttons
At the end I need t add them to database using Ajax and PHP
Here you can go with the code.
In this code i made changes in clone()
Here the changes
You first find existing child element.
Than clone that element and append it after last element
var cloneIndex = $(".clonedInput").length; this should be in clone() So it will pass proper incremented value of child element as id in your cloned html
the below code just only make clone of clonedInput not a whole div
Edit
I also edit remove function also.
It will only removes last element which was cloned.
Hope this will helps you. :)
$(document).ready(function()
{
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
});
var regex = /^(.+?)(\d+)$/i;
function clone() {
var cloneIndex = $(".clonedInput").length;
$(".rounded").find("#clonedInput1").clone().insertAfter(".clonedInput:last").attr("id", "clonedInput" + (cloneIndex+1));
}
function remove() {
$(".rounded").find(".clonedInput:last").remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-4 rounded" style="background-color: #D3D3D3">
<div class="row clonedInput" id="clonedInput1">
<div class="col-sm-6 ">
<label for="diagnosis_data">Medication</label>
<fieldset class="form-group">
<select class="form-control select" name="diagnosis_data" id="diagnosis_data">
<option value="choose">Select</option>
</select>
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<div class="col-sm-6">
<label for="medication_quantity">Quantity</label>
<fieldset class="form-group">
<input type="number" class="form-control" name="medication_quantity" id="medication_quantity">
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<!-- End class="col-sm-6" -->
</div>
<div class="actions pull-right">
<button class="btn btn-danger clone">Add More</button>
<button class="btn btn-danger remove">Remove</button>
</div>
<!-- End class="col-sm-4" -->
</div>
You can add style to your actions class to prevent it from showing on all cloned elements
css
.actions {
display: none;
}
.clonedInput:first-child .actions {
display: block;
}
Also for the removing function you could use .closest() instead of .parent().parent()
$(this).closest(".rounded").remove();
There are a lot of things that could be optimized and replaced but I've edited your code. I believe that this is the easiest way to learn.
The edits are marked as "STACKOVERFLOW EDIT" in the comments.
$(document).ready(function() {
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
$("button.submit").on("click", submit_form); // STACKOVERFLOW EDIT: execute the submit function
});
var regex = /^(.+?)(\d+)$/i;
function clone() {
var cloneIndex = $(".clonedInput").length;
$(".rounded").find("#clonedInput1").clone().insertAfter(".clonedInput:last").attr("id", "clonedInput" + (cloneIndex + 1));
}
function remove() {
if($(".clonedInput").length > 1) { // STACKOVERFLOW EDIT: Make sure that you will not remove the first div (the one thet you clone)
$(".rounded").find(".clonedInput:last").remove();
} // STACKOVERFLOW EDIT
}
// STACKOVERFLOW EDIT: define the submit function to be able to sent the data
function submit_form() {
var ajax_data = $('#submit_form').serialize(); // The data of your form
$.ajax({
type: "POST",
url: 'path_to_your_script.php', // This URL should be accessable by web browser. It will proccess the form data and save it to the database.
data: ajax_data,
success: function(ajax_result){ // The result of your ajax request
alert(ajax_result); // Process the result the way you whant to
},
});
}
The HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-4 rounded" style="background-color: #D3D3D3">
<form action="" method="post" id="submit_form"> <!-- STACKOVERFLOW EDIT: generate a form to allow you to get the data in easy way -->
<div class="row clonedInput" id="clonedInput1">
<div class="col-sm-6 ">
<label for="diagnosis_data">Medication</label>
<fieldset class="form-group">
<select class="form-control select" name="diagnosis_data[]" id="diagnosis_data"> <!-- STACKOVERFLOW EDIT: Add [] so that you may receive the values as arrays -->
<option value="choose">Select</option>
</select>
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<div class="col-sm-6">
<label for="medication_quantity">Quantity</label>
<fieldset class="form-group">
<input type="number" class="form-control" name="medication_quantity[]" id="medication_quantity"> <!-- STACKOVERFLOW EDIT: Add [] so that you may receive the values as arrays -->
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<!-- End class="col-sm-6" -->
</div>
</form> <!-- STACKOVERFLOW EDIT -->
<div class="actions pull-right">
<button class="btn btn-danger clone">Add More</button>
<button class="btn btn-danger remove">Remove</button>
<button class="btn btn-danger submit">Submit</button>
</div>
<!-- End class="col-sm-4" -->
</div>

Automatically change text in user-filled form before submitting

I have searched and found answers for questions similar to mine, but I am not experienced with JS, so I am not sure how to apply the answers to my situation. I have a form where users enter a URL to submit to me. The URL can be from any site but when users enter a Youtube short (share) URL, I need the field to be changed to a regular Youtube URL before the form is submitted. Here are the two answers I have found to similar questions:
Change form values after submit button pressed
Automatically change a value in a form field
Basically, when a user enters URLS in this format:
https://youtu.be/VIDEO_ID_HERE
I need the text in the field changed to this format before the form is submitted:
https://www.youtube.com/watch?v=VIDEO_ID_HERE
Thank you for any help.
The code I have for this popup form is:
<!-- POPUP 8 // START -->
<div id="popup-8" class="container container-size-11 container-radius-1 container-padding-5 container-shadow-1 bg-color-1 position-relative responsive-popup">
<h3 class="title-2 title-border-bottom-1 color-1"><?php echo $this->_('Add an image from a website') ?></h3>
<form action="<?php echo $this->url(array('controller' => 'find-images'),'urlpin_c');?>" method="post" class="event-find-images">
<div class="form-1 form-margin-20 margin-top-20">
<div class="form-row">
<div class="notification notification-color-3"><?php echo $this->_('Check out our bookmarklet to make pinning from a website even easier!') ?></div>
</div>
<div class="form-row form-row-group-top form-row-group-top-padding-3 margin-top-20">
<span class="field-button field-button-position-1 fill">
<input name="url" type="text" placeholder="http://" class="field field-color-1 field-size-1 event-url-text">
<button type="submit" class="button button-type-1 button-color-2 button-size-3 event-loader"><?php echo $this->_('Find') ?></button>
</span>
</div>
<div class="form-row event-back-ios-8">
<div class="table-grid">
<div class="table-grid-cell event-upload-pin">
Back
</div>
</div>
</div>
<div class="hide notification notification-color-1 margin-top-20 event-url-status"></div>
<div class="form-row form-row-group-top form-row-group-top-padding-3 margin-top-20">
<ul class="list-30 clearfix hide event-found-images"></ul>
</div>
</div>
</form>
</div>
<!-- POPUP 8 // END -->
<script type="text/javascript">
$('.event-find-images').on('submit',function(){
App.addLoader('.event-loader');
$('.event-url-status').addClass('hide');
App._ajax({
url: '<?php echo $this->url(array('controller' => 'find-images'),'urlpin_c');?>',
onSuccess: function(json) {
App.removeLoader('.event-loader');
if(json.location) {
window.location = json.location;
} else if(json.errors) {
var errors = [];
for(i in json.errors)
errors.push(json.errors[i]);
$('.find-images').remove();
$('.event-url-status').html(errors.join("<br />")).removeClass("hide");
} else {
//console.log(json);
}
},
type: 'POST',
data: $(this).serialize()
});
return false;
});
</script>
You can check and change the input value when the user submit:
// When the user submits,
$('.event-find-images').on('submit',function(){
// Change value of the url.
$(".event-url-text").val(function(index, value) {
// Find for pattern and then replace.
return value.replace(
/https:\/\/youtu\.be\/(.+)/,
"https://www.youtube.com/watch?v=$1"
);
});
// the rest of your code...
Hope this helps!
Give you text box some id like
<input id="yturl" name="url" type="text" placeholder="http://" class="field field-color-1 field-size-1 event-url-text">
Add this in submit callback before you do App._ajax.Also see an example besides
var shorturl = $("#yturl").val(); // https://youtu.be/c8aFcHFu8QM
var urlarray = shorturl .split("/"); //["https:", "", "youtu.be", "c8aFcHFu8QM"]
var videoID = urlarray[3]; // c8aFcHFu8QM
$var = "https://www.youtube.com/watch?v="+videoID;
$("#yturl").val(fullurl ); // assign full url to text box
Now in ajax data: $(this).serialize() jquery would see and use this updated value

Categories

Resources