load form using ajax then again submit using ajax - javascript

I have a page where I'm displaying some information. You can select a option and the page will then display a form by loading the form using ajax response:
$("body").on("change", "#patient_id", function(event){
var prescription_id = $(this).val();
event.preventDefault(); // disable normal link function so that it doesn't refresh the page
var curr_data = {
action: 'refferedcall',
prescription_id: prescription_id,
dataType: 'json'
};
$.post(hmgt.ajax, curr_data, function(response) {
$('.prescription_content').html(response);
return true;
});
});
This works fine. But this view is a form. I want to then submit the included form with Ajax as well. But I can't seem to do it. I think it is because if I set up a button handler for the form it doesn't work as the form isn't present when the main page and JQuery script is loaded.
So to be clear, I'm loading this div onto my main page using JQuery and Ajax load. I then want to simply submit this form with Ajax also.
<div class="prescription_content">
<div class="title">Submit News</div>
<form role="form" id="ref_form" name="ref_form_p">
<div class="form-group">
<label for="pat_ref_hosp">Hospital to Refer:</label>
<input type="text" class="form-control" id="pat_ref_hosp" name="pat_ref_hosp" value="<?php if(!empty($result->reffer_hospital)){ echo $result->reffer_hospital; }?>">
</div>
<input type="hidden" class="form-control" id="pres_note" name="pres_note" value="<?php echo $result->priscription_id ;?>">
<button type="button" id="<?php echo $result->priscription_id ;?>" class="btn btn-success reffering_status">Refer Now</button>
</form>
</div>
TIA
Then I submitted form again using ajax through below button click event:
$("body").on("click", ".reffering_status", function(event){
event.preventDefault(); // disable normal link function so that it doesn't refresh the page
var prescription_id = $("#pres_note").val();
var pat_ref_hosp = $("#pat_ref_hosp").val();
var curr_data = {
action: 'reffering_status',
dataType: 'json',
prescription_id: prescription_id,
pat_ref_hosp : pat_ref_hosp,
};
console.log(curr_data);
)};
Here is log displaying
Object {action: "reffering_status", dataType: "json", prescription_id: "1", pat_ref_hosp: ""}
pat_ref_hosp is empty
I don't know how to display ajax in jsfiddle
https://jsfiddle.net/3ggq3Ldm/

Yes the way you are doing it will not work because the contents of the DIV you are loading-in is not loaded into the DOM when your initial
$("body").on("click", ".reffering_status", function(event){});
call is made.
If I am understanding you correctly, this is the behaviour you want to achieve:
$("#patient_id").on("change", function(event) {
var prescription_id = $(this).val();
event.preventDefault(); // disable normal link function so that it doesn't refresh the page
var curr_data = {
action: 'refferedcall',
prescription_id: prescription_id,
dataType: 'json'
};
$.post(hmgt.ajax, curr_data, function(response) {
$(".prescription_content").html(response);
$(".reffering_status").on("click", function(event){
event.preventDefault(); // disable normal link function so that it doesn't refresh the page
var prescription_id = $("#pres_note").val();
var pat_ref_hosp = $("#pat_ref_hosp").val();
var curr_data = {
action: 'reffering_status',
dataType: 'json',
prescription_id: prescription_id,
pat_ref_hosp : pat_ref_hosp
};
console.log(curr_data);
)};
return true;
});
});
You simply need to run the code that attaches your click listener AFTER the DOM has already been updated with the new information.
Please let me know if this code does what you were intending it to.

Related

Submit the form inside jquery dialog box without reloading page

I have php page with a form, I want to open it in a dialog box and submit and show the data on same dialog without reloading the page
php
<form accept-charset="UTF-8">
<button type="submit" class="addButtonClass"></button>
please advice
$('.addButtonClass').submit(function (event) {
event.preventDefault();
....
.. Now your usual ajax post
}
Modify this
$('#add_user1').submit(function(e){
e.preventDefault(); //** prevent normal form submission and page reload
$.ajax({
type: "POST",
cache: false,
url: $link,
data: $('#add_user1').serializeArray(),
success: function (data) {
var json_obj = $.parseJSON(data);
var result = json_obj['result'];
var usergroup = json_obj['usergroup'];
var success = json_obj['success'];
var errorAry = {
}
}
});
return false;
});

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

Button and AJAX not responding

Im working on trying to get a button to run a php script with AJAX. To be clear I am really new to javaScript and PHP so my code might be completely wrong. I think that the problem is in my button click code not so much the ajax code. Any help is great
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(".submit").click(function myCall() {
var subdata = $("#form").serializeArray();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata
});
return false;
});
</script>
<div>
<form id="form">
Name of Product: <input type="text" name="productName" value="Enter Here">
<input type="button" name="submit" value="Submit" class="submit">
</form>
</div>
You need a DOM ready wrapper around the jQuery because it executes before the element exists (or is rendered by the browser).
You can use either $(function(){ }) or $(document).ready(function(){ });.
$(function(){
$(".submit").click(function myCall() {
var subdata = $("#form").serializeArray();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata
});
return false;
});
});
In this case, you don't need serializeArray() but simply serialize().
There is no success or complete function defined and so you wouldn't see anything when submitting this, unless of course you watch the developer console/net tab.
Also, using a form's submit event is preferred to the submit button's click event.
$(function(){
$("#form").submit(function myCall() {
var subdata = $(this).serialize();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata,
success : function(response){
console.log("success!");
}
});
return false;
});
});
Put your jQuery inside a document ready like this, and prevent the default action (to submit the form):
<script type="text/javascript">
$(document).ready(function(){
$(".submit").click(function(e) {
e.preventDefault();
var subdata = $("#form").serializeArray();
$.get("construct_new.php",{data: subdata}, function(){
console.log(data); // whatever returned by php
});
});
});
</script>
Document ready makes sure page has finished loading everything. e.preventDefault() stops the default action (for a form, submission, for an a tag, following the link).

jquery event (on submit) is affecting all my divs and not the only one where the button was clicked?

what's up guys? look... I have a comment system for my web page... and I've been dealing with this little problem for a entire week. I really need some help here x_x ... the thing is that when a user leave a comment on my page, this comment is showed automatically thanks to ajax, that's ok...
each comment can be voted. and here's my problem... these divs that contain the forms for voting are build dynamically and the thing is that when I do click on the button for sending the form in any comment... the resulting data appears in all the comments! instead of appear in the specific one where the submit button was clicked, so I don't know what to do at this point, I hope you can give me a hand. this is my code
the form:
<label > Vote </label>
<form action="vote.php" method="POST" class="form-vote" id="form-vote">
<button class="icon-thumbs-up" id="icon-thumbs-up"></button>
<input hidden="hidden" type="text" name="num-comment" id="num-comment" value="'.$d['id'].'" >
<input hidden="hidden" type="text" name="point" id="point" value="'.$d['point'].'" >
<p id="actual-points" class="actual-points"> '.$d['point'].'</p>
<div id="result" class="result"> </div>
</form>
the script:
<script type="text/javascript">
$(document).ready function() {
$('.form-vote')on('submit', function() {
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data) {
$('.actual-points').hide();
$('.result').html(data).fadeIn('slow');
}
})
return false;
});
})
</script>
Have you tried saving the 'this' object of the original event and using it inside the success function like this:
$('.form-vote')on('submit', function(e) {
e.preventDefault();
var $form = $(this); // Save here
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data) {
// use here
$form.find('.actual-points').hide();
$form.find('.result').html(data).fadeIn('slow');
}
})
return false;
});
change this:
$('.result').html(data).fadeIn('slow');
to this:
$(this).find('.result').html(data).fadeIn('slow');

using jquery to make ajax call and update element on form submit

Here is my html form
<div id=create>
<form action=index.php method=get id=createform>
<input type=text name=urlbox class=urlbox>
<input type=submit id=createurl class=button value=go>
</form>
</div>
<div id=box>
<input type=text id=generated value="your url will appear here">
</div>
Here is the javascript im trying to use to accomplish this;
$(function () {
$("#createurl").click(function () {
var urlbox = $(".urlbox").val();
var dataString = 'url=' + urlbox;
if (urlbox == '') {
alert('Must Enter a URL');
}else{
$("#generated").html('one moment...');
$.ajax({
type: "GET",
url: "api-create.php",
data: dataString,
cache: false,
success: function (html) {
$("#generated").prepend(html);
}
});
}return false;
});
});
when i click the submit button, nothing happens, no errors, and the return data from api-create.php isnt shown.
the idea is that the new data from that php file will replace the value of the textbox in the #box div.
i am using google's jquery, and the php file works when manually doing the get request, so ive narrowed it down to this
Because you're binding to the submit click instead of the form's submit.. try this instead:
$('#createForm').submit(function() {
// your function stuff...
return false; // don't submit the form
});
Dan's answer should fix it.
However, if #createurl is not a submit/input button, and is a link styled with css etc., you can do this:
$('#createurl').click(function () {
$('#createForm').submit();
});
$('#createForm').submit(function () {
// all your function calls upon submit
});
There is great jQuery plugin called jQuery Form Plugin. All you have to do is just:
$('#createform').ajaxForm(
target: '#generated'
});

Categories