Ajax form set textbox value onsubmit - javascript

after submit the form using ajax i cant set the value on the multiple textbox correctly, here's my form
<form id="searchForm" action="process.php" method="post">
<input id="cust_code" name="cust_code" required>
<input id="cust_code1" name="cust_code1" disabled>
<input id="cust_name" name="cust_name" disabled>
<button type="submit">Search</button>
</form>
process.php
$cust_code = $_POST['cust_code'];
$result = mysql_query("SELECT code,cust_name FROM information WHERE code=$cust_code") or die(mysql_error());
$data = mysql_fetch_array($result);
javascript:
var formData = {
'cust_code': $('#cust_code').val()
};
$.ajax({
type : 'POST',
url : 'process.php',
data : formData,
dataType : 'json',
encode : true,
success: function(data) // recieved data from process.php
{
var code = data[0];
var cust_name = data[1];
// Update id value
document.getElementById('cust_code').value = code;
document.getElementById('cust_code1').value = code;
document.getElementById('cust_name').value = cust_name;
}
})
the value of cust_code and cust_code1 changed after submit, but not for cust_name
any ideas?
EDIT: the id's has been use on another page(php include) so that make the input wont change, solved!

You can assign value by this way also in JQuery:
document.getElementById('cust_code').val(code);
or
document.getElementById('cust_code').attr('value',code);

The same IDs have been used on another page(php include) so the input value won't change, changing the ID to cust_names seems to do the trick

Related

Why jQuery.ajax() is not sending any data?

Tell me please, there is a form for sending data to the database. Without a script it works fine, but nothing happens with the script. In the console — Form Data has all the data, and the 200th code arrives, but is not added to the database.
PHP:
<?php
$data = $_POST;
if (isset($data['add'])) {
$posts = R::dispense('posts');
$posts->head = $data['head'];
$posts->desc = $data['desc'];
R::store($posts);
}
?>
HTML:
<form method="POST" id="FormID">
<input type="text" name="head" required />
<input type="text" name="desc" required />
<button type="submit" name="add">Добавить</button>
JS:
<script>
$("#FormID").submit(function(e)
{
var form = $(this);
var url = form.attr('action');
e.preventDefault();
$.ajax({
type: "POST",
url: url,
data: $("#FormID").serialize(),
success: function(data)
{
c = "hello";
$('#FormStatus').text(c);
}
});
});
</script>
You said:
if (isset($data['add'])) {
So the code only does anything if add in the data.
<button type="submit" name="add">Добавить</button>
add is a submit button. It will be included in the data when you submit the form.
data: $("#FormID").serialize(),
You aren't submitting the form. jQuery serialize does not include submit buttons because they aren't successful controls when you aren't submitting the form.
Use some other mechanism to determine if there is data to process (such as the presence of head and desc.
You have forget the action for your form
Why don't simply use $data['name'] instead of R::dispense?
If you what to do a POST request why don't you use $.post()?
What you need is these:
PHP Code:
<?php
$data = $_POST;
if (isset($data['add'])) {
if(isset($data['head']) AND !empty($data['head']) AND isset($data['desc']) AND !empty($data['desc'])) {
$head = htmlspecialchars($data['head']);
$desc = htmlspecialchars($data['desc']);
echo "Hello from server";
}
else {
echo "Please fill the form";
}
}
?>
HTML:
<form method="POST" id="FormID" action="path_to_php_file.php">
<input type="text" name="head" required />
<input type="text" name="desc" required />
<button type="submit" name="add">Добавить</button>
</form>
JS:
<script>
$("#FormID").submit(function(e)
{
e.preventDefault();
var form = $(this),
url = form.attr('action');
var data = {};
// To have post paramaters like
// { 'head' : 'Head value', 'desc' : 'Desc value' }
$.each(form.serializeArray(), function(i, field) {
data[field.name] = field.value;
});
$.post(url, data, function(Responses) {
// Will write "Hello from server" in your console
console.log(Responses);
});
});
</script>

select one id jquery without repetition

i want to do system comment (as facebook) system simple but i don't know how to select one id for submit .
for first form correct ,but other form
always i get data-id the first form and comment_input empty .
code html
<form method="POST" class="form_add" data-id='<?php echo trim(htmlspecialchars($row['id_post'])); ?>'>
<input type="text" name="comment" class="comment_input" >
</form>
code jquery
$('.form_add').each(function(i){
$(this).attr('id','form_'+i);
$('#form_'+i).on('submit',function(e){
e.preventDefault();
var query = $('.comment_input').val();
var queryid = $(this).data('id');
$.ajax({
method : 'POST',
data : {commentPost:query,idpost:queryid},
url : 'traitementCommentPost.php',
success : function(data)
{
$('.fetch_all_comment').prepend(data) ;
}
});
});
});
code php
if($_SERVER['REQUEST_METHOD'] === 'POST')
{
if(isset($_POST['commentPost']) && !empty($_POST['commentPost']) )
{
$commentPost = (string) trim(htmlspecialchars($_POST['commentPost']));
$idpost = (int) trim(htmlspecialchars($_POST['idpost']));
$id_user = (int)trim(htmlspecialchars($_SESSION['user_id']));
$commentPostL = strlen($commentPost);
if($commentPostL <1 || $commentPostL > 200)
{
// ajouter plus du détails
}
else
{
if(preg_match("/^([\s*a-zA-Z0-9é\â\ô\î\'\û\-\+\.\=\/\?\!\:\;\[\]\,\_\(\)\'\%\ç\è\ê\#\Ω\<\>\x{0600}-\x{06FF}]+\s*)+$/u",$commentPost))
{
$stmt=$connect->prepare('INSERT INTO
comment_post(id_post,id_user,comment,date_comment)
VALUES(:a,:b,:c,NOW())');
$stmt->bindValue(':a',$idpost,PDO::PARAM_INT);
$stmt->bindValue(':b',$id_user,PDO::PARAM_INT);
$stmt->bindValue(':c',$commentPost,PDO::PARAM_STR);
$stmt->execute();
} // preg match
} // else
}}
for first form correct ,but other form
always i get data-id the first form and comment_input empty
I would simplify your code by storing the ID in an hidden input element.
<form method="POST" class="form_add">
<!-- name your inputs based on what you will be sending back -->
<input type="text" name="commentPost" class="comment_input" />
<input type="hidden" name="idpost" value="<?php echo trim(htmlspecialchars($row['id_post'])) ?>" />
</form>
Then use a delegated event handler as you are dynamically-creating elements. This will basically attach an event handler to existing and new elements added to the DOM.
Inside the handler, you can use .serialize() to get all the submitted values.
$(document).on('submit', '.form_add', function(e){
e.preventDefault();
$.ajax({
method: 'POST',
data: $(this).serialize(),
url: 'traitementCommentPost.php',
success : function(data) {
$('.fetch_all_comment').prepend(data) ;
}
});
// or shorter to just do
// $.post('traitementCommentPost.php', $(this).serialize(), function (data) { /* etc */ });
});

How to submit a form and get some text in return using Ajax

This is my Fiddle code:
$("form.signupform").submit(function(e) {
e.preventDefault();
var data = $(this).serialize();
var url = $(this).attr("action");
var form = $(this); // Add this line
$.post(url, data, function(data) {
$(form).children(".signupresult").html(data.signupresult);
$(form).children(".signupresult").css("opacity", "1");
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form class="signupform" method="post" action="admin/signupinsert.php">
<p class="signupresult"></p>
<input type="text" name="firstname" />
<input type="submit" value="Sign Up"/>
</form>
Signupinsert.php page code:
// Code to insert data into Database
$signupresult = "Some value here";
$response = new \stdClass();
$response->signupresult = $signupresult;
header('Content-Type: application/json');
print json_encode($response);
Expected Result:
When user clicks on submit form button, the code runs in background. And submits the form without reloading the page.
And the signupinsert.php page return some text, and its text display on a paragraph with class signupresult.
And the form can be submitted unlimited times, without reloading the page.
Problem:
The form only gets submitted once. If I try to submit it twice, "Nothing Happens" (No values inserted into database, no value returned in paragraph with class signupresult.
Where is the problem?
You have to tell your request that you expect JSON as return. Else data.signupresult doesn't make sense; data is seen as a string.
I always use $.ajax, never $.post; I find it easier to add options.
$.ajax({
url: $(this).attr("action"),
dataType: 'JSON',
type: 'post',
data: $(this).serialize(),
success: function(data) {
...
}
})

Ajax: form data not passing on to e-mail

This is my form:
<form id='forma' action="index1.php" method="post">
<input name="name1" type="text">
<input class="s_submit" value="ЗАКАЗАТЬ" type="button" onclick="send1()">
</form>
This is my javascript:
function send1(){
$('#forma').submit(function(event){
var formData = {
'fio' : $('input[name=name1]').val(),
};
$.ajax({
type : 'post',
url : 'index1.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
}
This is my index1.php:
$fio=$_POST['name1'];
$mail_to="_______my_email_________";
$msg="Your name is: $fio
mail($mail_to, $thm, $msg, $headers);
On my e-mail only "Your name is:" message is sent, without the name someone submitted. Code works as expected when I set input type to submit and get rid entirely of send1() function. But input must be the button type and never go to another page on press. I suppose I should get rid of some of variable assignments, but which ones?
Your variable in the POST data is defined in formData object with the key of fio. Your PHP to retrieve it should therefore be:
$fio = $_POST['fio'];
On the form submission, you are overriding the actual form (containing your text field) from being submitted, and submitting your own formData object.
You can quite easily get the data from your HTML form by using
$("#forma").serializeArray()

flask ajax/jquery form submission

So I have this code below.
This is my jquery/ajax script
$(function() {
$(".reply").click(function(){
var id = $(this).attr("id");
var element = ".comment_replies#" + id;
$(element).show();
$(".submit_reply#" + id).click( function(event) {
event.preventDefault();
var reply_box = ".reply_box#" + id
var data = $(reply_box).val
$.ajax({
type : "POST",
url : "{{url_for('main.HomePage')}}",
data: JSON.stringify(data, null, '\t'),
contentType: 'application/json;charset=UTF-8',
success: function(result) {
console.log(result);
console.log(data)}
})
})
})
})
here is the form:
<form class = "reply_form" action="#" method="post">
<input class = "reply_box" type="text" placeholder ="write a reply" name="reply" id = "{{'id_' +com.id|string}}">
<input type="submit" class = "submit_reply" value = "reply" id = "{{'id_' +com.id|string}}">
<input type="hidden" value="{{com.id}}" name = "form_id">
</form>
and if I do:
if request.json["data"] in my HomePage view it somehow doesn't pass
because usually i'd just go if request.form when submitting the form the usual way. here is my homepage view
if request.json["data"] and request.method == "POST":
return request.json["data"]
it's only a test to see if it return what I want it too and it fails.
am I suppose to have extra imports for json? because I don't have any.
I also see this error on firebug:
POST http://127.0.0.1:5000/homepage
400 BAD REQUEST
11ms
I could submit the form the usual way but I wanna try submitting the form and appending the info without a page refresh.

Categories