Updating a DIV on Submit without page refresh - javascript

I need refresh <myDiv> on my webpage when the Submit button is clicked.
I created an example of what I need. I want to display the user input text inside <myDiv> when the Submit button is clicked. Currently it's not showing anything. How can I fix this?
http://jsfiddle.net/NathaliaZeed/8dn5j/2/
Thanks everybody.

You need to use complete: not done:, then, assign your val1 variable to myDiv.
Working fiddle: http://jsfiddle.net/8dn5j/14/
See below:
$('#btn').click(function(e) {
var val1 = $('#val1').val();
e.preventDefault();
$.ajax({
type: 'post',
data: {'val1':val1},
complete: function(jqXHR, textStatus){
$("#myDiv").html(val1);
}
});
});

The code in your example is good, except you forget to load the jQuery library.
If you make sure you include jQuery, the javascript code should work.
Also, your example should run on a PHP server. JSfiddle does not interpret PHP code, so that is also why the example does not work.
If you don't have a PHP server, Google for WAMP for Windows or MAMP for Mac.

Not Sure why you need php and ajax if there is only need to update the div on button click and not doing any server side processing for the need you described in question this code will work
<div class="myDiv" id="myDiv"></div>
<div class="sear">
<form action="" method="post">
Search Word: <br />
<input type="text" name="val1" id="val1" /><br />
<input type="button" value="Submit" id="btn" />
</form>
</div>
Js
$('#btn').click(function(e) {
var val1 = $('#val1').val();
$("#myDiv").html(val1);
$("#myDiv").toggle("slow");
});

By the way, you don't need to use the form-tag..
I would do it this way:
$('#btn').click(function(e) {
var val1 = $('#val1').val();
$.ajax({
type: 'post',
data: {val1:val1},
success: function(data) {
$("#myDiv").text(data);
}
});
});

For me it doesn't do anything with Ajax request.
$('#btn').click(function(e) { e.preventDefault();
$("#myDiv").html($('#val1').val());
//..ajax stuff..
});

Related

Pass variables from HTML form -> ajax load()

What I am trying to do
I have a HTML form which looks like this:
[input text field]
[submit button].
I want the output results to display in only a small part of the page (don't want to refresh the entire page after the button is clicked).
What I have done so far
I am using jquery load() as follows:
<script type="text/javascript">
function searchresults(id) {
$('#myStyle').load('displaysearchresults.php?id=' + id ; ?>);
}
</script>
Results will appear in a div which is exactly what I want:
<div id='myStyle'></div>
The problem
The script above works just fine (I used a variation of it elsewhere). But I have 2 problems:
1-How to call the load() script from the form. I tried this but it doesn't work:
<form id="form" name="form" method="post" action="searchresults('1')">
2-If I am not able to call the load() script from the form, how do I pass what is into the input text field to the load() script so in the end it can be proceessed by the displaysearchresults.php file???
Thanks
Currently its not working since you have a typo:
function searchresult(id) {
/^ no s
$('#myStyle').load('displaysearchresults.php?id=' + id ; ?>);
}
Here:
action="searchresults('1')"> // this should be on the onsubmit
^
Since you're intention is to submit the form without reloading, you could do something like:
$('#form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: 'displaysearchresults.php',
data: {id: 1},
type: 'POST',
success: function(response) {
$('#myStyle').html(response); // assuming the markup html is already done in PHP
}
});
});
Of course in the PHP side, just call it like a normal POST variable:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$id = $_POST['id'];
// other stuff you have to do
// echo markup stuff
exit;
}
Ok I have been able to do what I wanted to do, i.e., displaying search results in part of the page without reloading.
Actually it is not necessary to use the ajax load() function. You can do it with the script below:
<form id="form" method="POST">
<input type="text" id="textbox" name="textbox" />
<input type="submit" name="test" />
</form>
<div id="myStyle"></div>
<p>
<script src="jquery-1.10.2.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#form').on('submit', function(e){
e.preventDefault(); // prevent the form from reloading
$.ajax({
url: 'displaysearchresults.php',
type: 'POST',
dataType: 'html',
data: {text:$('#textbox').val()},
success: function(response) {
$('#myStyle').html(response);
}
});
});
});
</script>
So what is this doing:
It will "read" what the user entered in the textbox,
When the user click the "submit" button, it will put that into a POST variable and send it to "displaysearchresults.php" without reloading the page,
The search results will be displayed between the "mystyle" div.
Pretty nice.
Note for beginers: do not forget to copy the jquery file to your root folder otherwise ajax just won't work.

JQuery button takes url and submits php form

I run an application that shortens urls for authenticated users. The form for this application is simply an input for the full url, which then spits out a shortened url.
I would like to build a button that can be added to generated pages (the urls are long and messy) and once clicked would automatically submit the url shortening form.
The url shortening application is run in php. I've read a little bit about using ajax to submit the form. Does this matter if it's on a different website? Does anyone have a good tutorial or starting point for this sort of thing?
Many thanks!
edit to include code:
<form action="" method="post">
<label for="form_url">Which URL do you want to shorten?</label>
<input type="url" id="form_url" name="form[url]" required="required" value="http://">
<input type="hidden" name="form[_token]">
<button type="submit" role="button">Shorten URL</button>
</form>
$(document).ready(function() {
$('a.btn').click(function() {
var pathname = window.location;
$.ajax({
type: "POST",
url: 'http://url',
data: $(pathname).serialize,
success: success,
dataType: text
});
});
});
There isn't much to go on, considering you didn't post any code, but what I think you're asking is:
<form id="myForm" method="post">
<input type="text" name="long_url"/>
<input type="submit" value="Send"/>
</form>
Now in the Javascript, you'd capture the submit event and call and ajax request:
$("#myForm").submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "urlOfPhp",
data: $("#myForm").serialize(),
success: function(returned_data) {
// Handle Success Here.
}
}).error(function(){
// Handle an Error Here.
});
});
And that's the basics of Ajax. I'm also not clear on the Generated pages button thing, but this is a good starting point.

jQuery submit() is not firing

I am trying to trigger the submit of a form from a link outside the form (not the submit button).
Here is the basics of the form:
<form action="/Hospice/TabPatientTrackingPost" id="formTabPatientTrackingPost" method="post">
[a big form with lots of inputs]
<div class="pull-right">
<button type="submit" class="btn btn-brand" id="btnSave" name="btnSave">Save</button>
<button type="reset" class="btn btn-brand" id="btnCancel">Cancel</button>
</div>
</form>
Here is what the link looks like:
Living</li>
JS Function:
function triggerSave() {
alert("triggerSave test alert");
$("#formTabPatientTrackingPost").submit();
}
But, the code $("#formTabPatientTrackingPost").submit(); is not causing the form to post the submit.
The alert("triggerSave test alert"); is firing, but the form is not submitting.
It works fine if I just click the Save button.
Any ideas what I am doing wrong?
Based on what you have posted, this works fine for me.
http://jsfiddle.net/jFYN2/
triggerSave();
I would check to make sure you're including the right version of jQuery.
Also verify that you do not have any syntax issues in the [a big form with lots of inputs]
try this: http://jsfiddle.net/8rLGN/2/
$('a').click(function(e) {
e.preventDefault();
alert("triggerSave test alert");
$("#btnSave").trigger('click');
});
You need to make sure your function is available globally when calling functions from the onclick attribute, try:
triggerSave = function() {
alert("triggerSave test alert");
$("#formTabPatientTrackingPost").submit();
}
DEMO
As I worked on this more, I realized the problem was only occurring in Chrome. Everything worked in Firefox and IE (yeah, who would have guessed).
Then, that led me to this post: JQuery submit not working in Chrome
So, my final solution was to use an AJAX POST to get this working:
triggerSave = function () {
$.ajax({
url: '/Hospice/TabPatientTrackingPost',
type: 'POST',
dataType: 'json',
data: $('form#formTabPatientTrackingPost').serialize(),
success: function (data) {
console.log("success");
}
});
}
Thank you to everyone that helped! +1 for all the useful answers.

Execute script after load input file

I have an input file field to select files to upload, and I use ajax to send these pics to server. For execute all script after a file is selected, I use submit, but I think it could be better not to include the submit button and use jquery to detect when I select the file and process the submit action then.
My code:
<script>
jQuery(document).ready(function () {
jQuery('#form_up').ajaxForm({
dataType: 'json',
success: bol
});
});
function bol(datab) {
if (datab.field_empty == "bad") {
jQuery(".bol_request_fail").fadeIn(3000);
} else {}
}
</script>
<form name="form" method="post" id="form_up" runat="server" action="indexer_upload_user_pic.php" enctype="multipart/form-data" style="margin:0px;">
<input type="file" name="upload[imagen][]" id="logo2" class="file-upload"/>
</form>
I use one plugin for send the fields and all form by this you can see ajaxForm function.
The question is: How I can avoid using submit and instead send the pic when it is selected via file input?
I didnt test it, but this might work:
jQuery(document).ready(function () {
$("#logo2").change(function(){
jQuery('#form_up').ajaxSubmit({
dataType: 'json',
success: bol
});
});
});
Check the Plugin API if this dont work, I just quick checked it, and saw there is a ajaxSubmit...

Process form data using jQuery

I'm currently using Prototype, but I'd like to rewrite this function to jQuery:
function post(div,url,formId) {
new Ajax.Updater(div, url, {
asynchronous:true,
parameters:Form.serialize(formId)
});
}
HTML example that goes with it:
<form method="post" action="" id="foo"
onsubmit="post('result','getdata.php','foo');return false;">
<input type="text" name="data" />
</form>
<div id="result">&lt/div>
I've been looking at jQuery.load() and jQuery.post(), but I'm not sure which one to use and how exactly.
Thanks in advance for your help.
With this HTML:
<form method="post" action="getdata.php" id="foo">
<input type="text" name="data" />
</form>
<div id="result"></div>
You can do this with jQuery:
$(function() { // wait for the DOM to be ready
$('#foo').submit(function() { // bind function to submit event of form
$.ajax({
type: $(this).attr('method'), // get type of request from 'method'
url: $(this).attr('action'), // get url of request from 'action'
data: $(this).serialize(), // serialize the form's data
success: function(responseText) {
// if everything goes well, update the div with the response
$('#result').html(responseText);
}
});
return false; // important: prevent the form from submitting
});
});
The reason I got rid of the onsubmit code is because it is considered bad practice to have inline JavaScript like that. You should strive to make your forms free of JavaScript and then bind all the JavaScript away from it. This is known as unobtrusive JavaScript and it is a Good Thing.
EDIT:
Since you have that code in many pages, this is a function that will do what you want using the same signature you currently have on the post function. I recommend you take a few hours to update all your forms over keeping this, but here it is anyways:
function post(div,url,formId) {
$.post(url, $('#' + formId).serialize(), function(d) {
$('#' + div).html(d);
});
}
As far as your problem, the livequery plugin could help you there. Alternatively, it is as simple as encapsulating the binding code in a function and calling it whenever a form is added.
Use this and get rid of the onsubmit attribute in your HTML:
$(document).ready(function() {
$("#foo").submit(function() {
$.post($(this).attr("action"), $(this).serialize());
return false; // prevent actual browser submit
});
});
jQuery serialize method docs
You can't send "multipart/form-data" forms with jquery because of security problems. You must do it with flash or iframe...

Categories

Resources