How to declare variables dynamically in javascript - javascript

is it possible to read from post variables dynamically?
i.e.
function ajax_edit_color(color_id, building)
{
var color_name = $('#color_name_'+color_id).val();
var color_hex_code = $('#color_hex_code_'+color_id).val();
console.log(color_name, color_hex_code);
}
when I look at the console, the variables are undefined. Is there a correct syntax for this?
EDIT :
the HTML is dynamic (PHP):
<label for="color_name_<?php $value['id']; ?>">Color name : </label>
<input type="text" name="color_name_<?php $value['id']; ?>" id="color_name_<?php $value['id']; ?>" class="form-control" required="required" value="<?php echo $value['color_name']; ?>" />
<label for="color_hex_code_<?php $value['id']; ?>">Color HEX code : </label>
<input type="text" name="color_hex_code_<?php $value['id']; ?>" id="color_hex_code_<?php $value['id']; ?>" class="form-control" required="required" value="<?php echo $value['color_code']; ?>" />
AND HERE's the rendered HTML :
<label for="color_name_">Color name : </label>
<input type="text" name="color_name_6" id="color_name_" class="form-control" required="required" value="orange" />
<label for="color_hex_code_">Color HEX code : </label>
<input type="text" name="color_hex_code_6" id="color_hex_code_" class="form-control" required="required" value="ff9c00" />

Look at your final HTML:
<label for="color_name_">Color name : </label>
<input type="text" name="color_name_6" id="color_name_"
class="form-control" required="required" value="orange" />
The name is right, but the id is wrong. Fix your php, and the javascript will start working. The id needs to be color_name_6, not color_name_.

Your basic approach is correct, so I suggest you start with a simplified test, for example without PHP. One basic example, which I verified to work:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="js/libs/jquery-2.1.4.js"></script>
<script>
function test(){
var index=1;
var val=$("#color_name_"+index).val();
console.log( '****' +val);
};
</script>
</head>
<body>
<button onclick="test();return false;">test</button>
<input type="text" id='color_name_1' value='green'>
<input type="text" id='color_name_2' value='blue'>
</body>
This works. Now if your own code is failing, try looking for differences, in particular:
1. When is your javascript running - could it be before the "color_name" elements are rendered in the document?
2. Could your PHP be generating wrong values, this could be tested by viewing the document source of course

edit you javascript to match the following
function ajax_edit_color(color_id, building)
{
var color_name = $('#'+color_id).val();
var color_hex_code = $('#'+color_id).val();
console.log(color_name, color_hex_code);
}
//color_name_ and color_hex_code_ are both already part of your ids.

Related

update and save date automatically

Hi guys i am working for project in php I have <form> with save button <input> to update the data in the database
The idea what i want to do , instead to click every single page to update the data, i want to do it automatically by using for example javascript function for example every 10 min every single page will update auto
Manually if I click Save button it will update data in DB
once i click the page i can see there is some update and it need to save in db, i need to do this automatic click save button for every single pages every 10 min
Here is an example of what i did
<form action="/test.php" method="post">
<input type="text" name="test1" value="<?= $test->from; ?>" />
<input type="text" name="test2" value="<?= $test->to; ?>" />
<input type="text" name="test3" value="<?= $test->distance; ?>" />
<input type="text" name="test4" value="<?= $test->time; ?>" />
<input type="hidden" name="action" value="<?= $action ?>" />
<input type="hidden" name="id" value="<?= $test->id ?>" />
<input type="submit" name="submit" value="<?= $title ?>" />
</form>
And here for the script
window.onload(function () {
setTimeout("document.forms[0].submit();", 10000);
});
I need your help guys to solve this problem it will save my time instead of open every single page and click update button
Try this simple change in your script. I hope it will help.
function autoSubmit(){
setTimeout(document.forms[0].submit(), 10000);
}
window.onload = autoSubmit()

"Data entered successfully" message to appear on same page of insert form?

I have an insert form where I can submit data into my database.
Here's my code:
<form action="insert_backend.php" method="POST" enctype="multipart/form-data">
<!-- Method can be set as POST for hiding values in URL-->
<h2>Form</h2>
<label for="uploadedimage">Small image to upload: </label>
<input type="file" name="uploadedimage" id="uploadedimage"/><br />
<label>Date:</label>
<input class="input" name="date" type="text" value=""><br />
<label>Retrace:</label>
<input class="input" name="retrace" type="text" value=""><br />
<label>Start of Swing Trade:</label>
<input class="input" name="start_of_swing_trade" type="text" value=""><br />
<label>End of Swing Trade:</label>
<input class="input" name="end_of_swing_trade" type="text" value=""><br />
<label>Bull flag:</label>
<input class="input" name="bull_flag" type="text" value=""><br />
<label>Bear flag:</label>
<input class="input" name="bear_flag" type="text" value=""><br />
<label>EMA Crossover:</label>
<input class="input" name="ema_crossover" type="text" value=""><br />
<label>Trading Instrument:</label>
<input class="input" name="trading_instrument" type="text" value=""><br />
<input class="submit" name="submit" type="submit" value="Insert">
</form>
Here's a snippet of the "Success" message on the php that is used to process the data submitted to the database:
$stmt->bind_param('sssssssss',$target_path, $date, $retrace, $start_of_swing_trade, $end_of_swing_trade, $bull_flag, $bear_flag, $ema_crossover, $trading_instrument);
if(!$stmt){ exit("bind failed");}
//will return 0 if fail
if($stmt->execute() != 0){
echo "New record created successfully";
}else{ echo "Failed to insert new record";}
Whenever I Insert data, I get the "New record created successfully" message on the insert_backend.php page, which is the php file used to process and submit the data, but not on the actual form page used to insert data. Usually when you use a form to send a message to someone or to send data into a database, the form resets itself and you get a "success" message that shows at the bottom of the form without getting redirected to another page. But the code I have redirects me to the page that is used to process the data. how do I get it to show the "success" message on the same page as the form itself?
My FULL insert form code (with the php redirect check solution in it):
<!DOCTYPE html>
<html>
<head>
<title>Chart Submission Form</title>
<link href="insert.css" rel="stylesheet">
</head>
<body>
<div class="maindiv">
<!--HTML Form -->
<div class="form_div">
<div class="title">
<h2>Insert Data In Database Using PHP.</h2>
</div>
<form action="insert_backend.php" method="POST" enctype="multipart/form-data">
<!-- Method can be set as POST for hiding values in URL-->
<h2>Form</h2>
<label for="uploadedimage">Small image to upload: </label>
<input type="file" name="uploadedimage" id="uploadedimage"/><br />
<label>Date:</label>
<input class="input" name="date" type="text" value=""><br />
<label>Retrace:</label>
<input class="input" name="retrace" type="text" value=""><br />
<label>Start of Swing Trade:</label>
<input class="input" name="start_of_swing_trade" type="text" value=""><br />
<label>End of Swing Trade:</label>
<input class="input" name="end_of_swing_trade" type="text" value=""><br />
<label>Bull flag:</label>
<input class="input" name="bull_flag" type="text" value=""><br />
<label>Bear flag:</label>
<input class="input" name="bear_flag" type="text" value=""><br />
<label>EMA Crossover:</label>
<input class="input" name="ema_crossover" type="text" value=""><br />
<label>Trading Instrument:</label>
<input class="input" name="trading_instrument" type="text" value=""><br />
<input class="submit" name="submit" type="submit" value="Insert">
</form>
<?php
if (isset($_GET['success']) && $_GET['success']) {
echo "New record created successfully";
} else if (isset($_GET['success']) && !$_GET['success']) {
echo "Failed to insert new record";
}
?>
</div>
</div>
</body>
</html>
Updated my PHP code to include the header location:
$sql = "INSERT into charts (charts_URL, charts_date, charts_retrace, charts_start_of_swing_trade, charts_end_of_swing_trade, charts_bullflag, charts_bearflag, charts_ema_crossover, charts_trading_instrument) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
// s = string, i = integer, d = double, b = blob
//preparing statement
$stmt = $conn->prepare($sql);
if(!$stmt){ exit("prepare failed");}
//binding param
$stmt->bind_param('sssssssss',$target_path, $date, $retrace, $start_of_swing_trade, $end_of_swing_trade, $bull_flag, $bear_flag, $ema_crossover, $trading_instrument);
if(!$stmt){ exit("bind failed");}
//will return 0 if fail
if($stmt->execute() != 0){
$success = true;
}else{
$success = false;
}
header('location:insertchart.php?success='.$success);
exit;
}
}
}
?>
The FINAL code (actually a snippet) that made everything work:
if($stmt->execute() != 0){
$success = true;
header('Location:http://mlsinc.net/chart-submission/insertchart.php?success='.$success);
}else{
$success = false;
header('Location:http://mlsinc.net/chart-submission/insertchart.php?success='.$success);
}
}
//close connection
$conn->close();
Try with -
$stmt->bind_param('sssssssss',$target_path, $date, $retrace, $start_of_swing_trade, $end_of_swing_trade, $bull_flag, $bear_flag, $ema_crossover, $trading_instrument);
if(!$stmt){ exit("bind failed");}
//will return 0 if fail
if($stmt->execute() != 0){
$success = true;
}else{
$success = false;
}
header('location:yourform.php?success='.$success);
exit;
On you form page add a check for it -
if (isset($_GET['success']) && $_GET['success']) {
echo "New record created successfully";
} else if (isset($_GET['success']) && !$_GET['success']) {
echo "Failed to insert new record";
}
To show the message on form page
Store the message in session after inserting the row(since you are redirecting page)
I think the soultion suggested by sgt BOSE will work for you. But instead of passing a "success" GET parameter back to your page containing form, you should use a session variable because the $_GET['success'] will re-print the message if user reloads the window.
Once you print the result stored in session variable make sure to unset it.
Ok I see your problem here, it's actually pretty simple.
the way it works is that the message would be declared inside of the script tag
so you should do something like this so it will call the message.
<html>
<head>
<script type="text/javascript">
//Put the javascript function you want the button to do Here
function show_alert()
{
alert("Form Succesfully Submited");
}
</script>
</head>
<body>
<form action="insert_backend.php" method="POST" enctype="multipart/form-data">
<!-- Method can be set as POST for hiding values in URL-->
<h2>Form</h2>
<label for="uploadedimage">Small image to upload:</label>
<input type="file" name="uploadedimage" id="uploadedimage" />
<br />
<label>Date:</label>
<input class="input" name="date" type="text" value="">
<br />
<label>Retrace:</label>
<input class="input" name="retrace" type="text" value="">
<br />
<label>Start of Swing Trade:</label>
<input class="input" name="start_of_swing_trade" type="text" value="">
<br />
<label>End of Swing Trade:</label>
<input class="input" name="end_of_swing_trade" type="text" value="">
<br />
<label>Bull flag:</label>
<input class="input" name="bull_flag" type="text" value="">
<br />
<label>Bear flag:</label>
<input class="input" name="bear_flag" type="text" value="">
<br />
<label>EMA Crossover:</label>
<input class="input" name="ema_crossover" type="text" value="">
<br />
<label>Trading Instrument:</label>
<input class="input" name="trading_instrument" type="text" value="">
<br />
<!--This is where you tell the script where to load the (ID) for example im using a simple message for you what you need to do is make the id im sure you know how to create a simple (ID) inside of a java ,heck im thirteen im about an expert on it if i can do im sure you can! :) :)
anyway inside the div tag make it look like this: <div id=("PUT ID IN HERE") >
then put you function in the script for wha you want it to do hope this helped you have a nice day!-->
<div>
<input class="button" name="submit" type="submit" onclick="show_alert()" value="Submit">
</div>
</form>
</body>
</html>
Hope that this helps if not dont hate lol.

Javascript Empty field validation - Cannot read property 'value' of undefined

I have been researching for days and taken several example from here for a solution to validate a date fields to make sure it is not empty before moving to next page. but keeps getting cannot read property of undefined, and I have tried using Joomla build validate.js which will not work inside this custom component, and I am hoping for some help here to tackle this issue.
Here's the javascript
nextpage:function(){
var deliveryy=document.getElementsByName("customPlugin")[0].value;
if(delivery == "" || delivery == null) {
alert("filled out All Delivery Date & Time");
return false; } else { .........
Here's the onclick button
<button type="button" id="productbuilder_next" class="productbuilder_pagination pbbutton btn" onclick="productbuilder.nextpage();"> Next</button>
Here's the raw data of the field I am trying to validate that it is not empty
<input id="<?php echo $class.$rand ?>" class="required <?php echo $class ?>" required="true" type="text" value="" size="<?php echo $this->params->custom_size ?>" name="customPlugin[<?php echo $viewData[0]->virtuemart_customfield_id ?>][<?php echo $this->_name?>][comment]"><?php if($this->params->custom_populate_alternate_field){?> <input type="text" id="alternate<?php echo $rand?>" size="30">
Generated
<input id="vmcustom-datetime1930516000" class="required vmcustom-datetime hasDatepicker" required="true" type="text" value="" size="10" name="customPlugin[176][datetime][comment]">
You're looking for a name that doesn't exist in the DOM. In this way, it'll throw this error when you access the property value.
Classes can be used here. Just add a class in your element and search for it in your function.
HTML:
<input id="vmcustom-datetime1930516000" class="required validDelivery vmcustom-datetime hasDatepicker" required="true" type="text" value="" size="10" name="customPlugin[176][datetime][comment]">
JS:
var validDelivery = document.getElementsByClassName("validDelivery")[0].value;
JSFiddle: http://jsfiddle.net/t1g7cfrb/1/
Give it a try and let me know if it helps!
Name of your element is "validDelivery customPlugin[176][datetime][comment]"
And you want to handle it with getElementsByName("customPlugin"). It's incorrect.
You may for example add class customPlugin to element and handle it with getElementsByClassName("customPlugin")[0].

JavaScript error in function which calcs sum of two values

this is my JS code to check the match of two digits
<script type="text/javascript">
function match(){
var a=parseInt(document.getElementById("one"));
var b=parseInt(document.getElementById("two"));
var c=parseInt(document.getElementById("sum"));
var d;
d=a+b;
if(d!=c)
{
alert("Something is wrong!!");
}
else
{
alert ("Success");
}
}
</script>
html code for generat two digits and check on the process.
<form action="#" method="post" onsubmit="return match();">
<input type="text" name="one" id="one" value="<?php echo rand(1,9); ?>" readonly="readonly"/>
+
<input type="text" name="two" id="two" value="<?php echo rand(1,9); ?>" readonly="readonly"/>
=
<input type="text" name="sum" id="sum" />
<input type="submit" value="submit" />
</form>
Perhaps you want their value and not the element itself.
var a=parseInt(document.getElementById("one").value,10);
var b=parseInt(document.getElementById("two").value,10);
var c=parseInt(document.getElementById("sum").value,10);
Also, provide the radix when you are using parseInt() otherwise it may go crazy sometimes.

Form onsumbit executing a function

I have this code:
function src(){
var id = document.getElementsByName("query")[0].value;
window.location.href = "/search/?query=" + id;
}
var f_src = document.getElementById("search_form");
if(f_src)
f_src.onsubmit = function(){src();return false;};
I'm having problems with the submit part: I want, when I enter "example" in the field "url" to be redirected to "/search/?query=example", but it's not working, any help?
HTML:
<form id="search_form" method="get" action="" name="search_f">
<input id="search_field" maxlength="100" name="query" type="text" value="" placeholder="<?php echo $src_txt; ?>">
<input id="search_button" type="submit" value="">
</form>
Thanks.
Aside from the problem you might have, you can achieve the same behavior without JavaScript. You just have to give the form element the name "query" and make it submit a GET request to /search:
<form id="search_form" method="get" action="/search/" name="search_f">
<input id="search_field" maxlength="100" name="query" type="text" value="" placeholder="<?php echo $src_txt; ?>">
<input id="search_button" type="submit" value="">
</form>
The action attribute tells the browser where to make the request to. Every form control element with a name will be included with its value in the query string.
No JavaScript required.
If You don't insist on using javascript, You can achieve this using good old HTML:
<form action="/search/" method="get">
<input name="query" />
</form>

Categories