Particular div to refresh onsumbit using ajax or jquery - javascript

I want a particular div on a page that contains database field to refresh itself to bring out the currenty entry onsubmit of a form. the div that contains the record is called #new_entry
<div id="new_entry"></div>
<script>
$(document).ready(function(){
$("#form3").on('submit',function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "../calls/insert_call_love.asp",
data: data
}).success(function() {
$("#feedback").append("<div class='messages' style='border:1px purple solid; padding:2px; margin:5px;'>Your have loved this photo </div>");
setTimeout(function() {
$(".messages").fadeOut(function(){
$(".messages").remove();
});
}, 1000);
$("input[type=text]").val("");
});
});
});
</script>
this is what i'm posting to the insert_call_love.asp
<form action="<%=MM_editAction%>" method="post" name="form3" id="form2">
<input name="comment" type="text" id="comment" size="50" />
<input name="imageField3" type="image" id="imageField3" src="../imgs/buttons/comment.png" align="bottom" />
<input name="wardrobe" type="hidden" id="wardrobe" value="1" />
<input name="comme" type="hidden" id="comme" value="2" />
<input name="comfn" type="hidden" id="comfn" value="3" />
<input name="photo_id" type="hidden" id="photo_id" value="4" />
<input name="ctype" type="hidden" id="ctype" value="picture" />
<input name="resp_email" type="hidden" id="resp_email" value="5" />
<input name="MM_insert" type="hidden" id="MM_insert" value="form2" />
</form>

In your code, you have to add a variable to success(function()) function
success(function(msg)
**"msg"**will contain data which you want to return from below url:-
url: "../calls/insert_call_love.asp",
then you can assign this data to any div
}).success(function(msg) {
$('#new_entry').html(msg);
}
Note: variable "msg" will contain all the data which you have printed on the page "insert_call_love.asp"

Well depending on what you are doing on the server side with this post...You would need to query the DB and retrieve the latest item, and send it back/echo it out as JSON.
So in pseudocode steps...
Process posted variables...
Query DB for latest entry..
Echo out as JSON...
Then do something like ...
.success(function(data) {
$('#new_entry').html(data);

Related

Ajax submit redirects to new page (should not)

I can't figure out why I'm not able to properly do the ajax magic with this code. It just redirects to a new page as the server handle the request. I tried put a console.log("test"); in the jquery function, but it's never called. So I'm guessing the form submit never go through my ajax but directly to the server.
$("#startTest").submit(function(e)
{
console.log("test"); //This is never called
e.preventDefault();
$.ajax(
{
url : 'handler',
type: "POST",
data : $(this).serialize(),
success:function(data)
{
alert(data);
},
error: function()
{
alert("failure");
}
});
});
<form id="startTest" method="POST" action="handler">
<input type="hidden" name="answer" value="startTest">
<input type="text" name="firstname" value="" placeholder="Navn" id="navn" autocomplete="off"><br>
<input type="submit" name="submit" value="Start test">
</form>
Empty your form action. If your form has an action then when you submit your script follows that action. But you want to achieve that process via ajax so you don't fill action tag.Something like this
<form id="startTest" method="POST" action="">
<input type="hidden" name="answer" value="startTest">
<input type="text" name="firstname" value="" placeholder="Navn" id="navn" autocomplete="off"><br>
<input type="submit" name="submit" value="Start test">

How to capture URL created by form submit in Javascript and Ajax

I need help creating a URL that is clickable. We are currently using PeopleCode in peoplesoft to call an Iscript. That Iscript calls HTML. We've created this form below to build our URL
<form id="form1" name="frmHostedCheckout" method="POST" action="XXXXXXXXX">
<input type="hidden" id="api_token" name="api_token" value="XXXXXXXXX" />
<input type="hidden" id="school_id" name="school_id" value="XXXXXX" />
<input type="hidden" id="student_id" name="student_id" value="%BIND(:1)" />
<input type="hidden" id="email_address" name="email_address" value="%BIND(:2)" />
<input type="hidden" id="curriculum_id" name="curriculum_id" value="8" />
<input type="hidden" id="first_name" name="first_name" value="%BIND(:3)" />
<input type="hidden" id="last_name" name="last_name" value="%BIND(:4)" />
<input type="hidden" id="group" name="group" value="HavenTestGroup1" />
</form>
We are submitting the form with the following JavaScript...
< script type = "text/javascript" >
form1.submit(function() {
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function(response) {
$('#created').html(response);
}
});
return false;
});
< /script>
When I run this we get a URL string but, it's not a clickable hyperlink. How can we make the URL clickable?
Result from code
I believe that you should change this line:
$('#created').html(response);
To this:
$('#created').html('<a href="path-to-file-or-place">' +response + '</a'>);

Submit multiple form with one button

I know this question has been asked a lot, but there doesn't seem to be an answer for me. I'm sorry if I'm just really dumb, but I've been stuck for a day now..
I want to select a table row(see below), and then delete that user. Since I want to have multiple form's to interact with the table I can't place them in one form.
$("#clickMe").click(function () {
$(".myForms").trigger('submit');
});
$('.myForms').submit(function () {
console.log("SWAGGG");
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="listForm" action="index.php?p=admin" method="POST">
<?php
$userQuery = "SELECT * FROM usr2";
$row_userQuery = $dbportal->query($userQuery);
if(isset($row_userQuery) && !empty($row_userQuery))
{
//row[0] = ID
//row[1] = username(abbrevation)
//row[2] = admin? 0=normale user 1=admin
echo'
<table id="myTable" class="table table-striped">
<tr><td></td><td>User ID</td><td>username</td><td>Role</td></tr>';
foreach ($row_userQuery as $row)
{
echo'
<tr>
<td id="tdSelect"> <input type="checkbox" name="selectedUser[]" value="'. $row[0] .'" />
<td>'. $row[0] .'</td>
<td>'. $row[1] .'</td>
<td>'. $row[2] .'</td>
</tr>';
}
echo'</table>';
}
?>
<input type="hidden" name="action" value="listForm">
</form>
<form id="deleteForm" class="myForms" action="index.php?p=admin" method="POST">
<div class="leftTextBox">
<p>user ID:</p>
<p class="margin">gebruikersnaam:</p>
</div>
<div class="rightTextBox">
<input class="form-control" type="text" name="userID" placeholder="user ID">
<input class="form-control" type="text" name="login" placeholder="gebruikersnaam" style="margin-top: 8px;">
</div>
<input type="hidden" name="action" value="deleteForm">
</form>
<button id="clickMe" class="btn btn-default" style="margin-top:5px;float:right;">Delete user</button>
I'm sure that its just me overseeing something, but help would greatly be appriciated.
Also, I have ajaxForm plugin installed.
A 'submit' is by definition a jump to a new URL. You know this can only be done for one form at a time.
However, we talking normal 'submits' here, and you don't have to use normal submits to get information from a form and act on it.
Since you're using JQuery, you could use that. Have a look at ajax calls. For instance here:
http://api.jquery.com/jquery.post
Look for the example called: Post a form using ajax and put results in a div, you will find useful code there. It shows you how to get the values of the fields in the form.
Let's imagine you have 3 forms like this:
<form id="form1" action="api/url1">
<input name="field1" type="text" />
</form>
<form id="form2" action="api/url2">
<input name="field2" type="text" />
</form>
<form id="form3" action="api/url3">
<input name="field3" type="text" />
</form>
<button>Submit</button>
Then you can fire the submit of each form like this:
$('button').on("click", function () {
$('form').each(function (index, form) {
$(form).submit();
});
});
Then to prevent form full post back just prevent the default of the submit event and then post the serialized form with ajax:
$('form').on("submit", function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr("action"),
data: $(this).serialize(),
success: function (data) {
alert(data);
},
error: function (error) {
console.error({ status: error.status, statusText: error.statusText })
}
});
});
JSFIDDLE
If you want to use ajax
you can group a data of all input and post using new FormData()
function fnSubmintAll(){
var formData = new FormData();
$("#form1,#form2,#form3").each(function(idx,item){
var frmValue = $(item).serializeArray();
$.each(frmValue, function (key, input) {
formData.append(input.name,input.value);
});
})
$.ajax({
url: "/PostUrl",
type: "POST",
data: formData,
contentType:false,
processData: false,
success: function (result) {
alert("Success")
},
error: function () {
alert("Error")
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset>
<legend>From 1</legend>
<form id="form1">
<input name="field1" type="text" />
</form>
</fieldset>
<fieldset>
<legend>From 2</legend>
<form id="form2">
<input name="field2" type="text" />
</form>
</fieldset>
<fieldset>
<legend>From 3</legend>
<form id="form3">
<input name="field3" type="text" />
</form>
</fieldset>
<br />
<br />
<br />
<button type="button" onclick="fnSubmintAll">Submit All</button>

Convert li input values data to JSON

Hello I need to save multi values and update database using ajax.. I'm working on Yii framework..
in the first I need to send data using ajax as json but I have wrong on results.
Live code:
http://jsfiddle.net/kxJwp/2/
My javascript code is:
$("#save").live('click', function(){
var showtimes = [];
var values = {};
$('li inputs').each(function() {
values[$(this).attr('name')] = $(this).val();
});
$('li').each(function(i) {
showtimes[i]=values;
});
alert(JSON.stringify(showtimes));
});
Javascript output:
It's output last one li values x number of li
inputs:
<li>
<input name="show_id" class="show_id att" type="hidden" value="" />
<input name="movie_id" class="movie_id att" type="hidden" value="" />
<input name="cinema_id" class="cinema_id att" type="hidden" value="" />
<input name="status" class="status att" type="hidden" value="" />
<input name="times" class="timesArray att" type="hidden" value="" />
<li>
<li>
<input name="show_id" class="show_id att" type="hidden" value="" />
<input name="movie_id" class="movie_id att" type="hidden" value="" />
<input name="cinema_id" class="cinema_id att" type="hidden" value="" />
<input name="status" class="status att" type="hidden" value="" />
<input name="times" class="timesArray att" type="hidden" value="" />
<li>
You are seeing only one row because you have only one object, whereas you need an array of objects, so declare an array first, and then keep adding the objects to it. Something like this:
$("#save").live('click', function(){
var showtimes = []; // Create empty javascript array
var objec={};
$("li").find("input").each(function(index) { // Iterate over inputs
objec=new Object; // to create a new object for every matched element
objec[$(this).attr('name')]=$(this).val()+'avla';
showtimes[index]=objec; // Add object to array
});
var json = JSON.stringify(showtimes);
alert(json);
});
Code explanation:
Use the inbuilt index of each(), by passing the index to the function like: function(index){...}.
Edit: objec=new Object; is needed to avoid getting repeated values, because each time the same object was getting added to the array, but with new, a new object is created each time and that is added to the array.
Update: A better way to select the lis would be using a selector such as : $("li:has(input)") and then cycle through the children:
$("#save").live('click', function(){
var showtimes = [];
var values = {};
$("li:has(input)").each(function(i){
values = new Object;
$(this).children().each(function(){
values[$(this).attr('name')]=$(this).val();
});
showtimes.push(values);
});
alert(JSON.stringify(showtimes));
});
Edit: The output(arrays formed) in both the above samples is different.
Output for code sample 1:
json=[{"show_id":"1avla"},{"movie_id":"2avla"},{"cinema_id":"3avla"},{"status":"4avla"},{"times":"5avla"},{"show_id":"6avla"},{"movie_id":"7avla"},{"cinema_id":"8avla"},{"status":"9avla"},{"times":"0avla"}]
Output for code sample 2:
json=[{"show_id":"1","movie_id":"2","cinema_id":"3","status":"4","times":"5"},{"show_id":"6","movie_id":"7","cinema_id":"8","status":"9","times":"0"}]
Your original js code shows
$("tr").find("input.att").each(function() {
however your view code shows you are using an <li> instead of <tr>
So shouldn't it be $("ul") or $("li")
You can use another alternate method. The changes you should made is place the the lis and input's under a form ad submit the form via ajax. Also you should change the names of the input according to this ie add square brackets so that you can retrieve it as arrays in PHP. No jSON needed
So
<form id="myform" action="action.php">
.....
<li>
<input name="show_id[]" class="show_id att" type="hidden" value="" />
<input name="movie_id[]" class="movie_id att" type="hidden" value="" />
<input name="cinema_id[]" class="cinema_id att" type="hidden" value="" />
<input name="status[]" class="status att" type="hidden" value="" />
<input name="times[]" class="timesArray att" type="hidden" value="" />
<li>
<li>
<input name="show_id[]" class="show_id att" type="hidden" value="" />
<input name="movie_id[]" class="movie_id att" type="hidden" value="" />
<input name="cinema_id[]" class="cinema_id att" type="hidden" value="" />
<input name="status[]" class="status att" type="hidden" value="" />
<input name="times[]" class="timesArray att" type="hidden" value="" />
<li>
....
</form>
and the javascript for ajax
$("#save").live('click', function(){
var form = $('#myform');
$.ajax( {
type: "POST",
url: form.attr( 'action' ),
data: form.serialize(),
success: function( response ) {
console.log( response );
}
} );
});
then in your controller you will get the submitted data as array
print_r($_POST['show_id']);
print_r($_POST['movie_id']);
etc etc

Pass data to a FORM and auto submit it

The thing I'm trying to have is a JQuery/JavaScript code that will automatically pass some data from facebook to a form (basically the form doesn't need to be shown). so the first part is ready (the part that pulls the data from facebook).
window.fbAsyncInit = function() {
FB.init({appId: 'xxxxxxxxxxxxxxx', status: true, cookie: true, xfbml: true});
};
FB.Event.subscribe('auth.login', function(response) {
if (response.session) {
FB.api({
method: "fql.query",
query: "SELECT name,email FROM user WHERE uid = " + response.session.uid
}
Now i need to insert the name and the email to the inputs with name="name" and name="email" and auto submit the form.
Thanks in advance!
EDIT: here is the form:
<form method="post" class="af-form-wrapper" action="http://www.aweber.com/scripts/addlead.pl" >
<input type="hidden" name="meta_web_form_id" value="XXXXXXXX" />
<input type="hidden" name="listname" value="XXXXXX" />
<input type="hidden" name="meta_adtracking" value="XXXX" />
<input type="hidden" name="meta_message" value="1" />
<input id="awf_field-22176678" type="text" name="name" class="text" value="" tabindex="500" />
<input class="text" id="awf_field-22176679" type="text" name="email" value="" tabindex="501" />
<input name="submit" class="submit" type="submit" value="Submit" tabindex="502" />
<div class="af-clear">
</form>
EDIT 2: I need to do something like this just simplified with jQuery:
<?php
$formcode = '<form method="post" action="http://www.aweber.com/scripts/addlead.pl" >
<input type="hidden" name="meta_web_form_id" value="864136470" />
<input type="hidden" name="listname" value="fbu-ppv-mmoney1" />
<input type="hidden" name="meta_adtracking" value="FB_Ultralizer_PPV" />
<input type="hidden" name="meta_message" value="1" />
<input id="awf_field-22176678" type="text" name="name" class="text" value="" tabindex="500" />
<input class="text" id="awf_field-22176679" type="text" name="email" value="" tabindex="501" />
<input name="submit" class="submit" type="submit" value="Submit" tabindex="502" />
</form>
'; ?>
<script type="text/javascript">
customar_formcode="$formcode";
customar_formcode=customar_formcode.replace("{email}", user.email);
customar_formcode=customar_formcode.replace("{name}", user.name);
document.getElementById(\'form\').submit();
</script>
Use Jquery's POST to send the data without the need for the markup for a form and using auto submits:
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
EDIT:
If you have already got the form setup in the DOM you should just fill it in with JavaScript and submit it with JavaScript
To change the input values use Jquery like so:
$('input[name$="name"]').val('value');
once all the inputs are set to how you want them you can submit the form using this:
if you have the ID form on your form then you can use code like
$('#form').submit();
Hope this helps
with jquery you can pass all data of form at once with something like:
var data = $(#formID).serialize();

Categories

Resources