dynamically create more php objects on scroll - javascript

I want to do the following and do not know how to best approach it:
I have a Facebook like Wall in a Social Website I created.
Every wall Post is a PHP Object with several "comment" objects attached to it.
All Relevant Data is currently fetched from the Database at the time the page loads and works as I wanted it to.
My Wall is getting quite long so I would like to implement infinite scrolling via JQuery and Ajax.
I wanted to send a request for more post objects to a php page which would instantiate them and send the finished objects back. Now I have read that this is bad practice sending PHP Objects via JSON and that it can lead to Problems and potential attack vectors.
How should I approach this? Write the entire wall in Jquery? Have it send Requests for the Data to PHP but display everything with JQuery instead of PHP?
A few pointers would be very appreciated.

You should send AJAX request for needed posts and return ready HTML which you can just append to the container with $('wall_container').append($(new_post_html));

I would say load the initial page and append the data to the wall as you get it. No need to send objects. All the data you need will be in the responseText of the request object
var request = new XMLHttpRequest();
var form = new FormData();
form.append('param_1',val_1);
form.append('param_2',val_2);
request.open("http://example.com/getPostsForWall.php","POST",true);
request.send(form);
request.onreadystatechange = function(){
if(request.status==200 && request.readyState == 4){
//Successful request
response = JSON.parse(request.responseText);
//Want to append a title using jquery to your wall that has an id of wall?
$("#wall").append("<h2 class='wall-post-title'>"+response.post_title+"<h2>");
}
};
This is assuming you have your server side code returning a variable with the key 'post_title' when you send your response

Related

Upload data to the db without stopping the loading of the site

I have a small problem, I created a data analysis system on my site. Everything works, only that every time I run the post to be able to insert the data in the db, it slows down the loading of the site a lot. I was wondering if it was possible to load the data in the database without stopping the execution of the site. For example, if I load and click on an item in the menu I would like it not to let me wait for the data to be entered in the db but to continue with the click I made on the menu item.
My code works this way.
I take the data that interest me with javascript and I post to a php page for data entry
Thank
I don't know if you are using AJAX calls to pass the value from frontend to PHP.
If not, try to use AJAX calls calling the PHP page for data entry and passing the values you want to store. AJAX calls are asynchronous so JavaScript does not have to wait for the server response.
This is an example of AJAX call:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "data_entry.php?value1=exampleOfValueBeingStored1&value2=exampleOfValueBeingStored2", true);
xhttp.send();
}
in the REST paradigm if you need to update values you should use PUT or POST instead of GET. GET should be used only when you want retrieve values already inserted inside database for example.

Laravel - load new content from DB using ajax dynamically

I am still learning about how Ajax works and I encountered this problem:
#getDashboard Controller:
$data = Post::latest()->get();
return view('view', ['data'] => $data);
view.blade.php Page:
<div>
#foreach($data as $post)
<p>{{ $post->ad_title }}</p>
#endforeach
</div>
This loads all posts from the database, but new ones appear only on refresh. How can i load new posts from database without refreshing, i suppose using AJAX? Thank you.
Yes, you can do so using ajax.
If you want to return JSON from Laravel controller, you can do so very easily.
Just return the object or array instead of view. Laravel will automatically return JSON as response.
For example:
getDashboardJson(){
return Post::latest()->get();
}
Form Ajax if you call the corresponding URL of this method, you will get json of all latest posts.
What you would want to do is create a function that executes an XMLHTTP Request and then populates your page with the results, then set an interval on that function.
In your PHP, you will want to populate an array with all the data you want in your page. You will then json_encode it and echo it out. Ensure to set your content-type header to application/json.
In your Javascript, you will want to:
XMLHTTP Request the information
If there was an error, then handle it
JSON.Parse it into an array
Validate it (you may return in your array that no information was found)
Update your HTML
There are 2 options I would recommend for your ajax. The first is Javascript's built in XMLHTTPRequest method, which you can read up on here. The alternative is jQuery.ajax, which you can read up on here. Both pages should conrtain enough information for you to hit the ground running but if not, I would be happy to prepare some examples for you.
Good luck.

Load data with AJAX only if it has not already been loaded?

I need to load data for my JavaScript app to use. I would like to load the following:
userlist JSON
milestones JSON
Tags JSON
user ACL permissions JSON
These 4 items of data from the server as JSON should be loaded using AJAX but only loaded once.
So I need code that will check to see if the data is loaded already and if it is, use it. If it is not loaded yet, it would make an AJAX request and load the data, and then use it.
I have multiple JavaScript files which need access to this data so I want to make sure that any of them can access it, and whichever once calls for it first will load it using AJAX and make it available for the other scripts to call it without making multiple repeat AJAX requests.
How could I go about this using JavaScript and jQuery?
A basic example would be super appreciated and useful. Thank you
If any of these are not set, load them using AJAX. After loading with AJAX, set these vars for the next caller to access them without a new AJAX request being made...
var userList = userJsonData;
var milestoneList = milestoneJsonData;
var tagList = tagJsonData;
var useAclPermissions = useAclPermissionsJsonData;
Just store the data in a global javascript variable, which is set to null, when your page loads. The first script which loads the data, stores it in the variable, all the other scripts try to access the content of the variable, and if not set, load it:
var milestoneData = null;
function getMilestoneData() {
if (milestoneData === null) {
//make the ajax request, and populate milestoneData variable
} else return milestoneData;
}
According to can i use you can check out localstorage aka webstorage. If you can use it, it might solve your issues. There is a jQuery plugin available. jstorage is an alternative, and has a really simple example at the bottom of the page. Hope this helps.

JQuery Send data to page using jQuery Post and data()

I'm having a bit of difficulty conceptualising this: I have some data stored to a button:
var input2 = '<button id="viewmap1" class="viewmap">Find on Map</button>';
//MAKE DATA
$(input2).data('longlat', coords);
Now I want to send that data to another page. I understand I am to use jQuery post, eg:
$.post("test.html", { func: "getNameAndTime" },
function(data){
alert("Hello");
}, "json");
But im not entirely sure how to go about it. Can any one point me in the right direction? Thanks
Sending data to a different page isn't as simple as it sounds. If it were simple, crackers could manipulate all the other pages that you currently have open in browser tabs.
When you call $.post(), that just sends data to the server, not to another page. The URL is a way to tell the server how to process the data but it doesn't magically connect you to the browser tab/window which has test.html open.
The usual solution is to use a single page which contains the button and the elements to display the results (a.k.a "view"). You send the POST request and then update the view in the callback function.
$(input2).on('click', function(){
// do your post stuffs
});
then need to trigger the button click
$(input2).click();

Multiple AJAX responses

I have a page where a user can "view more info", an ID is sent to a php page which then queries the database. It then returns some data, with some of the data I want to put this into a textarea, the other into a standard div.
How can I send multiple responses back, and how do I know what the data is? e.g. send name and address, how do I know what the php page is sending back so that I can interpret the data on client side?
Is there a better way than using
httpxml.responseText.indexOf("something")
As the two responses may contain similar data? What I hope to do is send two variables from the PHP page and then "see" these variables on client side?
Hope I haven't made this too confusing, thanks.
Javascript only please.
Return JSON containing all your values from the PHP. Then after getting the response your javascript can do whatever you'd like to do with the values.
http://www.php.net/manual/en/function.json-encode.php
--PHP--
$responseArr = array('a'=>1, 'b'=>2);
echo json_encode($responseArr);
If I remember correctly (i do this with jQuery now), just performing eval() on your response text will form the object for you.
--javascript-- (just vanilla js right? you didnt mention jQuery or anything)
this is probably inside your onreadystatechange block
var r = xhr.responseText; //assuming you name the XMLHttpRequest object 'xhr'
var rlist = eval('('+r+')');
document.getElementByID("foo").innerHTML = rlist['a']; //or whatever you want to do with these
document.getElementByID("bar").innerHTML = rlist['b'];

Categories

Resources