Ajax, just sending value not showing page - javascript

I have two files with php and html. This is the basic info inside my A.php file
<div class="col-md-8">
<input type="email" class="form-control" placeholder="Ingresar Número de Nota" id="idnote" name="idnote">
</div>
<button type="button" class="btn btn-primary" id="notes">Enviar</button>
When the user click in the button, it calls a function inside a js.
$(document).ready(function() {
var formData = {
'id' : $('input[name=idnote]').val()
};
$.ajax({
type : 'POST',
url : '../consults/findnote.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
//Going to findnote.php and keeping formData
//This findnote.php contains a completely different design but I need the first value to make some changes for the user.
})
});
});
The problem is that after the ajax, my webpage is not going to findnote.php is just sending the value, And I need to show findnote.php
I know if i use
event.preventDefault();
Ajax will prevent the reload, but I'm not using it.
There is a way to do it?
How Do I keep values after making a window.location? (Because if I call the file after the successful call I lose the value)
Should I try with only php? (Its an option)

Why don't do pure HTML ?
<form action="../consults/findnote.php" method="POST">
<div class="col-md-8">
<input type="email" class="form-control" placeholder="Ingresar Número de Nota" id="idnote" name="id">
</div>
<button type="submit" class="btn btn-primary" id="notes">Enviar</button>
</form>
Just added the form tag and edited the name of the input for it complies with your function result.
"The problem is that after the ajax, my webpage is not going to findnote.php is just sending the value"
This is basically what ajax is made for :)
With ajax, you can, if you want, append the result to the current page (you didn't in your code. Just sent datas).
The other solution with form tag, the one above, load the result as a new page, like a classic link.

you need to create a form and pass a function on submit that will run before form submit and redirect
<form action="../consults/findnote.php" method="POST" onsubmit="myfunction()">
<input type="email" class="form-control" placeholder="Ingresar Número de Nota" id="idnote" name="idnote">
</div>
<button type="submit" class="btn btn-primary" id="notes">Enviar</button>
</form>
then in your jquery you can do
function myfunction() {
var formData = {
'id' : $('input[name=idnote]').val()
};
$.ajax({
type : 'POST',
url : '../consults/findnote.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
//Going to findnote.php and keeping formData
//This findnote.php contains a completely different design but I need the first value to make some changes for the user.
})
});
}

Related

Refresh a specific class after post ajax Javascript

So after lot of researchs, I come here to request your help, there is my problem :
I have a comment system with multiple forms on a same page (I use FOSCommentBundle on Symfony). And I want to be able to post comments with Ajax (this part work, no problems) and refresh the comment section after the post is submitted (And i'm stuck on this part).
There is an example of code :
$(document).on("submit", ".postAjax", function(e){
e.preventDefault();
$(this).LoadingOverlay("show");
data = $(this).serializeObject();
$.ajax({
url: $(this).attr('action'),
type: 'POST',
success:function(){
$(".comments").load(window.location.href + " .comments");
}
});
});
<form method="POST" class="postAjax" action="./comment/post/1">
<input type="textarea" name="comment">
<input type="hidden" name="identifier" value="1">
<input type="submit">
</form>
<div class="comments">
<!-- Comments refreshed after post here -->
</div>
<form method="POST" class="postAjax" action="./comment/post/2">
<input type="textarea" name="comment">
<input type="hidden" name="identifier" value="2">
<input type="submit">
</form>
<div class="comments">
<!-- Comments refreshed after post here -->
</div>
<!-- ... -->
I have tried lot of things, the function ".load" of JQuery but it load all the "comments" class and duplicate the comments in each class.
If someone have a solution... Thank you
First of all, in the provided code, your <form> tag lack an action attribute for your code to work properly.
Then, to answer your question, modify your controller action (the one saving your new comment) so that it return the informations of the submitted comment (json format is better). Then, transform the returned json into html code, and append the result to your comments <div>, for example :
$(document).on("submit", ".postAjax", function(e){
e.preventDefault();
$(this).LoadingOverlay("show");
data = $(this).serializeObject();
var element = $(this);
$.ajax({
url: $(this).attr('action'),
type: 'POST',
success:function(newCommentData){
/* do some process here to transform your newCommentData array into html code */
$(element).next(".comments").append(newCommentData);
}
});
});
Also, if you want it to be cleaner, you could have an hidden 'div', with the same model as a comment div, but with each content replaced by patterns ( ex : %commentTitle%, %commentBody% ). Then each time you post a new comment, you could get that hidden div, and replace patterns with your comment data. That way, if you change comment section structure later, the JS script will still work the same way, without adjustments needed.
Try this
$(document).on("submit", ".postAjax", function(e){
e.preventDefault();
$(this).LoadingOverlay("show");
data = $(this).serializeObject();
var $comment = $(this).next(".comments");
$.ajax({
url: $(this).attr('action'),
type: 'POST',
success:function(){
$comment.append("<div />");
$comment.last("div").load(window.location.href + " .comments");
}
});
});

Prevent redirecting after post

It's probably a bad idea to ask a question, which already have multiple answers and multiple times, but I should ask it anyway. I tried pretty much everything I find there Prevent redirect after form is submitted but nothing helps me.
There is a some minor detail, which I don't see. I'm not very familiar with jQuery and AJAX. Especially with the former.
So, the code:
<form id="form" action="uploadfile.php" method="post" enctype="multipart/form-data" ><!--action="uploadfile.php" onsubmit="return false;" -->
<label>Name</label>
<input id="username" name="username" type="text" onblur="checkUsername(this.value)" onkeypress="clearError('nameerror')" oninput="clearError('nameerror')" /><br>
<label id="nameerror"></label><br>
<label>Email</label>
<input id="email" name="email" type="text" onblur="validateEmail(this.value)" onkeypress="clearError('emailerror')"/><br>
<label id="emailerror"></label><br>
Select a file<br />
<label id="draganddroperror"></label><br>
<input name="fileToUpload[]" id="fileToUpload" type="file" onchange="onChange(event)" multiple /><br />
<button id="btnSubmit" onclick="sendData()" style="background-color: gray; color: #ffffff;" />Отправить</button>
</form>
There is my JS
function sendData() {
var file_data = $("#fileToUpload").prop("files");
console.log(file_data);
if ($("#file_data").val() != "") {
var form_data = new FormData();
//form_data.append('file', file_data);
//console.log(file);
form_data.append('file', file_data);
console.log(form_data);
$.ajax({
url: 'uploadfile.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data) {
// get server responce here
//alert(data);
// clear file field
//$("#your-files").val("");
return false;
}
});
return false; //event.preventDefault();
} else {
alert("Please select file!");
}
}
So, this is the code in question. All works flawlessly, except redirect. Another questions contains submit, but I didn't have submit input. I tried to delink form from post method (1st line), but I got server error. Return false everywhere.
I spent countless hours on this question, it consumed almost all my night hours for a few days. I would appreciate any help, thanks.
The trick to prevent form submission is return false onsubmit as below:
<form id="form" onsubmit="return sendData()" method="post" enctype="multipart/form-data">
<!--action="uploadfile.php" onsubmit="return false;" -->
<label>Name</label>
<input id="username" name="username" type="text" onblur="checkUsername(this.value)" onkeypress="clearError('nameerror')" oninput="clearError('nameerror')" />
<br>
<label id="nameerror"></label>
<br>
<label>Email</label>
<input id="email" name="email" type="text" onblur="validateEmail(this.value)" onkeypress="clearError('emailerror')" />
<br>
<label id="emailerror"></label>
<br> Select a file
<br />
<label id="draganddroperror"></label>
<br>
<input name="fileToUpload[]" id="fileToUpload" type="file" onchange="onChange(event)" multiple />
<br />
<button type="submit" id="btnSubmit" style="background-color: gray; color: #ffffff;">Upload</button>
</form>
Note that I have written onsubmit=return sendData(). When the sendData() will return true the form will get submitted, otherwise it will never get submitted. For that the last statement in sendData() is return false;. In this way the form never gets submitted in current window, instead only Ajax submit works.
function sendData() {
var file_data = $("#fileToUpload").prop("files");
console.log(file_data);
if ($("#file_data").val()) {
var form_data = new FormData();
//form_data.append('file', file_data);
//console.log(file);
form_data.append('file', file_data);
console.log(form_data);
$.ajax({
url: 'uploadfile.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data) {
// get server responce here
//alert(data);
// clear file field
//$("#your-files").val("");
}
});
} else {
alert("Please select file!");
}
return false;
}
I hope this gives you the clear understanding.
You want to cancel the default event handler for the submit event that the button triggers. To do this you need access to the event itself. It's best practice to handle the button click from JavaScript entirely instead of calling functions from HTML.
var submitButton = document.getElementById('btnSubmit');
submitButton.addEventListener('click', sendData);
// Then you will have access to the event in the sendData function
function sendData(ev) {
ev.preventDefault();
...
}
Live example
A slightly cleaner approach is to handle the form submitting, however this is done. This would also catch a form submit by hitting the enter key for example.
var form = document.getElementById('form');
form.addEventListener('submit', sendData);
Live example
In function sendData() you should pass event param like this
function sendData(evt) {
}
and then in this function we should add evt.preventDefault(); to stop submit action. Hope this help.
Add type attribute with the value of button and you are done:
<button id="btnSubmit" type="button" ...
By default The value for the type attribute is submit, which tells the browser to submit the from to the server, If you change it to button the browser will do nothing, you can only bind events when the button is clicked

Upload files Using Ajax, Jquery and Struts2

Hi can any one please tell me how to upload files using ajax, jquery and Struts2. I have gone through the lot of tutorials in the net but i didn't get any possible solution. The requirement is when ever we click on the button the javascript function need to be called.The javascript(jquery) initiate the Ajax engine and ajax need to call the struts action to get the response. Here the request and response is without refresh the page and without using the IFrames.
I use iframe to submit my data without refresh.
i) My html is as follows :
1) Add form tag. // You can just copy paste my form tag just change the action
2) Add target="my_iframe" // The iframe name.. it can be anything
<div class="bp_up_input">
<form name="banner_image_uploads" id="banner_image_uploads" method="post" action="" target="my_iframe" enctype="multipart/form-data">
<span>
<input type="file" name="banner_image" class="my_vld" lang="Image_path" />
<input type="button" id="banner_image_upload" value="Upload" class="bp_button_style" />
</span>
<input type="hidden" name="slt_store_id" value="" />
<input type="hidden" name="sld_location" value="" />
</form>
</div>
ii) My javascript code is a follows :
$('#banner_image_upload').live('click',function(){
if($.trim($('input[name="banner_image"]').val()) != '' && $.trim($('select[name="bp_location"]').val()) != '' && $.trim($('#store_names').val()) != ''){
$("iframe").remove(); //Remove previous iframe if present
$("body").append('<iframe id="my_iframe" name="my_iframe" src="" style="display:none;"></iframe>'); //Append iframe to body with id my_iframe
$('#banner_image_uploads').submit();//submit the form with id banner_image_uploads
$("#my_iframe").load(function(){
var val = $("iframe")[0].contentDocument.body.innerHTML; // I use php so I just echo the response which I want to send e.g 250:new and save it in var val.
var data = val.split(':'); // I split the variable by :
var html = '<tr><td><img width="800" height="60" border="0" src="/assets/store_banners/live/'+$.trim($('input[name="sld_location"]').val())+'/'+data[1]+'" id="'+data[0]+'"><img src="/images/delete_trash.png" width="9" height="12" class="image_delete" style="padding-left:37%;"/></td></tr>'; // In my case I wanted to upload an image so on success I had to show the image which was uploaded. You can skip this and the below code if you want.
$('.bp_table tbody').append(html); //Append the uploaded image to the container I wanted.
$('input[name="banner_image"]').val(''); //On success I clear the file name
});
}else{
alert('Please Select filters');
}
Hi the below code is working for me. I hope it will help you.
JSP Code:
<div id="uploadImg">
<s:form id="uploadImgForm" action="strutsaction" method="post" enctype="multipart/form-data">
<s:file name="imgFileUpload" label="Choose file to upload" accept="image/*"></s:file>
<s:submit value="Upload" align="center" id="uploadImgSubmitBtn"></s:submit>
</s:form>
<div>
JQuery:
$("#uploadImgSubmitBtn").click(function(e){
// Get form
var form = $('#uploadImgForm')[0];
// Create an FormData object
var data = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "strutsaction.action",
data : data,
cache: false,
processData: false,
contentType: false,
success: function(data){
$('#uploadImg').html(data);
}
});
});

Submit URL via AJAX / PHP set variable without refreshing page, load variable

I'm having an issue with some script to perform a function via AJAX without refreshing my page. I have a field for a user to enter an external URL, and when they click submit it pops up a modal window, with some information generated through a separate PHP page (images.php currently). I have the script working when the form is actually submitted, the page reloads, and images.php is able to see index.php?url=whatever, but I'm trying to update the page without having to refresh. Do I need to re-render the DIV after defining the variable? I think this may be where I'm having problems.
JS
<script type="text/javascript">
$(function() {
$("#newNote").submit(function() {
var url = "images.php"; // the script where you handle the form input.
var noteUrl = $('#noteUrl).val();
$.ajax({
type: "POST",
url: url,
data: {noteUrl: noteUrl},
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
HTML
<form id="newNote">
<input type="text" class="form-control" id="noteUrl">
<input type="button" class="btn btn-default" id="addNote" data-toggle="modal" data-target="#noteModal" value="Add Note"/>
</form>
PHP (aside from form being submitted to this, this is also included in the modal, which opens, but returns NULL on var_dump($postUrl))
$postUrl = $_REQUEST['noteUrl'];
echo $postUrl;
I could definitely be missing something glaring here, but honestly I've tried every combination of AJAX example I could find on here. Am I missing a huge step about having PHP get the variable? Do I need to refresh a DIV somewhere?
Please help.
Here is a bit neater version of the same code, with the missing quote corrected.
$(function() {
$("#newNote").submit(function() {
$('#notePreview').empty();
var url = "images.php"; // the script where you handle the form input.
var noteUrl = $(this).find('#noteUrl').val();
var request = $.ajax({
type: "POST",
url: url,
data: {noteUrl: noteUrl}
});
request.done(function(data) {
$('#notePreview').append(data);
});
return false; // avoid to execute the actual submit of the form.
});
});
Add the attribute name="noteUrl" to your input
<form id="newNote">
<input type="text" class="form-control" name="noteUrl" id="noteUrl">
<input type="button" class="btn btn-default" id="addNote" data-toggle="modal" data-target="#noteModal" value="Add Note"/>
</form>
You can also do var_dump($_REQUEST); to see what request variables are being sent.
You might have missed the noteUrl as name. Try giving the name as below and get it using the same name. In your case it is noteUrl
<form id="newNote">
<input type="text" class="form-control" name="noteUrl" id="noteUrl">
<input type="button" class="btn btn-default" id="addNote" data-toggle="modal" data-target="#noteModal" value="Add Note"/>
</form>
Shouldn't this
var noteUrl = $('#noteUrl).val();
be
var noteUrl = $('#noteUrl').val();
^^^

How to submit a form with specific fieldset

I have a form like this:
<form name="paymentForm" id="paymentForm" action="/submit.jsp" method="post">
<fieldset id="ccData">
<input id="ccNumber" name="ccNumber"/>
</fieldset>
<fieldset id="otherData">
<input id="requestId" name="requestId"/>
</fieldset>
</form>
When you slick submit, I would like to submit(via ajax) only #ccData filedset to some different url (e.g. submitCC.jsp) and based on response I want to submit full form to actual url.
How can I achieve that ?
Use jQuery's serialize method
var formData = $("#ccData").serialize()​;
$.post("TheUrl",formData);
You could do that with JavaScript - e.g jQuery. You build an eventHandler like
$('#paymentForm').on('click', function () {
$(this).preventDefault();
if ($(this).hasClass('first_send')) {
$.ajax({
url: "your_url",
data: { ccData: $('#ccData').val()}
}).done(function ( data ) {
$('#paymentForm').addClass('first_send')
// examin the data, insert stuff you need and send the form again
// with ajax
})
} else {
$(this).removeClass('first_send')
// this is the second send - so do stuff here - show a result or so
}
})
With the class first_send you can check if it is the first send or the second. This is just an untested, incomplete idea how you could do it. I guess you get the big picture ...

Categories

Resources