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).
Related
I've small JS code which is not working as per my need.
Actually my backend PHP code contains so many functions which i want to process by pressing submit button and meantime i also want to show the status "Scanning" in place of submit button and when the data got fully processed, then i want to show "Completed" Status in place of submit button.
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function () {
$(#response).show();
$(#form).hide();
}
});
});
});
</script>
You can simply show whatever you want when user clicks the button. And when you get the response you can change to whatever you want. Something like.
This is just an example of mocking your ajax request.
var $button = $("#btn");
$button.click(function() {
$button.text("Scanning...");
var promise = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('foo');
}, 5000);
});
promise.then(function(){
$button.text("Done");
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn"> Submit </button>
You can use beforeSend...
beforeSend is a pre-request callback function that can be used to modify the jqXHR..
You can refer here for more detail.
And you can follow my code below for your ease.
..
Javascript:
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
let submitBtnEl = $(this).find('button[type="submit"]'); //submit button element
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
beforeSend: function( xhr ) {
submitBtnEl.html('Scanning'); //the submit button text will change after click submit
},
success: function () {
$(#response).show();
$(#form).hide();
submitBtnEl.html('Completed'); //the submit button text will change after the form is completely submit
}
});
});
});
</script>
.
.
HTML:
<form>
<input type="text" name="input1" />
<button type="submit">Submit</button>
</form>
.
.
For your ease, you can try the code on this fiddle
I am using a django form with ajax using this code:
<form id="form-id">
<p> Search : <input name="{{ form.query.html_name }}" value="{{ form.query.value }}" type="search" id="form-input-id" autofocus onfocus="var temp_value=this.value; this.value=''; this.value=temp_value">
</p>
</form>
and the Javascript code:
$( document ).ready(function() {
$('#form-id').on('change', function() {
this.submit();
})
$('#form-id').on('submit', function(evt) {
evt.preventDefault();
var form = evt.target;
$.ajax({
url: form.action,
data: $(form).serialize(),
success: function(data) {
$('.results').html(data);
}
});
});
});
But here is the thing, everytime the submit event is triggered, I feel like the whole page is reloaded (it blinks). What could I do to prevent this from happening?
Your change event is submitting your form and page refreshes. Delete it and add change event to second function, where you're currently waiting for submit event.
$('#form-id').on('change', function(evt) {
var form = evt.target;
$.ajax({
url: form.action,
data: $(form).serialize(),
success: function(data) {
$('.results').html(data);
}
});
});
To prevent submit on enter, add keypress event to function and detect when enter is pressed. Like this:
$('#form-id').on('change keypress', function(evt) {
var key = evt.which;
if (key == 13) {
return false;
} else {
var form = evt.target;
$.ajax({
url: form.action,
data: $(form).serialize(),
success: function(data) {
$('.results').html(data);
}
});
}
});
Key number 13 is enter. When it's pressed, nothing is returned. You could have also replaced return false with evt.preventDefault(). And for other keys, Ajax will be triggered.
What if you add:
return false;
To your code, like so:
$( document ).ready(function() {
$('#form-id').on('change', function() {
this.submit();
})
$('#form-id').on('submit', function(evt) {
evt.preventDefault();
var form = evt.target;
$.ajax({
url: form.action,
data: $(form).serialize(),
success: function(data) {
$('.results').html(data);
}
});
return false;
});
});
Got this from:
https://simpleisbetterthancomplex.com/tutorial/2016/11/15/how-to-implement-a-crud-using-ajax-and-json.html
A very important detail here: in the end of the function we are
returning false. That’s because we are capturing the form submission
event. So to avoid the browser to perform a full HTTP POST to the
server, we cancel the default behavior returning false in the
function.
How I specify my form in html / django template:
<form id="form-id" action="required-url-goes-here" method="post">
<p> Search : <input name="{{ form.query.html_name }}" value="{{ form.query.value }}" type="search" id="form-input-id" autofocus onfocus="var temp_value=this.value; this.value=''; this.value=temp_value">
</p>
</form>
The tutorial I pointed to above works in a different way then you do. It specifies, inside the ajax request:
- url
- type
- data
- dataType
It also uses a different way to reference the form, and it is the only way I know, so I can't judge if there is an error in the rest of your code.
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.
I am submitting a form like this:
<input id="submitBtn" style="margin-top:20px;" type="button" onclick="document.getElementById('form94').submit();" value="Opdater">
That for some reason doesn't trigger my jQuery .submit() function.
$("#form94").submit(function() {
var form = $(this);
$.ajax({
url : form.attr('action'),
type : form.attr('method'),
data : form.serialize(), // data to be submitted
success: function(response){
$("#showFancyBoxThankYouLink").click();
}
});
return false;
});
Because you use different selectors
document.getElementById('form94'); //returns a HTML DOM Object
$('#form94'); //returns a jQuery Object
You can try next code, it works fine
<form id="form94">
<input id="submitBtn" style="margin-top:20px;" type="button" onclick="$('#form94').submit();" value="Opdater">
</form>
<script type="text/javascript">
$("#form94").submit(function(e) {
e.preventDefault();
alert('test');
});
make a function out of it and trigger it with onclick like this:
<input id="submitBtn" style="margin-top:20px;" type="button" onclick="myfunction()" value="Opdater">
function myfunction() {
var form = $(this);
$.ajax({
url : form.attr('action'),
type : form.attr('method'),
data : form.serialize(), // data to be submitted
success: function(response){
$("#showFancyBoxThankYouLink").click();
}
});
return false;
}
Is the javascript running after the form has been rendered? If not, either make sure that your javascript is after the form or try to have it run after the document has loaded.
$(document).ready(function() {
$("#form94").submit(function() {
var form = $(this);
$.ajax({
url : form.attr('action'),
type : form.attr('method'),
data : form.serialize(), // data to be submitted
success: function(response){
$("#showFancyBoxThankYouLink").click();
}
});
return false;
});
});
Another way to go about having the form submit is to add the onsubmit attribute to your form and have it return a function. You could also change your button type to submit and remove the onclick attribute.
<form id="form94" name="form94" onsubmit="return SubmitMyForm();">
<input type="submit" value="Opdater">
</form>
<script>
function SubmitMyForm() {
var form = $(this);
$.ajax({
url : form.attr('action'),
type : form.attr('method'),
data : form.serialize(), // data to be submitted
success: function(response){
$("#showFancyBoxThankYouLink").click();
}
});
return false;
}
</script>
Without a code example, it is hard to tell. But also, some browsers only submit a form when a user clicks a submit button, you cannot submit via script.
There are also a ton of other SO posts around this topic and they all either boil down to the form not existing when the submit event is attached (is your script executing at the top of the document or on the document's ready event?).
Form doesn't exist yet:
Why Jquery form submit event not firing?
Jquery .Submit() is not triggering submit event
Submitting via script:
Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?
Not using a submit button:
jQuery submit not firing
replace this
onclick="document.getElementById('form94').submit();"
with onclick="$( "#form94" ).submit();"
The javascript submit() is not bubbling in IE and they might be other gotchas.
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'
});