I am trying to send a JavaScript variable to PHP but not exactly sure how to do it, a few things have said Ajax but I've never used it before and can't get my head around it. Does anyone know what the easiest way to do this would be? The column which I am attempting to populate in my DB is called 'cogs'.
I have the following JavaScript code:
<script>
$(document).ready(function() {
$('#duration-select').change(function() {
var cogs = $('#cogsday').html();
cogs = cogs.replace(/\D/g,'');
var x =$('#duration-select').val();
var y = cogs * x;
$('#request').removeClass('hidden');
$('#duration-value').text('Total cost for this duration = ' + (y) + ' cogs');
if($(this).val() !== '') {
} else {
$('#duration-value').text('');
}
});
$('#request').click(function() {
var cogs = $('#cogsday').html();
cogs = cogs.replace(/\D/g,'');
var x =$('#duration-select').val();
var y = cogs * x;
$('#total').text(y);
});
});
</script>
And the following HTML code:
<label id="total"></label>
Here is where I am trying to post the data, everything else is posting except for the $cost:
<form name="form" method="post">
<div class="modal-footer">
<?php
if ($row3['availability'] === 'Available') {
if (isset($_POST['request'])) {
$to_id = $row3['customerid'];
$from_id = $_SESSION['customerid'];
$time_sent = date('Y-m-d H:i:s');
$subject = 'Request for ' . $row3['title'];
$title = $row3['title'];
$listingid = $listingid;
$cost = $_POST['total']; //posting 0
$message = $customer_data['first_name'] . ' ' . $customer_data['last_name']
$request = mysql_query("INSERT INTO messages (to_id, from_id, listing_id, time_sent, subject, message, cogs, messagenumber, title, msgrand) VALUES ('$to_id', '$from_id', '$listingid', '$time_sent', '$subject', '$message', '$cost', '1', '$title', '$randomString')") or die(mysql_error());
}
}
?>
<input type="submit" class="btn btn-success" name="request" value="Yes" />
<input type="submit" class="btn btn-danger" data-dismiss="modal" value="No" />
</div>
</form>
Then I am trying to post the value of the label id=total to my db or the JavaScript variable (y). The problem is that 0 is always being sent to the DB when it should instead be the value that is in the label where the id is total.
Use name parameter for hidden variable and it will be automatically passed to PHP .
<label id="total"></label>
<input type="hidden" name="total" id="nameID"/>
in javascript below $('#total').text(y); write $('#nameID').val(y); . Everything will work properly.
You used total label , but $_POST recognizes only input type so use input type=.... instead of a label,divs etc.
IF YOU REAllY NEED ANSWER REPLY HERE
you have make an input type and its value is to be set by that javascript and then you'll be able to get that $cost value in php code
<input type="hidden" value="" name="total" id="total">
..................
$("#total").val(y);
You can use this to send the variables....
<input type="text" id="name" class="name" placevalue="Enter you name" required /><br><br>
<input type="text" id="email" class="email" placevalue="Enter you name" required /><br><br>
<button id= "det_submit" onclick="submit_det()"> Submit </button>
<script>
function submit_det() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if(name != "" && email != "") {
$.post(
'xx.php',
{
name : document.getElementById("name").value,
email1 : document.getElementById("email").value,
},
function(data){
alert(data);
});
} else {
alert("empty");
}
}
</script>
here is xx.php
<?php
if(isset($_POST['name']) && isset($_POST['email1'])) {
$name = $_POST['name'];
$email = $_POST['email1'];
//code to insert into your database......
}
?>
Use a ID and Name for hidden parameter like this
<label id="total"></label
<input type="hidden" name="name" id="name"/>
and in jQuery edit the code like this
$('#total').text(y);
$('#nameID').val(y);
hope that it will work
Related
here is my way to submit a form.
In reality it has much more text inputs.
Everything works fine, but I hope there is a shorter way, especially on server side, regarding that data-col on client side is in fact a corresponding column name on server.
html
<form id='dform'>
<input type='text' class='dinp' data-col='nick'>
<input type='text' class='dinp' data-col='state'>
<input type='text' class='dinp' data-col='city'>
<input type='text' class='dinp' data-col='uname'>
<input type='text' class='dinp' data-col='pass'>
</form>
js
$('#msave').on('click', function(){
let id=$('.aact').attr('data-id');
let obj = {};
$('.dinp').each(function(){
let col = $(this).attr('data-col');
obj[col] = $(this).val().trim();
});
obj = JSON.stringify(obj);
$.post('a_users_pro.php', {fn: 'm_save', args: [id, obj]}, function(data){
console.log(data);
});
});
php
function m_save($id, $obj){
global $db;
$obj = json_decode($obj);
$sql = "
update users
set nick = :anick
, state = :astate
, city = :acity
, uname = :auname
, pass = :apass
where id = :aid
";
$st = $db->prepare($sql);
$st -> execute([
":aid" => $id,
":anick" => $obj->nick,
":astate" => $obj->state,
":acity" => $obj->city,
":auname" => $obj->uname,
":apass" => $obj->pass
]);
}
You can use the name attribute of input elements with your data-col value and pass the serialized form data to the AJAX request. Here is a implementation:
HTML:
<form id="myForm">
<input type="text" name="name" placeholder="name">
<input type="email" name="email" placeholder="email">
<input type="number" name="age" placeholder="age">
<input type="hidden" name="id" value="1">
<button type="submit">Submit</button>
</form>
JavaScript:
$(document).ready(function() {
$('#myForm').on('submit', function(e) {
e.preventDefault();
$.post('update.php', $('#myForm').serialize());
});
});
PHP:
<?php
if (isset($_POST)) {
// Validate request
$sql = 'UPDATE users
SET
name = :name,
email = :email,
age = :age
WHERE id = :id
';
$st = $db->prepare($sql);
$st->execute([
':id' => $_POST['id'],
':name' => $_POST['name'],
':email' => $_POST['email'],
':age' => $_POST['age'],
]);
}
?>
In your example I can't see where .aact and data-id come from. I assumed that the id value would be available to the view so I passed it to the request as a hidden input.
I have this http://localhost/resume/Template/index.html?msg=Message%20Sent%20Successfully
how do I extract the message "Message Sent Successfully and display it in this form
<form action="send_form_email.php" name="contactForm" method="post">
//I want to display the message here
<h4>E-mail</h4>
<div class="border-stripes">
<input type="email" class="textfield" name="email" placeholder="Your e-mail address" />
</div>
<h4>Message</h4>
<div class="border-stripes">
<textarea class="textarea" name="message" rows="3" placeholder="Your message"></textarea>
</div>
<br />
<br />
<input id="submit" name="submit" type="submit" value="Submit">
</form>
This should echo the GET variable:
<?php echo urldecode($_GET['msg']); ?>
If you want to do this in javascript then you can try to parse query string:
var query = (function() {
function decode(string) {
return decodeURIComponent(string.replace(/\+/g, " "));
}
var result = {};
if (location.search) {
location.search.substring(1).split('&').forEach(function(pair) {
pair = pair.split('=');
result[decode(pair[0])] = decode(pair[1]);
});
}
return result;
})();
$('form[name=contactForm]').prepend('<p>' + query['msg'] + '</p>');
Javascript:
I have write down the function for same using that you can access any parameter of URL.
Example:
function getParamValue(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(location.href);
if (results == null)
return "";
else
return decodeURI(results[1]);
}
alert(getParamValue('param'));
Your solution:
http://jsfiddle.net/tb8cetLy/1/
If you need to do it in php (note that there is no security check for XSS)
<form action="send_form_email.php" name = "contactForm" method="post">
<?php echo urldecode($_GET['msg']); ?>
<h4>E-mail</h4>
<div class="border-stripes"><input type="email" class="textfield" name="email" placeholder="Your e-mail address" /></div>
<h4>Message</h4>
<div class="border-stripes"><textarea class="textarea" name="message" rows="3" placeholder="Your message"></textarea></div><br /><br />
<input id="submit" name="submit" type="submit" value="Submit">
</form>
else in js
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var msg = getParameterByName('msg');
$( "form" ).prepend( "<p>"+msg+"</p>" );
The function getParameterByName is taken from here
I guess you are doing something like this in send_form_email.php
// process form data
// redirect to index.html with $_GET['msg'] variable
If you want pretty URLs, use a function like this below, include it on top of your common file
session_start();
function flash_set($k,$v)
{
$_SESSION['flash'][$k] = $v;
}
function flash_get($k)
{
if(isset($_SESSION['flash'][$k]))
{
$msg = $_SESSION['flash'][$k];
unset($_SESSION['flash'][$k]);
return $msg;
}
return '';
}
change the send_form_email.php to redirect without $_GET parameters, after you process your form put this,
// process form data
flash_set('form','Message Sent Successfully');
// redirect here
Now, use this in your form like,
<form action="send_form_email.php" name="contactForm" method="post">
<?php echo flash_get('form')?> // I want to display the message here
<h4>E-mail</h4>
The flash message will only show up single time after being redirected, if user refreshes the page, it disappears!!
In HTML/PHP only, you would use urldecode($_GET['msg'])
You can also do it with javascript with a function like :
function getQuerystring(key, default_) {
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
This function will allow you to get msg with var msg = getQuerystring("msg"); and you can mix it with unescape functions ( http://www.w3schools.com/jsref/jsref_unescape.asp ).
i am using the following form:
<form id="dataForm" method="post">
<h2 id="formheader"> Update Product Description</h2>
<div>
<label>Product Name:</label>
<input class="inputForm" id="orginalName" type="text" name="Name">
</div>
<div>
<label>New Description:</label>
<input class="inputForm" id="newDescription" type="text" name="newDescription">
</div>
<div id="theSubmit">
<button id="editDescription">Submit</button>
</div>
</form>
and using the following simple php, which when used with action=editProductDes.php works...
$Name = $_POST['Name'];
$Description = $_POST['newDescription'];
if($Name !="" && $Description !=""){
$sql = "UPDATE PRODUCTS SET P_Description = '$Description' WHERE P_NAME = '$Name'";
$conn->exec($sql);
and then when i use the following java script the data is not passed through and I cannot see why as I have a similar function and form where the JavaScript works fine, can anyone see why the data is not passing through?
function editDescription(){
xmlhttp = new XMLHttpRequest();
var name = document.getElementById("orginalName");
var Description = document.getElementById("newDescription");
var data_seen = false;
// this is a flag to record whether any data has been seen. Used in the guard ofthe alert statement.
if (name.value !="" && Description.value !="" ){
data_seen = true;
xmlhttp.open("POST","editDescription.PHP",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("Name=" + name.value + "&Description=" + Description.value);
}
if (!data_seen) {
alert("please enter some data");
}
}
submitButton = document.getElementById("editDescription");
submitButton.addEventListener("click", editDescription);
You are posting to editDescription.PHP instead of editProductDes.php
Change the following:
xmlhttp.open("POST","editProductDes.php",true);
You are also sending the data in your post under another name than you expect it to be in your PHP code (Description instead of newDescription) - change:
xmlhttp.send("Name=" + name.value + "&newDescription=" + Description.value);
Hello guys i have this php jquery ajax create user form that passes the create details to the php script but i keep getting null on the post variables anyhelp would be appreciated! code below
Html:
<form method="post" action="" id="createForm">
<input type="text" name="createUser" class="form-control" placeholder="Brugernavn*" id="createUser">
<input type="email" name="createUserEmail" class="form-control" placeholder="Email*" id="createUserEmail">
<input type="password" name="createUserPass" id="createUserPass" class="form-control" placeholder="Kodeord*" id="createUserPass">
<input type="password" name="confirmUserPass" id="confirmUserPass" class="form-control" placeholder="Bekræft Kodeord*" id="createUserPass">
<h4 id="newsletterText">Vil du have vores nyhedsbrev?</h4>
<select name="newsletter" id="newsletter" class="form-control"><option value="yes">Ja tak!</option><option value="nej" selected="">Nej tak</option></select>
<input type="submit" name="submitCreateUser" class="btn btn-success" id="submitCreateUser" value="Opret!">
</form>
jquery:
$(document).ready(function(){
$("#submitCreateUser").click(function(){
var username = $("#createUser").val();
var email = $("#createUserEmail").val();
var pass = $("#createUserPass").val();
var cPass = $("#createUserPassC").val();
var newsletter = $("#newsletter").val();
$.ajax({
type: "POST",
url: "createuserajax.php",
data: "username="+username+"&email="+email+"&pass="+pass+"&cPass="+cPass,
success: function(html){
if(html=='true')
{
alert(username);
}
else
{
}
},
}
);
});
});
PHP:
<?php
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['pass'];
var_dump($username);
$securePassword = md5(($password));
$sqlInsertUser = "INSERT INTO users (username,email,password) VALUES ('$username','$email','$securePassword')";
$result = mysqli_query($con,$sqlInsertUser);
As adeneo says, your html form is likely being submitted the standard way before the ajax call is made because you haven't prevent the default behaviour. try the below instead:
Alternatively, you could remove <input type="submit" name="submitCreateUser" class="btn btn-success" id="submitCreateUser" value="Opret!"> and give the id="submitCreateUser" to some other element like a custom button or link. When you click and input tag with the type submit it will submit the accompanying form the normal way by default. This happens before the click handler hears the click so the form is submitted before your code call the ajax. Use a different element for the click and this wont happen
And don't forget for this to work at all, your php file must echo something which will be returned in your html variable, without that html will never be true and nothing will ever happen.
Part of your problem is that your input elements, specifically the ones for the password and password checks both have two separate id tags the first is duplicated and the second is a different id altogether. Also in your jquery, when you try to get the id check value you use another, different, id.
Here is a test page that address all of these issues and works as expected:
http://dodsoftware.com/sotests/createuserajax.html
The test php code:
<?php
if( isset($_POST) )
{
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['pass'];
echo 'username --'.$username.', email --'.$email.', password --'.$password;
}
?>
The html code:
<form method="post" action="" id="createForm">
<input type="text" name="createUser" class="form-control" placeholder="Brugernavn*" id="createUser">
<input type="email" name="createUserEmail" class="form-control" placeholder="Email*" id="createUserEmail">
<input type="password" name="createUserPass" id="createUserPass" class="form-control" placeholder="Kodeord*">
<input type="password" name="confirmUserPass" id="confirmUserPass" class="form-control" placeholder="Bekræft Kodeord*" >
<!-- these lines had duplicated id tags-->
<h4 id="newsletterText">Vil du have vores nyhedsbrev?</h4>
<select name="newsletter" id="newsletter" class="form-control">
<option value="yes">Ja tak!</option>
<option value="nej" selected="">Nej tak</option>
</select>
<input type="submit" name="submitCreateUser" class="btn btn-success" id="submitCreateUser" value="Opret!">
</form>
The jQuery code:
<script>
$(document).ready(function() {
$("#submitCreateUser").click(function( event ) { // add event var here
event.preventDefault(); // add this line to stop the form from submitting the normal way before the ajax call
var username = $("#createUser").val();
var email = $("#createUserEmail").val();
var pass = $("#createUserPass").val();
var cPass = $("#confirmUserPass").val(); // you were using "#createUserPassC" here in error
var newsletter = $("#newsletter").val();
var datastring = "username=" + username + "&email=" + email + "&pass=" + pass + "&cPass=" + cPass +"&newsletter=" + newsletter;
$.ajax({
type: "POST",
url: "createuserajax.php",
data: datastring,
success: function(html) {
if (html) { // changed this line from "if (html == 'true')" just for testing
alert(html); // changed this line from "alert(username);" just for testing
} else {
alert('something went wrong!');
}
},
});
});
});
</script>
I'm Trying to change the values in the database using PHP and MySQL.
I am getting the values from database and storing them in placeholder for each input but when i submit the form again it submit the inputs with empty values, i tried storing them in Value attribute for each input again the old value is overwriting what i write in the input field so nothing in the database change.
How can i keep the old value in the input fields but in case the content of these fields changed the new value is passed back to the database instead of the old one.
Here is my Code :
function list_products () {
$get = mysql_query('SELECT `id`, `SKU`, `sub`, `pname`, `desc`, `price`, `ship`, `qty`, `cat` FROM `products` ORDER BY `id` DESC');
if (mysql_num_rows($get) == 0) {
echo "There are no product to display!";
} else {
while ($get_row = mysql_fetch_assoc($get)) {
echo
'<h5>'.$get_row['pname'].' id: '.$get_row['id'].'</h5>
<form action="delete_product.php" method="post">
<input type="hidden" value="'.$get_row['id'].'" name="id">
<input type="submit" name="submit" value="DELETE" class="btn btn-lg btn-danger">
</form>
<form action="update_p.php" method="post">
<input type="hidden" placeholder="'.$get_row['id'].'" name="id" value="'.$get_row['id'].'">
<label>SKU:</label>
<input type="text" placeholder="'.$get_row['SKU'].'" name="SKU" value="'.$get_row['SKU'].'" required="">
<label>Name:</label>
<input type="text" placeholder="'.$get_row['pname'].'" name="pname" required="" value="'.$get_row['pname'].'">
<label>Subtitle:</label>
<textarea rows="2" maxlength="46" name="desc" placeholder="'.$get_row['sub'].'" required="">'.$get_row['sub'].'</textarea>
<label>Description:</label>
<textarea rows="4" name="desc" placeholder="'.$get_row['desc'].'" required="">'.$get_row['desc'].'</textarea>
<label>Price:</label>
<input type="text" placeholder="'.number_format($get_row['price'], 2).'" name="price" value="'.number_format($get_row['price'], 2).'" required="">
<label>Shipping:</label>
<input type="text" placeholder="'.number_format($get_row['ship'], 2).'" name="ship" value="'.number_format($get_row['ship'], 2).'" required="">
<label>Quantity:</label>
<input type="text" placeholder="'.$get_row['qty'].'" name="qty" value="'.$get_row['qty'].'" required="">
<label>Category:</label>
<input type="text" placeholder="'.$get_row['cat'].'" name="cat" value="'.$get_row['cat'].'" required=""><br>
<input type="submit" name="submit" value="EDIT" class="btn btn-success btn-lg">
</form>
<hr>
';
};
}
}
The update_p.php page:
if (empty($_POST) === false && empty($errors) === true) {
$id = $_POST['id'];
$update_data = array(
'pname' => $_POST['pname'],
'desc' => $_POST['desc'],
'price' => $_POST['price'],
'ship' => $_POST['ship'],
'qty' => $_POST['qty'],
'cat' => $_POST['cat']
);
update_product($id, $update_data);
The update_data function :
function update_product($id, $update_data) {
$update = array();
array_walk($update_data);
foreach($update_data as $field=>$data) {
$update[] = '`' . $field . '` = \'' . $data . '\'';
}
mysql_query("UPDATE `products` SET " . implode(', ', $update) . " WHERE `id` = $id");
}
#MaveRick Thanks for the effort, but my question is how to overwrite the value of the input fields on the page before we send the information to the server, i think its can be done using JavaScript more than php, however to make more clear these input fields refers to values in the database already stored and i would like to give the option for the user to change them in his admin panel by retrieving the content of these fields from the database and print them in the actual input fields so in case the customer pressed edit(submit) with out touching anything the same values will be sent again to the database this way nothing will be change, and in another case where the customer added or changed any value in any of these fields then the new value will be passed. hopefully i clarified my issue now. Thanks for your help anyway.
#Prafful Garg i already tried the value field but it didn't work thanks for your help anyway
You can retrieve the data again from the database in file update_p.php as follow:
if (empty($_POST) === false && empty($errors) === true) {
$id = $_POST['id'];
$get = mysql_query("SELECT * FROM `products` WHERE `id` = '$id';");
$get_row = mysql_fetch_assoc($get);
$update_data = array(
'pname' => (empty($_POST['pname'])?$get_row['pname']:$_POST['pname']),
'desc' => (empty($_POST['desc'])?$get_row['desc']:$_POST['desc']),
'price' => (empty($_POST['price'])?$get_row['price']:$_POST['price']),
'ship' => (empty($_POST['ship'])?$get_row['ship']:$_POST['ship']),
'qty' => (empty($_POST['qty'])?$get_row['qty']:$_POST['qty']),
'cat' => (empty($_POST['cat'])?$get_row['cat']:$_POST['cat'])
);
update_product($id, $update_data);
But this is not a professional way to do it.
What you can do is a loop to create the update statement and test each input; if not empty then add to the update statement , name=value otherwise to skip this input and process the next one in the array POST. something similar to the following:
function update_product($id, $update_data) {
$update = array();
array_walk($update_data);
foreach($update_data as $field=>$data) {
$update[] = '`' . $field . '` = \'' . $data . '\'';
}
$query = "UPDATE `products` SET `id` = '$id'";
foreach($update_data AS $k=>$v){
if(!empty($v) && strlen($v)>0)
$query .= ", `".$k."` = '".$v."'";
}
$query .= " WHERE `id` = '$id';";
mysql_query($query);
}
IMPORTANT NOTE: mysql() is vulnerable and deprecated, please try to avoid using mysql() and use mysqli() or dbo() extensions instead.