how to add div content to mysql without using form element - javascript

I want to save div content into mysql without using form and button means page should be opened in browser and it should send it's all div content to mysql table automatically.
here it is what i tried
var myVar = setInterval(function(){getElement()},5000);
function getElement()
{
var iBody = $("#frametest").contents().find(".bx-viewport").html();
document.getElementById("demo").innerHtml=iBody;
alert(iBody);
}
i want this demo div to be saved in mysql

If you don't want to use forms, I think AJAX is a great option.
var contents = $('#frametest').contents().find('.bx-viewport').html();
$.ajax({
url: 'path/to/php/script',
type: 'POST',
data: {content: contents},
success: function() {
// do something after sending data
}
});
This will send contents to the php script defined in the url property of the AJAX call as a POST request, and in the php script you can use the normal thing you'd do for saving it in MySQL.

Related

Ajax call function for each tab

I created responsive tabs just using css. But when I try to implement ajax calls, i am bit confused.
I have a few questions:
What is the best way to make ajax request for each tab?
Is there any shortest way to append response to "tab" div?
How can I call ajax on page load for selected tab?
After first click on tab, do not need to make ajax call again. I need to cache response, but "cache:true" does not work.
Also any other improvements, suggestions and corrections would be helpful.
Example: JSFiddle
if you must use ajax i would run a loop through all the data you need to load do it at once an store the data in a variable (or object in this case)
than the change event will get the id from the tabData which is already populated and you won't need to call the ajax pages again.
now this will solve your cache problem since you won't need it for this scenario
if you want to instant populate the first selected tab when you open the page created an if statement in the ajax success
end result would look something along these lines:
$(document).ready(function() {
//data for the tabs
var tabs = {
1:"tabone",
2:"tabtwo",
3:"tabthree"
}
//empty object for now will be filled with ajax data
var tabData = {};
var activeTabVal=1;
var activeTabID = $('input[name=tabs]:checked', ".tabs").attr('id');
for(key in tabs) {
ajaxCall(key);
}
$('.tabs input').on('change', function() {
var activeTab=$('input[type="radio"]:checked', '.tabs').val();
var tabElement = $('input[name=tabs]:checked', ".tabs").attr('id');
//since we have the data already no need to call ajax here we just get it out of our already loaded data
var data = tabData[activeTab];
replaceData(tabElement, data);
});
function ajaxCall(key){
$.ajax({
type: "POST",
dataType: 'jsonp',
url: 'https://jsonplaceholder.typicode.com/posts/'+key,
async: false,
cache: true,
contentType: "application/json; charset=utf-8",
success: function (msg) {
tabData[key] = msg.body;
//use this to imediatly populate the selected div fo your second point
if(key == activeTabVal) {
replaceData(tabs[key], tabData[key]);
}
}
});
}
function replaceData(tabElement, tabData) {
$('#'+tabElement).next().next().closest('div').append(tabData);
}
});
I would instead of calling it on change I would call it on tab button clicked
Give your tab a data-id and the corresponding container div the same data-id, then when you append you can do something like $('.tab-container[data-id='+$(this).attr('data-id')+']').append('The content');
If you bind it to click you can simply run $('.tab-button .active').trigger('click');
If I were you I would store the data into the data portion of the container div and retrieve it again when they click on it again. So you just check if it was set, if not then do ajax call, if it was just pluck it out and display it. https://api.jquery.com/jquery.data/

How to store JS variable in a database

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

Extract form variable in AJAX response using jquery

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();

Datatables submit form serverside data

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.

How to Make a Feed From User Submitted Posts

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

Categories