How to Make a Feed From User Submitted Posts - javascript

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

Related

How to refresh a specific part of the HTML Document with Vanilla JavaScript

I am working on an AJAX cart system where the sub total will automatically update when the quantity changes. My solution is every time the input changes, post it to the current page (cart page) then reload the div that displays the sub total. However, I don't know how to do this with pure JavaScript, and I haven't found any reference yet.
This is my function for the above algorithm:
var _rangeInput = document.querySelectorAll('.ranum'), _upAload = document.getElementsByClassName('upAload');
var _frmData = {};
for (var i = 0; i < _rangeInput.length; i ++) {
_rangeInput[i].addEventListener('change', function(){
_frmData[this.name] = this.value;
ajaxFormValidate({
type: 'POST',
url: location.href,
method: true,
sendItem: _frmData,
success: function(response) {
//reload here
}
});
}, false);
}
Code explaination:
First, get the inputs and divs that need to be processed.
Loop through all of the inputs and get their values and names.
I have written an AJAX function for my self, you can look above.
Is there anyway to do this with pure JavaScript?
I can't use JavaScript methods or functions to change the content since I am sending the request to the same page, as a result, response here will have the value of the whole document.
Also, this is how the system works:
First, the user changes the quantity they want
AJAX sends request to the same page
The page changes the information based on the request
AJAX receives the request, and refreshes/reloads the specific div
Simply set the innerHTML of your sub total div with the response data.
document.getElementById("sub-total").innerHTML = response.value; //Whatever value you get in response
It sounds like you're actually asking how to get a single element out of an AJAX response.
You can do that by parsing the response into a temporary element, then finding the element you need within it:
const holder = document.createElement('div');
holder.innerHTML = response;
const myElement = holder.querySelector('some selector');

I have a query with upload real time data to load in div without refresh in jquery

I am making a chat function, in which I have put the chat records with while loop but I want to get new records with out refresh the div at the real time.
But If no record is updated new so div doesn't refresh because of scroll force me to bottom.
Use this (I guess u have php installed, you use a PHP page):
var ajaxurl = "updatepage.php(CORRECT URL HERE)";
var data = {};
data["CurBox"] = document.getElementById(IDOFCHATBOX).innerHTML
$.post(ajaxurl, data
, function (response) {
func(response);
});
and make sure you run checks on that the current chatbox is not already the same as when it would be updated! :)
use the post method inside the refreshscript to get the current chatbox contents

how to add div content to mysql without using form element

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.

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 do I make a jQuery POST function open the new page?

I know that a submit button in HTML can submit a form which opens the target page, but how do I cause a jQuery ajax call to POST information to a new page and also display the new page. I am submitting information that is gathered by clicking elements (which toggle a new class called "select") and then identifiers from these items with the new class are added to a string and POSTed to the new page. This new page will use this data to provide a summary of the selections from the previous page. I currently can get it to POST the data to a new PHP page but it seems to be the ajax function simply remains on the current page (which is great for some things, just not this), not redirecting to the new page. how might I go about doing this?
here's the script section:
//onload function
$(function() {
//toggles items to mark them for purchase
//add event handler for selecting items
$(".line").click(function() {
//get the lines item number
var item = $(this).toggleClass("select").attr("name");
});
$('#process').click(function() {
var items = [];
//place selected numbers in a string
$('.line.select').each(function(index){
items.push($(this).attr('name'));
});
$.ajax({
type: 'POST',
url: 'additem.php',
data: 'items='+items,
success: function(){
$('#menu').hide(function(){
$('#success').fadeIn();
});
}
});
});
return false;
});
any pointers would be great!! thanks
edit:
thanks for the help, I've changed my script to :
//onload function
$(function() {
//toggles items to mark them for purchase
//add event handler for selecting items
$(".line").click(function() {
//get the lines item number
var item = $(this).toggleClass("select").attr("name");
});
$('#process').click(function() {
var items = [];
//place selected numbers in a string
$('.line.select').each(function(index){
items.push($(this).attr('name'));
});
$('#items').attr('value',items);
$('#form').submit()
});
return false;
});
First of all I discourage using ajax here as you are not using it for the purpose for which it is intended to, and you are forcing it to do a reload.
You can do something like this in the success of ajax
success: function(){
window.location = "the new url you wanted to load";
}
Edit:
Why not do a normal post with form action attribute set to the page you want to post to and you can access all the variables of the form in that posted page, or alternatively you can concatenate or store in array all your values and store this array in a hidden variable and access this variable in the posted script.
Ajax posts by definition won't to a page load. But you can do whatever you want in your success handler. So just change the document location there:
success: function(){
$('#menu').hide(function(){
$('#success').fadeIn();
});
window.location = 'http://www.example.com/elsewhere';
}
Oftentimes a POST will return a HTTP 301 or 302 redirect. In that case, you can get the returned header information from the XHR object, which is passed into the callback functions.
complete: function( xhr ) {
// assume we got a redirect; the new URL will be in the Location header
window.location = xhr.getResponseHeader( 'Location' );
}

Categories