jQuery grabbing wrong form when using ajax - javascript

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

Related

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

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
});;

Trying to display PHP echo in HTML with JSON

I'm trying to display two PHP echo messages from a seperate PHP file onto my HTML body page. Whenever you click the submit button the echo message should popup in the HTML page without redirecting me to the PHP page.
I need to connect to my two files through Javascript so I wrote a script attemtping to connect the HTML file with the PHP file.
My HTML:
<div id="formdiv">
<form action="phpfile.php" method="get" name="fillinform" id="fillinform" class="js-php">
<input id="fillintext" name="fill" type="text" />
<input type="submit" id="submit1" name="submit1">
</form>
</div>
phpfile.php:
$q = $_GET['fill'];
$y = 2;
$work = $q * $y;
$bork = $work * $q;
echo json_encode($work) ."<br>";
echo json_encode($bork);
Javascript:
$(".js-php").submit(function()
var data = {
"fill"
};
data = $(this).serialize() + $.param(data);
$.ajax({
type:"GET",
datatype:"json",
url:"phpfile.php",
data: data,
success: function (data){
$(".formdiv").html(
""
"Your input: ")
}
You attached your logic to .submit() event and if you don't prevent default action, the form will be submitted to server. You can prevent it that way:
$(".js-php").submit(function(e) {
// your code goes here
e.preventDefault();
});
You'll have to append the data to your div like this:
success: function (data) {
$(".formDiv").append("Your input: " + data);
}
As per your html you should try this below code :
If you want to replace the whole html inside the div having id="formdiv"
success: function (data){
$("#formdiv").html("Your input: "+data)
}
or
success: function (data){
$("#formdiv").text("Your input: "+data)
}
If you want to append data to the div having id="formdiv"
success: function (data){
$("#formdiv").append("Your input: "+data)
}
Add curly braces after $(".js-php").submit(function(e) and close it after your ajax ends.
Add e.preventDefault() before you call ajax so it will not redirect
you to phpfile.php
Add alert(data) inside your function called at success of ajax.
there is a syntax error n line $(".formdiv").html("""Your input: ");
Your updated code should look like.
$(".js-php").submit(function(e){
var data = {
"fill"
};
data = $(this).serialize() + $.param(data);
$.ajax({
type:"GET",
datatype:"json",
url:"phpfile.php",
data: data,
success: function (data){
alert(data);
}
}

How do i send parameter in ajax function call in jquery

I'm creating an online exam application in PHP and am having trouble with the AJAX calls.
I want the questions to be fetched (and used to populate a div) using an AJAX call when one of the buttons on the right are clicked. These buttons are not static; they are generated on the server (using PHP).
I'm looking for an AJAX call to be something like this:
functionname=myfunction(some_id){
ajax code
success:
html to question output div
}
and the button should call a function like this:
<button class="abc" onclick="myfunction(<?php echo $question->q_id ?>)">
Please suggest an AJAX call that would make this work
HTML
<button class="abc" questionId="<?php echo $question->q_id ?>">
Script
$('.abc').click(function () {
var qID = $(this).attr('questionId');
$.ajax({
type: "POST",
url: "questions.php", //Your required php page
data: "id=" + qID, //pass your required data here
success: function (response) { //You obtain the response that you echo from your controller
$('#Listbox').html(response); //The response is being printed inside the Listbox div that should have in your html page. Here you will have the content of $questions variable available
},
error: function () {
alert("Failed to get the members");
}
});
})
The type variable tells the browser the type of call you want to make to your PHP document. You can choose GET or POST here just as if you were working with a form.
data is the information that will get passed onto your form.
success is what jQuery will do if the call to the PHP file is successful.
More on ajax here
PHP
$id = gethostbyname($_POST['id']);
//$questions= query to get the data from the database based on id
return $questions;
You are doing it the wrong way. jQuery has in-built operators for stuff like this.
Firstly, when you generate the buttons, I'd suggest you create them like this:
<button id="abc" data-question-id="<?php echo $question->q_id; ?>">
Now create a listener/bind on the button:
jQuery(document).on('click', 'button#abc', function(e){
e.preventDefault();
var q_id = jQuery(this).data('question-id'); // the id
// run the ajax here.
});
I would suggest you have something like this to generate the buttons:
<button class="question" data-qid="<?php echo $question->q_id ?>">
And your event listener would be something like the following:
$( "button.question" ).click(function(e) {
var button = $(e.target);
var questionID = button.data('qid');
var url = "http://somewhere.com";
$.ajax({ method: "GET", url: url, success: function(data) {
$("div#question-container").html(data);
});
});

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