How to pass javascript variable in .html() to php - javascript

I am adding a text area on click of a particular div. It has <form> with textarea. I want to send the jquery variable to my php page when this submit button is pressed. How can this be achievable. I am confused alot with this . Being new to jquery dizzes me for now. Here is my code,
`
<script type="text/javascript">
$(document).ready(function(){
$('.click_notes').on('click',function(){
var tid = $(this).data('question-id');
$(this).closest('ul').find('.demo').html("<div class='comment_form'><form action='submit.php' method='post'><textarea cols ='50' class='span10' name='notes' rows='6'></textarea><br><input class='btn btn-primary' name= 'submit_notes' type='submit' value='Add Notes'><input type='hidden' name='submitValue' value='"+tid+"' /></form><br></div>");
});
});
</script>`

Your code works fine in the fiddle I created here -> https://jsfiddle.net/xe2Lhkpc/
use the name of the inputs as key of $_POST array to get their values.
if(isset($_POST['submitValue'])) { $qid = $_POST['submitValue']; }
if(isset($_POST['notes'])) { $notes = $_POST['notes']; }

You should send your data after form submitted, something like this
:
$(".comment_form form").submit(function(e) {
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
you can assign event after insert your form.
// handling with the promise
$(this).closest('ul').find('.demo').html("<div class='comment_form'><form action='submit.php' method='post'></form><br></div>").promise().done(function () {
// your ajax call
});;

Related

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) {
...
}
})

How do i submit a hidden form using ajax when the page loads?

How can i submit a hidden form to php using ajax when the page loads?
I have a form with one hidden value which i want to submit without refreshing the page or any response message from the server. How can implement this in ajax? This is my form. I also have another form in the same page.
<form id = "ID_form" action = "validate.php" method = "post">
<input type = "hidden" name = "task_id" id = "task_id" value = <?php echo $_GET['task_id'];?>>
</form>
similar to Zafar's answer using jQuery
actually one of the examples on the jquery site https://api.jquery.com/jquery.post/
$(document).ready(function() {
$.post("validate.php", $("#ID_form").serialize());
});
you can .done(), .fail(), and .always() if you want to do anything with the response which you said you did not want.
in pure javascript
body.onload = function() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","validate.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("task_id=" + document.getElementById("task_id").value);
};
I think you have doubts invoking ajax submit at page load. Try doing this -
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
"url": "validate.php",
"type": "post"
"data": {"task_id": $("#task_id").val();},
"success": function(){
// do some action here
}
})
})
</script>
If you're using jQuery you should be able to get the form and then call submit() on it.
E.g.:
var $idForm = $('#ID_form');
$idForm.submit();
Simple solution - jQuery AJAX post the value as others have suggested, but embed the PHP value directly. If you have multiple forms, you can add more key:value pairs as needed. Add a success/error handler if needed.
<script type="text/javascript">
$(document).ready(function(){
$.post( "validate.php", { task_id: "<?=$_GET['task_id']?>" } );
})
</script>
As others have said, no need for a form if you want to send the data in the background.
validate.php
<?php
$task_id = $_POST['task_id'];
//perform tasks//
$send = ['received:' => $task_id]; //json format//
echo json_encode($send);
JQuery/AJAX:
$(function() { //execute code when DOM is ready (page load)//
var $task = $("#task_id").val(); //store hidden value//
$.ajax({
url: "validate.php", //location to send data//
type: "post",
data: {task_id: $task},
dataType: "json", //specify json format//
success: function(data){
console.log(data.received); //use data received from PHP//
}
});
});
HTML:
<input type="hidden" name="task_id" id="task_id" value=<?= $_GET['task_id'] ?>>

jQuery grabbing wrong form when using ajax

I have a php function that loops thru matches in a database, inside the loop, there is a form that gets returned to the page where the function is called:
while($row=mysql_fetch_array($get_unconfirmed))
{
echo "<form name='confirm_appointment' method='post' class='confirm_appointment'>";
echo "<input type='hidden' name='app_id' value='$appointment_id'>";
echo "<input type='hidden' name='clinic_id' value='$clinic_id'>";
echo "<td><input type='submit' class='update_appointment_button' value='$appointment_id'></td>";
echo "</form>";
}
Then I have jQuery to submit the form:
$( document ).ready(function() {
$(".update_appointment_button").click(function(){
var url = "ajax/update_appointment_status.php";
$.ajax({
type: "POST",
url: url,
data: $(".confirm_appointment").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
});
But the issue is, the way its set up, no matter what row I push "submit" for - I always get the values from the last row (form).
So I know the issue, I am not telling jQuery to get the values from the form with the button thats pushed. I need to somehow use .this maybe, but just cant seem to figure out the correct syntax.
Any help would be appricated!
You can access its parent form like this
data: $(this).closest(".confirm_appointment").serialize(),
or something like this
data: $this.parent().parent().serialize(),
Another way: replace the button click event by the form submit event.
$(document).ready(function () {
$('.confirm_appointment').submit(function (e) {
e.preventDefault();
var url = "ajax/update_appointment_status.php";
var serialized = $(this).serialize();
$.ajax({
type: "POST",
url: url,
data: serialized,
success: function (data) {
alert(data); // show response from the php script.
}
});
});
});
JSFiddle demo

Hide button inside a table after form submit?

So, I'm trying to make a row containing a delete button to .hide after pressing delete.
The problem is.. The delete button submits a form, I can't pre-define my button class/ID because it's beeing echo'd multiple times (php script reads a dir, then puts all files in a table)
this is the current script, It does post the form in the background, But it doesn't hide the element, I tried some stuff myself but the script then ended up hiding all the buttons on the page or it won't work at all..
The button beeing echo'd:
echo "<input type='submit' value='delete' name='submit'>";
The Script behind it:
$("#delform").submit(function() {
var url = "../../setdel.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#delform").serialize(), // serializes the form's elements.
success: function(data)
{
// location.reload(); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
Catch the button's onclick instead of catching the submission. Example:
echo "<input type='submit' value='delete' name='delete' class='trigger_delete'>";
// ^^ don't name your buttons as submit
// it will conflict to .submit() method
The on JS:
$('.trigger_delete').on('click', function(e){
e.preventDefault(); // prevent triggering submit
var url = "../../setdel.php";
$.ajax({
type: 'POST',
url: url,
data: $("#delform").serialize(),
success: function(response) {
console.log(response);
$(e.target).closest('tr').hide(); // or .fadeOut();
}(e) // <--- this one
});
});

How to prevent jQuery ajax submit form on page

I have two ajax calls on a page. There are text inputs for searching or for returning a result.
The page has several non ajax inputs and the ajax text input is within this . Whenever I hit enter -- to return the ajax call the form submits and refreshes the page prematurely. How do I prevent the ajax from submitting the form when enter is pressed on these inputs? It should just get the results.
However, I cannot do the jquery key press because it needs to run the ajax even if the user tabs to another field. Basically I need this to not submit the full form on the page before the user can even get the ajax results. I read return false would fix this but it has not.
Here is the javascript:
<script type="text/javascript">
$(function() {
$("[id^='product-search']").change(function() {
var myClass = $(this).attr("class");
// getting the value that user typed
var searchString = $("#product-search" + myClass).val();
// forming the queryString
var data = 'productSearch='+ searchString + '&formID=' + myClass;
// if searchString is not empty
if(searchString) {
// ajax call
$.ajax({
type: "POST",
url: "<?php echo $path ?>ajax/product_search.php",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#results" + myClass).html('');
$("#searchresults" + myClass).show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results" + myClass).show();
$("#results" + myClass).append(html);
}
});
}
return false;
});
$("[id^='inventory-ESN-']").change(function() {
var arr = [<?php
$j = 1;
foreach($checkESNArray as $value){
echo "'$value'";
if(count($checkESNArray) != $j)
echo ", ";
$j++;
}
?>];
var carrier = $(this).attr("class");
var idVersion = $(this).attr("id");
if($.inArray(carrier,arr) > -1) {
// getting the value that user typed
var checkESN = $("#inventory-ESN-" + idVersion).val();
// forming the queryString
var data = 'checkESN='+ checkESN + '&carrier=' + carrier;
// if checkESN is not empty
if(checkESN) {
// ajax call
$.ajax({
type: "POST",
url: "<?php echo $path ?>ajax/checkESN.php",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#esnResults" + idVersion).html('');
},
success: function(html){ // this happens after we get results
$("#esnResults" + idVersion).show();
$("#esnResults" + idVersion).append(html);
}
});
}
}
return false;
});
});
</script>
I would suggest you to bind that ajax call to the submit event of the form and return false at the end, this will prevent triggering default submit function by the browser and only your ajax call will be executed.
UPDATE
I don't know the structure of your HTML, so I will add just a dummy example to make it clear. Let's say we have some form (I guess you have such a form, which submission you tries to prevent)
HTML:
<form id="myForm">
<input id="searchQuery" name="search" />
</form>
JavaScript:
$("#myForm").submit({
// this will preform necessary ajax call and other stuff
productSearch(); // I would suggest also to remove that functionality from
// change event listener and make a separate function to avoid duplicating code
return false;
});
this code will run every time when the form is trying to be submitted (especially when user hits Enter key in the input), will perform necessary ajax call and will return false preventing in that way the for submission.

Categories