i cant find any solution with this condition, when id user text value changed, name & address will filled. but it return some error in the php query.
sorry if this post duplicated because i cant find solution with my condition.
here the html form
<form id="frm_add_bill" name="frm_add_bill" >
<label >id user</label>
<input type="text" onchange="getplg()" id="kdp" name="kdp">
<label >user name</label>
<input type="text" maxlength="25" name="name" id="name" readonly>
<label >user address</label>
<input type="text" name="address" id="address" readonly>
</form>
Here javascript and php code
<script type="text/javascript"> function getplg(){
var kdpe = $('#kdp').value;
$.ajax({
type: 'post',
url: '',
data: kdpe,
timeout: 50000
});
}</script>
<?php
if (isset($_POST['kdpe'])) {
$kpde=htmlspecialchars($_POST['kdpe']);
$amxz=mysql_query("SELECT name, address from tbl_user where id_user='$kpde'");
$camqz=mysql_fetch_array($amxz);
echo "<script>document.write(fillem());</script>";
}
?>
<script type="text/javascript">
function fillem(){
document.frm_add_bill.name.value=<?php echo $camqz['0'];?>;
document.frm_add_bill.address.value=<?php echo $camqz['1'];?>;
}
</script>
function getplg(){
try{
var kdpe = $('#kdp').val();
console.log("here");
$.ajax({
method: 'post',
url: '',
data: {val:kdpe}}).done(function(data){
console.log(data);
console.log("hello");
});
}catch(Exception){
alert("error");
}
}
</script>
try this.
First of all change your ajax function as:
function getplg()
{
var kdpe = $('#kdp').val();
$.ajax({
type: 'post',
url: '',
data: "kdpe="+kdpe,
timeout: 50000
});
}
Here you need to pass as "kdpe="+kdpe by using param.
And move fillem() in if (isset($_POST['kdpe'])) check.
<?php
if (isset($_POST['kdpe'])) {
$kpde=htmlspecialchars($_POST['kdpe']);
$amxz=mysql_query("SELECT name, address from tbl_user where id_user='$kpde'");
$camqz=mysql_fetch_array($amxz);
echo "<script>document.write(fillem());</script>";
?>
<script>
function fillem(){
document.frm_add_bill.name.value=<?php echo $camqz['0'];?>;
document.frm_add_bill.address.value=<?php echo $camqz['1'];?>;
}
</script>
<?php
}
?>
Side note:
Stop using mysql_* becuase its deprecated and close in PHP 7. Use mysqli_* or PDO
You should pass data like this format:
$.ajax({name:value, name:value, ... })
i was found answer for this case
this js code use inside tag
<script type="text/javascript">
$(document).ready(function()
{
$("#kdp").blur(function() {
var idkategori = $(this).val();
if (idkategori != "")
{
$.ajax({
type:"post",
url:"getsubkat.php",
data:"id="+ idkategori,
success: function(data){
$("#name").html(data);
}
});
}
});
});
</script>
and this html
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">
User Code
</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="kpd" name="kdp" >
</div>
</div>
<div id="name">
</div>
and the php code are different page with js and html (getsubkat.php)
<?php
include ("components/inc/connection.php");
$id=$_POST['id'];
$query=mysql_query("SELECT name, address from tbl_user where user_code='".$id."'");
$data=mysql_fetch_array($query);
echo"<div class='form-group'>";
echo"<label for='inputEmail3' class='col-sm-2 control-label'>user name </label>";
echo"<div class='col-sm-10'>";
echo"<input type='text' class='form-control' value='$data[user_name]' readonly>";
echo"</div>";
echo"</div>";
echo"<div class='form-group'>";
echo"<label for='inputEmail3' class='col-sm-2 control-label'>user address</label>";
echo"<div class='col-sm-10'>";
echo"<input type='text' class='form-control' value='$data[user_address]' readonly>";
echo"</div>";
echo"</div>";
?>
You must use onkeydown, onkeyup, onpaste, or oninput event instead of onchange event.
Related
I have newsletter subscribe input in opencart website and when i input email and press subscribe it says "Email is not valid!: even thou it is.
So i cant use it since it doesnt take emails.
I used this theme and didnt change anything in the subscribe module,
you can scroll down to the footer and check how it behaves here: http://demopavothemes.com/pav_woosa/demo2/
Cant figure out what is the problem.
Heres the code of the module:
<div class="<?php echo $prefix; ?> newsletter-v1" id="newsletter_<?php echo $position.$module;?>">
<form id="formNewLestter" method="post" action="<?php echo $action; ?>" class="formNewLestter">
<div class="panel panel-v1">
<div class="panel-heading">
<h4 class="panel-title"><?php echo $objlang->get("entry_newsletter");?></h4>
</div>
<div class="panel-body">
<div class="input-group">
<input type="text" placeholder="Email Here ..." class="form-control email" <?php if(!isset($customer_email)): ?> <?php endif; ?> size="18" name="email">
<div class="input-group-btn pull-left">
<button type="submit" name="submitNewsletter" class="btn btn-primary icon-mail radius-6x"><?php echo $objlang->get("button_subscribe");?></button>
</div>
</div>
<input type="hidden" value="1" name="action">
<div class="valid space-top-10"></div>
</div>
<?php if (!empty($social)): ?>
<?php echo html_entity_decode( $social );?>
<?php endif ?>
</div>
</form>
</div>
<script type="text/javascript"><!--
$( document ).ready(function() {
var id = 'newsletter_<?php echo $position.$module;?>';
$('#'+id+' .box-heading').bind('click', function(){
$('#'+id).toggleClass('active');
});
$('#formNewLestter').on('submit', function() {
var email = $('.inputNew').val();
$(".success_inline, .warning_inline, .error").remove();
if(!isValidEmailAddress(email)) {
$('.valid').html("<div class=\"error alert alert-danger\"><?php echo $objlang->get('valid_email'); ?><button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button></div></div>");
$('.inputNew').focus();
return false;
}
var url = "<?php echo $action; ?>";
$.ajax({
type: "post",
url: url,
data: $("#formNewLestter").serialize(),
dataType: 'json',
success: function(json)
{
$(".success_inline, .warning_inline, .error").remove();
if (json['error']) {
$('.valid').html("<div class=\"warning_inline alert alert-danger\">"+json['error']+"<button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button></div>");
}
if (json['success']) {
$('.valid').html("<div class=\"success_inline alert alert-success\">"+json['success']+"<button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button></div>");
}
}
});
return false;
});
});
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
--></script>
This line:
$('.inputNew')
is looking for a class named inputNew. Your HTML doesn't have an element with that name. Your element it looks like has a class of email.
<input type="text" placeholder="Email Here ..." class="form-control email" <?php if(!isset($customer_email)): ?> <?php endif; ?> size="18" name="email">
^^^^^
You also could use the form-control but that doesn't sound unique. An id would be better or you could use the name attribute like this:
$('input[name="email"]')
so change the JS line to:
var email = $('.email').val();
or
var email = $('input[name="email"]').val();
You can read more about these here, https://api.jquery.com/category/selectors/.
I asked yesterday a similar question and i resolved the answer myself in which i wanted to add data into the database using ajax to avoid refreshing the page.
Now, i wish to do the same thing, but update the data in the database.
Im not sure if the issue is caused by having 2 ajax script requests on the same page..
I am trying to submit this form:
I should probably tell you, this form is in a modal screen
<form id="editarticleform" method="post">
<div class="form-group">
<input type="hidden" class="form-control" id="blog-id" name="blog-id" value="<?php echo $list['id']; ?>">
</div>
<div class="form-group">
<label for="blog-title">Article title</label>
<input type="text" class="form-control" id="blog-title" name="blog-title" placeholder="Blog title" value="<?php echo $list['blog_title']; ?>" required>
</div>
<div class="form-group">
<label for="blog-content">Article content</label>
<textarea class="form-control" id="blog-content" name="blog-content" placeholder="Blog content" required><?php echo $list['blog_body']; ?></textarea>
</div>
<div class="form-group">
<label for="exampleInputFile">Article image</label>
<input type="file" class="form-control-file" id="article-image" name="article-image" aria-describedby="fileHelp" value="<?php echo $list['blog_image']; ?>">
<small id="fileHelp" class="form-text text-muted">This is the image that will appear along side the article.</small>
</div>
<fieldset class="form-group">
<legend>Active</legend>
<div class="form-check">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="active-inactive" id="optionsRadios1" value="1" checked>
Article is active - Will be shown in the blog.
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="active-inactive" id="optionsRadios2" value="0">
Article is inactive - Will not show.
</label>
</div>
</fieldset>
<fieldset class="form-group">
<legend>Comments</legend>
<div class="form-check">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="enable-comments" id="enable-comments1" value="1" checked>
Enable comments - Users can post comments
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="enable-comments" id="enable-comments2" value="0" aria-describedby="disableComments">
Disable comments - Users cannot post comments
<small id="disableComments" class="form-text text-muted">If you disable comments for users, administrators will still be able to post comments.</small>
</label>
</div>
</fieldset>
<button type="submit" id="edit_article" name="edit_article" class="btn btn-primary">Save</button>
</form>
Updating the database using this script:
<?php
require_once("../../includes/database.class.php");
session_start();
$uid = $_SESSION['uid'];
$id = $_POST['blog-id'];
$title = $_POST['blog-title'];
$content = $_POST['blog-content'];
$image = $_POST['article-image'];
$active = $_POST['active-inactive'];
$comments = $_POST['enable-comments'];
$sql = "UPDATE blog_article SET blog_title = '$title', blog_body = '$content', blog_image = '$image', active = '$active', comments = '$comments' WHERE id = '$id'";
// print_r($sql);
$result = $database->query($sql);
if ($result) {
echo "Article updated.";
}else {
echo "Query failed" . print_r($sql);
}
?>
Via AJAX to avoid refreshing the page:
<script>
var submit = $('#edit_article');
submit.click(function() {
var data = $("#editarticleform").serialize();
var update_div = $('#update_div');
$.ajax({
data: data,
type: 'post',
url: '/editarticle.php',
success:function(html){
update_div.html(html);
}
});
});
</script>
As with the last question, the script works perfectly fine if i directly set the form action to the editarticle.php script. When i implement the ajax script, it doesn't update the database.
I am unsure if its got something to do with the blog-id, but thats what my head immediately thinks it is.. Or it may be that i am being blind and its a tiny little issue..
I suspect that the click event isn't triggered. Perhaps try something like this:
<script>
// Wait for document ready
$(function(){
$(document).on('click', '#edit_article', function() {
var data = $("#editarticleform").serialize();
var update_div = $('#update_div');
$.ajax({
data: data,
type: 'post',
url: '/editarticle.php',
success: function(html){
update_div.html(html);
}
});
});
});
</script>
Check the Network tab of your browser's developer tools to see that anything gets sent to the backend, and the request headers to see if all the necessary data is included.
I would do the following to debug;
Check what you are sending to the php file, to see if blog-id value is not empty. by doing var data = $("#editarticleform").serialize();
console.log(data);
Change your ajax url to url: 'editarticle.php' ,because it seems your ajax probably doesn't see the php file.
if you use modal bootstrap try this :
$('#myModal').on('shown.bs.modal', function () {
var submit = $('#edit_article');
submit.click(function () {
var data = $("#editarticleform").serialize();
var update_div = $('#update_div');
$.ajax({
data: data,
type: 'post',
url: '/editarticle.php',
success: function (html) {
update_div.html(html);
}
});
});
})
check this
<script>
// Wait for document ready
$(document).ready(function(){
$("#edit_article").click(function() {
var data = $("#editarticleform").serialize();
var update_div = $('#update_div');
$.ajax({
url: 'editarticle.php',
type: 'post',
data: data,
success: function(html){
update_div.html(html);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
});
});
</script>
If still doesn't work try to send raw data with ajax and check if it works
data: "blog-id="+blog-id
This code almost works, it inserts into the db and it is giving feedback on the page to say it has updated. However I am getting undefined index between lines 5-8 in the insert_message.php and my database is filling with blank entries (except the date).
Apologies for being new to jquery and AJAX. Need some help.
form
<form enctype='multipart/form-data' action='insert_message.php' method='POST' id='contact_form'>
<div class="row">
<div class="col-xs-6">
<div class='form-group'>
<label for='email'>Email:</label>
<input class='form-control' type='email' id='email' name='email' required='required' maxlength='35'/>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-6">
<div class='form-group'>
<label for='subject'>Subject:</label>
<input class='form-control' type='text' id='subject' name='subject' required='required' maxlength='35'/>
</div>
</div>
</div>
<div class="form-group">
<label for='message'>Message:</label>
<textarea class="form-control" placeholder="Message" id='message' required="required"></textarea>
</div>
<input type="hidden" name="reciever" id='receiver' value="Admin">
<input class='btn btn-primary' id='submit' type='submit' value='submit' >
</form>
<span id="result"></span>
jquery
<script>
$(document).ready(function(){
$("#submit").click( function(e) {
e.preventDefault();
var message1 = $('message').val();
var sender1 = $('sender').val();
var receiver1 = $('receiver').val();
var subject1 = $('subject').val();
$.post("insert_message.php", {message:message1, sender:sender1, receiver:receiver1, subject:subject1}, function(info) { $("#result").html(info);
});
clearInput();
});
$("#contact_form").submit( function() {
return false;
});
function clearInput() {
$("#contact_form :input").each( function() {
$(this).val('');
});
}
});
</script>
insert_message.php
<?php
include("connections/conn.php");
$getsubject = mysqli_escape_string($conn,$_POST["subject1"]);
$getmessage = mysqli_escape_string($conn,$_POST["message1"]);
$getsender = mysqli_escape_string($conn,$_POST["sender1"]);
$getreceiver = mysqli_escape_string($conn,$_POST["receiver1"]);
$date = date("Y-m-d");
$insertmessage = "INSERT INTO messages (id,subject,message,date,sender,receiver) VALUES (NULL,'$getsubject','$getmessage','$date','$getsender','$getreceiver')";
$insert = mysqli_query($conn, $insertmessage) ;
if($insert){
echo "Message Sent";
}else{
echo "Message did not send";
}
UPDATE
attempted alternative way but I still get the undefined index in the inser_message.php
$(document).ready(function(){
$("#submit").click( function(e) {
e.preventDefault();
$.ajax({
url: "insert_message.php",
type: "POST",
data: $("#contact_form").serialize(),
success: function(result){
$("#result").html(result);
}
});
});
});
You have several problems in both JS and PHP.
Adjust typo in input hidden where actually name="reciever" instead of name="receiver";
In your $("#submit").click() function you're trying to selecting elements with an invalid selector (e.g. $('message').val() instead of $("#message").val());
Adjust $_POST keys by removing 1 at end. If you have any doubt, print the whole array print_r($_POST);
This is not an error but a suggestion. Since you require conn.php to do your job, I would use require instead of include.
Remove the $conn and the 1's from your 'get' block and, for example:
$getsubject = mysqli_escape_string($_POST["subject"]);
$getmessage = mysqli_escape_string($_POST["message"]);
$getsender = mysqli_escape_string($_POST["sender"]);
$getreceiver = mysqli_escape_string($_POST["receiver"]);
I am working with a script wherein I should be able to submit a form without page reload with the help of AJAX. The problem is that the form is not submitted to the database. Any help would be appreciated. I had messed with the codes but nothing works for me.
Here is the javascript code:
<script type="text/javascript">
setInterval(function() {
$('#frame').load('chatitems.php');
}, 1);
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var usercontent = $("#username").val();
var namecontent = $("#nickname").val();
var dataString = 'content=' + textcontent;
var userString = 'content=' + usercontent;
var nameString = 'content=' + namecontent;
if (textcontent == '') {
alert("Enter some text..");
$("#content").focus();
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "chatitems.php",
data: {
dataString,
userString,
nameString
},
cache: true,
success: function(html) {
$("#show").after(html);
document.getElementById('content').value = '';
$("#flash").hide();
$("#frame").focus();
}
});
}
return false;
});
});
</script>
this is my form:
<form action="" method="post" name="form">
<input type="hidden" class="form-control" id="username" name="username" value="<?php echo $username; ?>" readOnly />
<input type="hidden" class="form-control" id="nickname" name="nickname" value="<?php echo $nickname; ?>" readOnly />
<input type="hidden" class="form-control" id="chat_role" name="chat_role" value="<?php echo $pm_chat; ?>" readOnly />
<input type="hidden" class="form-control" id="team" name="team" value="<?php echo $manager; ?>'s Team" readOnly />
<input type="hidden" class="form-control" id="avatar" name="avatar" value="<?php echo $avatar; ?>" readOnly />
<div class="input-group">
<input type="text" class="form-control" id="content" name="content" />
<span class="input-group-btn">
<input type="submit" name="submit" class="submit_button btn btn-primary" value="Post"></input>
</span>
</div>
</form>
and finally, this is my PHP code:
<?php
include('db.php');
$check = mysql_query("SELECT * FROM chat order by date desc");
if(isset($_POST['content']))
{
$content=mysql_real_escape_string($_POST['content']);
$nickname=mysql_real_escape_string($_POST['nickname']);
$username=mysql_real_escape_string($_POST['username']);
$ip=mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
mysql_query("insert into chat(message,ip,username,nickname) values ('$content','$ip','$username','$nickname')");
}
$req = mysql_query('select * from chat ORDER BY date desc');
while($dnn = mysql_fetch_array($req))
{
?>
<div class="showbox">
<p><?php echo $dnn['username']; ?> (<?php echo $dnn['ip']; ?>): <?php echo $dnn['message']; ?></p>
</div>
<?php
}
?>
I know there is something wrong with my code somewhere but had spent few days already but no avail. Im hoping that someone would help.
UPDATE
The form is being submitted successfully with this code only data: dataString but when I added the nameString and the userString thats when everything doesnt work as it should. I tried messing around that code but still got nothing.
To find out what is wrong with this you need to establish that:
a) The click event is firing, which you could test by adding a console.log('something'); at the top of that function.
b) The AJAX function is working somewhat correctly, which again you could check by adding a console.log() in the success callback of the AJAX request. You can also check console for errors, e.g if the chatitems.php is 404'ing
c) That all the data you're collecting from the DOM e.g var textcontent = $("#content").val(); contains what you're expecting it to. Again console.log().
d) That the page you're calling is successfully processing the data you're sending across, so die() a print_r() of the $_POST values to check the data it's receiving is in the format your expecting. You also need to add some error handling to your mysql code: https://secure.php.net/manual/en/function.mysql-error.php (or better yet use PDO or MySQLi https://secure.php.net/manual/en/book.pdo.php), which will tell you if there's something wrong with your MySQL code. You can check the return of you're AJAX call (which would include any errors) by console.log(html) in your success callback.
Information you gather from the above will lead you to your bug.
If i understand right, it seem you try to bind event before the button is available. Try (depend on the version of JQuery you use) :
$(document).on('click, '.submit_button', function(){
...
});
As always thanks in advance if you can help with this one.
I'm trying to use Ajax to call a script and post the form data at the same time. Everything works as expected except the $POST data which comes back blank when I try to echo or print it. Can anyone shine a light on what I have missed here please?
<form id="guestlist" name="guestlist">
<?php // Collect CLUBS data to pass to guestlist script ?>
<input type="hidden" name="gl_clubname" value="<?php echo $ptitle; ?>" />
<input type="hidden" name="gl_clubnumber" value="<?php echo $phoneno_meta_value; ?>" />
<input type="hidden" name="gl_clubemail" value="<?php echo $email_meta_value; ?>" />
<?php // Collect USERS data to pass to guestlist script ?>
<input type="hidden" name="gl_name" value="<?php echo $fullname;?>" />
<input type="hidden" name="gl_email" value="<?php echo $email;?>" />
<input type="hidden" name="gl_dob" value="<?php echo $birthday;?>" />
<input type="hidden" name="gl_propic" value="<?php echo $profile_url;?>" />
<div id="clubcontactleft">
<textarea id="clubmessage" name="gl_message" placeholder="Your message" rows="4" style="background-image:url('http://www.xxxxx.com/wp-content/themes/xxxxx/images/userreview.jpg');
background-repeat:no-repeat; padding-left:40px; background-size:40px 94px; width:250px; margin-bottom:15px;"></textarea>
<input type="text" name="gl_when" placeholder="Enquiry Date" style="background-image:url('http://www.xxxxx.com/wp-content/themes/xxxxx/images/calendaricon.jpg');
background-repeat:no-repeat; padding-left:40px; background-size:40px 38px; width:250px;">
<input type="text" name="gl_phonenumber" placeholder="Phone Number" style="background-image:url('http://www.xxxxx.com/wp-content/themes/xxxxx/images/phonecall.jpg');
background-repeat:no-repeat; padding-left:40px; background-size:40px 38px; width:250px;">
</div>
<div class="guestlistbutton">Send Message</div>
</form>
<script type="text/javascript">
$(document).ready(function($){
$(".guestlistbutton").on('click',function(event) {
event.preventDefault();
$("#clubcontactform").empty();
var url = "http://www.xxxxxx.com/wp-content/themes/xxxxxx/guestlist.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#guestlist").serialize(), // serializes the form's elements.
success: function(data)
{
$('#clubcontactform').append(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
Here is the php file that it pulls in
<?php
echo 'Pulling in guestlist.php<br/>';
$gl_message = $_POST['gl_message'];
print_r($gl_message);
echo $gl_message;
?>
Thanks!
Every thing seems to be correct only you forget to include the jquery file. please include and try once. If still persist the issue will create the Jsfiddle
I checked your code in my local machine and I got the following error "Caution provisional headers are shown". If you have the same message in your browser console, this information can help you: "CAUTION: provisional headers are shown" in Chrome debugger
Also, I see that js work perfectly. Problem in your url address. Try send your form to itself, just write html part and php part of code in one file.
<div>
<form id="Get_FRm_Data">
/*
Some field using.....
/*
</form>
<button type="button" name="submit" class="submit_act">Submit</button>
</div>
<script>
var file_pathname = window.location.protocol + "//" + location.host + "/foldername/";
$(document).on("click", ".submit_act", function ()
{
var $this_val=$(this);
$this_val.html("Loading...").prop("disabled",true);
var $data_ref = new FormData($("#Get_FRm_Data")[0]);
$data_ref.append("action", "fileaction_name");
$pathname = file_pathname + "filename.php";
$.ajax({
url: $pathname,
type: 'POST',
data: $data_ref,
cache: false,
contentType: false,
processData: false,
dataType: 'json',
success: function (result, status)
{
console.log(result);
if (status == "success")
{
$this_val.html("Submit").prop("disabled",false);
}
}
});
});
</script>
<?php
if (isset($_POST['action']))
{
$action = $_POST['action'];
if($action=="fileaction_name")
{
print_r($_POST);
}
}
?>