For those of you that use the Datatables js plugin, how can I create this example with server side data?
The example uses data that is hardcoded in the HTML.
You would basically do the following:
Serialize the form data (using jquery serialize as the example shows)
Submit said data to your form handling scrip (php etc)
They already provide the jquery serialize code so I won't show that, however the jQuery AJAX function will be needed (at the least):
$.ajax({
type: "POST",
url: "some.php",
data: YOUR-SERIALIZED-DATA-HERE,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
And on your Server side PHP file you just grab the correct form array and parse your values ($_POST).
I had the same problem and didn't want to do an ajax save, so I did this:
var table = $("#mytable").datatable();
$("#myform").submit(function () {
var hiddenArea = $("<div></div").hide().appendTo("#myform");
table.$('input:hidden').detach().appendTo(hiddenArea);
// Prevent original submit and resubmit, so the newly added controls are
// taken into account
this.submit();
return false;
});
The idea is that I take all the inputs that are currently not in the dom and move them inside a hidden container.
Related
I'm using CakePHP and since several days I try to store a java script variable with the help of ajax (jQuery) in a mysql database.
I'm using the following code to do this:
<!-- document javascripts -->
<script type="text/javascript">
$(document).ready(function () {
$('#saveForm').submit(function(){
var formData = $(this).serialize();
var formUrl = $(this).attr('action');
$.ajax({
type: 'POST',
url: formUrl,
data: formData,
success: function(data,textStatus,xhr){
alert(data);
},
error: function(xhr,textStatus,error){
alert(textStatus);
}
});
return false;
});
});
</script>
But when I click on the submit button, Ajax will post the whole sourcode of my webpage. =(
What I need is a function to store a java script variable to my database but without reloading the page.
I am grateful for any help =)
You told jQuery to serialise a form element. That is, convert the form element to a text string. In other words, you are telling it to get the form's HTML code and send that to your server.
I don't know (or want to know) what the correct way of sending a form's data by AJAX is, but I do know that you need to actually do something like access the form's fields to get their values.
My js is a bit rusty but try changing:
var formData = $(this).serialize();
To:
var formData = $('#saveForm').serialize();
Or:
var formData = $('#saveForm').val().serialize();
That's assuming you want to serialize and store the html of the whole form.
To pull just a value from the form (I don't think you need serialize) try:
var formData = $('#saveForm #someInputName').val();
Of course changing someInputName to whatever the actual name of the field you want to save is.
The problem could be in data parameter.. $('#saveForm').serialize();
should be ok
All,
I have a Jquery ajax request calling out a URL. The ajax response I receive is an HTML form with one hidden variable in it. As soon as my ajax request is successful, I would like to retrieve the value of the hidden variabl. How do I do that?
Example:
html_response for the AJAX call is :
<html><head></head><body><form name="frmValues"><input type="hidden"
name="priceValue" value="100"></form></body></html>
$.ajax({
type: 'GET',
url: "/abc/xyz/getName?id="+101,
cache: false,
dataType: "html",
success: function(html_response)
{
//Extract form variable "priceValue" from html_response
//Alert the variable data.
}
});
Thanks
The html_response you get will be a string. As such, if you happen to know exactly what the page will look like, you can just search the text using indexOf.
...But that solution is messy and error prone. Alternatively, you could create a new HTML element (like a div), put your response html in there, and then obtain the hidden variable as you would access any normal html element.
For example:
var tempDiv = $("<div/>");
tempDiv.append(html_response);
var myValue = tempDiv.find("input[name='priceValue']").val();
You can create JQuery object:
var form = $(html_response);
Then get your input PriceValue using JQuery selectors & traversal.
You can read it with $(html_response).find("input[name='priceValue']").val();
I want to encrypt some data in a form using jQuery before it's sent to the server, it can be a MD5 hash. It is a small project, so I don't really need to use SSL.
I have the following JavaScript code where I use $.md5 in the password confirmation info:
$(document).ready(function() {
var dataToSend = {};
dataToSend['action'] = 'signup';
dataToSend['name'] = name.val();
dataToSend['email'] = email.val();
dataToSend['confsenha'] = $.md5(pass2.val());
var options = {
target: '#error',
url: 'insert.php',
beforeSubmit: validate,
data: dataToSend,
success: function(resposta) {
$('#message').html(resposta);
}
};
$('#customForm').ajaxForm(options);
});
The problem is that the data is being duplicated. I tought that overwriting the data being sent by using the var dataToSend would make ajaxForm send only data in that map. But besides sending data from dataToSend, it also sends data from the form, so what I wanted to encrypt using MD5 appears both encrypted and clean. This is an example of what goes in the request:
usuario=user&email=user%40email.com&senha=12345&confsenha=12345&send=&action=signup&name=user&email=user%40email.com&confsenha=d41d8cd98f00b204e9800998ecf8427e
I know I have to define the a function beforeSerialize, but I don't know how to manipulate form data. Can anyone tell me how to do that?
As per the documentation on the plugin site:
data
An object containing extra data that should be submitted
along with the form.
The word along is the crux.
So when you pass data as a part of the options object that data is serialized and is sent along with any data/input elements values that are part of a form.
A better approach would be to hash the password value and assign it to the same field or another hidden field in the beforeSubmit handler(in your case the validate function) and remove the dataToSend object totally.
Something like:
Without any hidden element:
function validate(){
//Other Code
pass2.val($.md5(pass2.val()));
}
With a hidden element in the form:
function validate(){
//Other Code
$("#hdnPass").val($.md5(pass2.val()));
pass2.val("");
}
I'm trying to figure out how to use AJAX to create a Twitter-like feed that displays user's posts on the same page immediately after they push the submit button. It would be an infinite-feed site that would have a "more" button at the bottom.
All I'm trying to make is a simple page containing a textarea box with a submit button and to have user submissions appear below the box as they are submitted.
If possible, a walk through or discussion of the script needed to do this would be great.
Thanks so much
All you need is a server-side script with an SQL query that would return newer posts.
have your javascript store a variable of the date or of the last post id (used PHP for clarification):
result = mysql_query("SELECT ID,POST FROM POSTS WHERE DATE>" . $_GET['date']); //or use WHERE ID> $_GET['id']
while(rows[] = mysq_fetch_array(query));
print json_encode(rows);
now you have a server-side script that will return new posts, so all you have to do is write javascript function for the more button:
updatePosts = function () {
$.ajax({
url: 'serversiderUrl?lastId=' + last_id, //last_id is global variable for the id of the last post on the page
success: function(data){
data = JSON.parse(data);
for(i in data){
$('#posts_container').append(data[i].post); //do your appending functions here
last_id = data[i].id;
}
}
}
now for posting new entries create a server-side script of your favorite language that handles new posts:
result = mysql_query("INSERT INTO POSTS VALUES(''," . urldecode($_POST['POST']) . ")");
now for the client side:
submit_post = function(){
$.ajax({
type: 'POST',
url:'yourposturl',
data: "post=" + encodeURIComponent($('#textArea').text()),
success: function(){
updatePosts(); // call the function that update the posts so the new entry is now added to the page
}
});
}
Now bind the functions to the appropriate buttons when the document is fully loaded:
$(document).ready(function (){
$('#moreButtonId').click(updatePosts);
$('#submitButtonId').click(submitPost);
});
There are many ways such as the submit button kept sending it to the database while we'd append text to a container underneath. Or we can update the container underneath to create a container (page) that are similar, after the ajax response is successful then we append the data to the container beneath
$.post(url,function(data){
//Here you can append the data responsed by the ajax request to the container underneath
});
But you have to have a exactly same view with a conatiner (feed container) existing in the currently page
Hey all. I was fortunate enough to have Paolo help me with a piece of jquery code that would show the end user an error message if data was saved or not saved to a database. I am looking at the code and my imagination is running wild because I am wondering if I could use just that one piece of code and import the selector type into it and then include that whole json script into my document. This would save me from having to include the json script into 10 different documents. Hope I'm making sense here.
$('#add_customer_form').submit(function() { // handle form submit
The "add_customer_form" id is what I would like to change on a per page basis. If I could successfully do this, then I could make a class of some sort that would just use the rest of this json script and include it where I needed it. I'm sure someone has already thought of this so I was wondering if someone could give me some pointers.
Thanks!
Well, I hit a wall so to speak. The code below is the code that is already in my form. It is using a datastring datatype but I need json. What should I do? I want to replace the stupid alert box with the nice 100% wide green div where my server says all is ok.
$.ajax({
type: "POST",
url: "body.php?action=admCustomer",
data: dataString,
success: function(){
$('#contact input[type=text]').val('');
alert( "Success! Data Saved");
}
});
Here is the code I used in the last question, minus the comments:
$(function() {
$('#add_customer_form').submit(function() {
var data = $(this).serialize();
var url = $(this).attr('action');
var method = $(this).attr('method');
$.ajax({
url: url,
type: method,
data: data,
dataType: 'json',
success: function(data) {
var $div = $('<div>').attr('id', 'message').html(data.message);
if(data.success == 0) {
$div.addClass('error');
} else {
$div.addClass('success');
}
$('body').append($div);
}
});
return false;
});
});
If I am right, what you are essentially asking is how you can make this piece of code work for multiple forms without having to edit the selector. This is very easy. As long as you have the above code included in every page with a form, you can change the $('#add_customer_form') part to something like $('form.json_response'). With this selector we are basically telling jQuery "any form with a class of json_response should be handled through this submit function" - The specific class I'm using is not relevant here, the point is you use a class and give it to all the forms that should have the functionality. Remember, jQuery works on sets of objects. The way I originally had it the set happened to be 1 element, but every jQuery function is meant to act upon as many elements as it matches. This way, whenever you create a form you want to handle through AJAX (and you know the server will return a JSON response with a success indicator), you can simply add whatever class you choose and the jQuery code will take over and handle it for you.
There is also a cleaner plugin that sort of does this, but the above is fine too.
Based on your question, I think what you want is a jQuery selector that will select the right form on each of your pages. If you gave them all a consistent class you could use the same code on each page:
HTML
<form id="some_form_name" class="AJAX_form"> ... </form>
Selector:
$('form.AJAX_form")