Laravel - load new content from DB using ajax dynamically - javascript

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.

Related

dynamically create more php objects on scroll

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

How to scrape a JavaScript value in PHP

I’m new to PHP and coding in general and I can’t figure this out. I’m trying to get the number of kills from this profile page.
At the moment, the string I am trying to get is:
29362
When I view the page source, this number is nowhere to be seen.
When I use inspect element, however, I find:
<td class="num">29362</td>
How can I get the content shown in inspect element instead of the content shown by viewing the page source?
In using a tool like Firebug for Firefox, or the inspector for Safari and Chrome, you can see that at page load a series of AJAX requests are made for data. Though I didn't dig through all of the data returned by those requests, I do see the data you're looking for in at least one of them:
http://uberstrike.com/profile/all_stats/631163
So at page load JavaScript makes a series of AJAX requests back to the server to get all the data, then it manipulates the DOM to insert it all into the view.
If you wanted, your PHP could directly request the URL I pasted above and json_decode the response. This would produce a data structure for you to use which includes that number in the kills_all_time property.
Quick and dirty example:
<?php
$data_url = 'http://uberstrike.com/profile/all_stats/631163';
$serialized_data = file_get_contents($data_url);
$data = json_decode($serialized_data, true);
var_dump($data['kills_all_time']);
I looked and it looks like there is no API currently, so your best method will be to do an inter-web-server http request. Get the page you want and then it is a lot of string math from there.
I would recommend using string search to find <td class="name">Kills</td> and the kills row will appear right after it. From there its simply extracting the number using string math.
To add to what JAAulde has explained, it seems like there is a method to these AJAX requests. And they are all based on the profile ID that can be found at the end of the URL:
http://uberstrike.com/public_profile/631163
Then in the Safari debugger (which is what I am using) you can see these XHR (XMLHttpRequest) requests which are directly connected to API calls:
Then looking at the data in them shows some really nicely formatted JSON. Great! No scraping! So just go through these URLs to see what you can see:
http://uberstrike.com/profile/items
http://uberstrike.com/profile/user_info/631163
http://uberstrike.com/profile/user_loadout/631163
http://uberstrike.com/profile/all_stats/631163
And looking at the all_stats endpoint shows:
"kills_all_time":29362,
Nice!
So now let’s use some PHP json_decodeing like this:
// Set the URL to the data.
$url = 'http://uberstrike.com/profile/all_stats/631163';
// Get the contenst of the URL via file_get_contents.
$all_stats_json = file_get_contents($url);
// Decode the JSON string with the 'true' optionso we get any array.
$all_stats_json_decoded = json_decode($all_stats_json, true);
// Dump the results for testing.
echo '<pre>';
print_r($all_stats_json_decoded);
echo '</pre>';
Which will dump an array like this:
Array
(
[headshots_record] => 24
[nutshots_record] => 33
[damage_dealt_record] => 6710
[damage_received_record] => 31073
[kills_record] => 50
[smackdowns_record] => 45
[headshots_all_time] => 4299
[nutshots_all_time] => 1925
[kills_all_time] => 29362
[deaths_all_time] => 16491
…
Now to get kills_all_time just do this:
// Return the 'kills_all_time'.
echo $all_stats_json_decoded['kills_all_time'];
Which gives us:
29362

How do I change pages and call a certain Javascript function with Flask?

I am not sure if I worded my question correctly. I'm not actually sure how to go about this at all.
I have a site load.html. Here I can use a textbox to enter an ID, for example 123, and the page will display some information (retrieved via a Javascript function that calls AJAX from the Flask server).
I also have a site, account.html. Here it displays all the IDs associated with an account.
I want to make it so if you click the ID in account.html, it will go to load.html and show the information required.
Basically, after I press the link, I need to change the URL to load.html, then call the Javascript function to display the information associated with the ID.
My original thoughts were to use variable routes in Flask, like #app.route('/load/<int:id>') instead of simply #app.route('/load')
But all /load does is show load.html, not actually load the information. That is done in the Javascript function I talked about earlier.
I'm not sure how to go about doing this. Any ideas?
If I need to explain more, please let me know. Thanks!
To make this more clear, I can go to load.html and call the Javascript function from the web console and it works fine. I'm just not sure how to do this with variable routes in Flask (is that the right way?) since showing the information depends on some Javascript to parse the data returned by Flask.
Flask code loading load.html
#app.route('/load')
def load():
return render_template('load.html')
Flask code returning information
#app.route('/retrieve')
def retrieve():
return jsonify({
'in':in(),
'sb':sb(),
'td':td()
})
/retrieve just returns a data structure from the database that is then parsed by the Javascript and output into the HTML. Now that I think about it, I suppose the variable route has to be in retrieve? Right now I'm using AJAX to send an ID over, should I change that to /retrieve/<int:id>? But how exactly would I retrieve the information, from, example, /retrieve/5? In AJAX I can just have data under the success method, but not for a simple web address.
Suppose if you are passing the data into retrieve from the browser url as
www.example.com/retrieve?Data=5
you can get the data value like
dataValue = request.args.get('Data')
You can specify param in url like /retrieve/<page>
It can use several ways in flask.
One way is
#app.route('/retrieve/', defaults={'page': 0})
#app.route('/retrieve/<page>')
def retrieve():
if page:
#Do page stuff here
return jsonify({
'in':in(),
'sb':sb(),
'td':td()})
Another way is
#app.route('/retrieve/<page>')
def retrieve(page=0):
if page:
#Do your page stuff hear
return jsonify({
'in':in(),
'sb':sb(),
'td':td()
})
Note: You can specify converter also like <int:page>

How to pass value to another static page via javascript?

I am trying to pass value to another page and read the value in the another page. I use only JavaScript and jQuery. Not use others language as PHP. I don't want to be as like (http://www.example.com/?value=test). I am trying to use POST or GET method.
On first page:
$.post("second_page.html",{q:"test"});
window.location.replace("second_page.html");
On second page:
var location_query = window.location.search.substring(1);
var vars = location_query.split("&");
for (var i in vars) {
var param = vars[i].split("=");
params[param[0].toString()] = param[1];
}
If I pass value as like http://www.example.com/?q=test , the second page script is read the value, but I use this line: $.post("second.html",{q:"test"}); not read.
How to pass value from first page to another static page via JavaScript or jQuery or ajax?
See this post says:
POST data is data that is handled server side. And Javascript is on client side. So there is no way you can read a post data using JavaScript.
but you can use cookies to read and store values:
<script src="/path/to/jquery.cookie.js"></script>
you can get it from here
Try with reading the documentation and see if this works for you.
Without using GET or POST you can transfer the content using HTML5 Local Storage or
Web SQL
$.post and $.get send AJAX request and waiting response on current page, you cant send params for next window.location.replace by this.
Use url get-params window.location.replace("404.html?q=404"); and look this for get params on second page.

.load() with data

I want to load data into a checkout page using .load() to load the pages in a modal window. The data that needs to be loaded is a shipping price value, that needs to be usable on the loaded page.
JS
function totalCalc() {
var shipping = ($('#shippingform input[name="shipping"]').val());
$('#cartdialog').load("/ash/shop/checkout.php",[$('#shippingform input[name="shipping"]')]);
alert(shipping);
}
CHECKOUT.PHP
$myTotal = ($subtotal + $_POST['shipping']);
I need the value which is shown through the "alert(shipping);" to be a usable value on checkout.php. You'll see I try to $_POST[] it in a php variable, but it wont work. I must be sending the data wrong...
Per the jQuery API, data sent as a query-string format string through .load() is treated as GET. Data sent as a JSON object is treated as POST. Basically, send it like this:
.load("/ash/show/checkout.php", {shipping: shipping});
As it seems you're using jQuery: http://api.jquery.com/jQuery.post/
or if you want proper control over it, use the ajax method: http://api.jquery.com/jQuery.ajax/
Alternatively, you could add the shipping cost to the URL and use $_GET

Categories

Resources