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.
Related
I have a controller that takes a lot of data by file and inserts it into the database. How can I show the user some status about how much code is run.
For example, I want to show statuses like, "file upload was done", "data is being validated", "data is inserted" etc. My initial approach was to use the session.
I inserted something like the following in appropriate places on controllers.
..
..code for file upload
..
session()->put('_order_upload_status','file upload done');
..
..code for validation
..
session()->put('_order_upload_status','data is being validated');
Then on the front end, I ran a bit of js code to get the status periodically.
function intervalAction()
{
var intervalID = window.setInterval(getStatus, 500);
}
function getStatus()
{
var request = new XMLHttpRequest();
var url = '{{ route('order.upload.getStatus') }}';
request.open('GET',url,true);
request.onload = function(){
document.getElementById('percentageModalTextBox').innerHTML = this.response
};
request.send();
}
The url {{ route('order.upload.getStatus') }} does nothing more than to get the session data.
However, this approach is not working. I can get the correct session only after the file upload controller runs completely. So I am getting nothing for a long time and only the last status after everything is over.
How can I show the status update to the user?
So I have already had my first experience with Web Design, but there were some things I did in a certain way that I didn't like, mainly because of time. So anyway, I don't know which is the correct way to handle sessions. What I did in my previous project was to embed PHP into HTML and based on whatever was in $_SESSION, usually an id and a user type number, then I'd open or close parts of the website to the user, through embedded PHP.
However, this is not how I wanted to do this initially, at first what I wanted to do was to make a JavaScript code to send a request through AJAX to the server, and check if the session was still active, and based on that open/close parts of the website, but then I'd have to make a request on every page and every so often to make sure the user is logged in. Should I handle something like this client-side?
What are some other ways to check the session but without embedding PHP and using JavaScript instead to modify the HTML document.
To do this, all you need is an ajax request on loop and a php file to check the session.
The Javascript
function checkLogin(un) { //put this function in a loop of some sort depending on how you want to use it
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
logout(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "checklogin.php?un=" + un, true);
xmlhttp.send();
}
function logout(resp) {
if (resp == "false") { //comparing actual text, not boolean
window.location.href = 'logout.php'; //destroy the session or something
}
}
The PHP file checklogin.php (very simple)
<?php
if ($_SESSION[$_GET['un']] != true) {
echo 'false';
}
?>
The php will depend on how you store your sessions, but in this case it is just using one session titled by their username that stores true if signed in. I would recommend making this more complex if you decide to actually use it.
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
CONTEXT:-
This question is about some basic concepts about AJAX. I have been following this tutorial and this example for the JS part, and this (the last one on this page) for the PHP part.
So suppose the scenerio is that the JS is invoked on the click of a button. Now when the button is clicked and the JS function is invoked, the entire web page is already loaded. So if I pass a variable from JS in the URL passed from the XMLHTTPRequest.open() function (and using the GET method), the variable is sent to the $_REQUEST array on the server-side.
1. Now since the page has already been loaded, so how can I make changes to, say the value of an element's attribute, while the element is already displayed.
SCENERIO:-
I have a PHP array with HTML for three div's, and they are echoed/displayed. Initially all the divs except the first one have a display:none; style property. Now on the click of a button in the first div, I want to call a JS function where I set display:none to the first div, and display:block; to the second div. Now that is easy. But I want this change in the display property in the HTML for the respective div in the aforementioned array on the server side as well.
So I figured I need AJAX. Following this example, I tried sending a variable in URL, and then tried to get the variable from $_REQUEST, but $_REQUEST does not seem to contain it. Although I asked this question here, but I feel it might be because the part of the page where I am writing the code to get the variable from $_REQUEST is already executed, I am wondering where should I write the code to execute only after the click of the mentioned button?
2. Basically where do we write the AJAX script since the code for the page is already executed?
NOTE:- Don't suggest JQuery. I can't use JQuery, I can use YUI though. I searched SO and found solutions using some JQuery method.
JS CODE:-
function xyz(var divIdOne, var divIdTwo) {
document.getElementById(params.divIdOne).style.display = "none";
document.getElementById(params.divIdTwo).style.display = "block";
document.getElementById(params.divIdTwo).style.border = "5px solid red";
var xmlhttp;
if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest();}
else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.open("GET","myfile.php?pass_back="+"pass_back",true);
xmlhttp.send();
}
Where in the server side PHP script do I write the code which receives the variable from the URL so that it is executed after the button is clicked (the button whose click event invoked this JS fucntion).
I was trying to do something like this at a random place in the server file but it does not work out:
foreach($_REQUEST as $requestkey => $requestvalue) { //loop for just checking the elements of $_REQUEST
echo $requestkey.': '.$requestvalue;
}
if (array_key_exists('pass_back', $_REQUEST)) {
foreach ($array_of_divs as $div) {
if ($div->id=$divIdOne) {
$div->style='display:none';
} else if ($div->id=$divIdTwo) {
$div->style='display:block';
}
}
} else {echo 'FALSE!';}
Let me see if i understand correctly:
You set the display property on some div with js.
You want to update some flag on your server so next time a request is made you get the same display properties as the client.
AJAX is asynchronous, so you can call it wherever you want (your button click, document ready, etc).
Make an AJAX request to some url in server that can answer it and update your flags with the values you want. You may need some kind of persistence to keep those for the next time you reload your page or you won't notice any change.
Make sure you understand what AJAX is.
Here's an example of an AJAX function:
function ajax(url, method, send, success){
var x = new XMLHttpRequest || new ActiveXObject('Microsoft.XMLHTTP'), ec = [], s, sl;
if(send){
for(var i in send){
ec.push(encodeURIComponent(i)+'='+encodeURIComponent(send[i]));
}
s = ec.join('&').replace(/%20/g, '+'); sl = s.length;
}
else{
s = null; sl = 0;
}
if(method.match(/^get$/i)){
s = s === null ? '' : '?'+s;
x.open('GET', url+s); x.send();
}
else{
x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
x.setRequestHeader('Content-length', sl);
x.setRequestHeader('Connection', 'close');
x.open('POST', url); x.send(s);
}
if(success){
x.onreadystatechange = function(){
if(x.readyState === 4 && x.status === 200){
/* when PHP has processed what you send through `.send()` or a $_GET URL
your function will fire with the evaluated responseText passed to it
*/
success(eval('('+x.responseText+')'));
}
}
}
}
ajax('page.php', 'GET', {property:'value', property2:'value2'}, function(data){
/* when PHP has processed what you send through `.send()` or a $_GET URL
the anonymous function here executes sending what should be JSON
(if you `echo json_encode($associativeArrayYouMake);`on your PHP page)
through the data argument here - so data is JSON containing your PHP
Associative Array properties
*/
// affect the DOM
// document.getElementById('someId').innerHTML = data.some_property;
// or document.getElementById('someId').innerHTML = data['some_property'];
});
I'm thinking about adding some twitter functions in my web-application, so I started doing some tests. I checked the way to call the search twitter URL (more info in: http://dev.twitter.com/doc/get/search) in order to get tweets that contains the searched word/sentence. I realized that you can do it in php just getting the JSON file that the search URL returns with the file_get_contents() function. Also you can do it directly in JavaScript creating a script object, appending it to the body and use the callback parameter of the search URL to process the data.
Different ways to do, but that's the way I finally did it:
MAIN HTML FILE:
<title>Twitter API JSON</title>
<script type="text/javascript">
//function that created the AJAX object
function newAjax(){
var xmlhttp=false;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
//function that search the tweets containing an specific word/sentence
function gettweets(){
ajax = newAjax();
//ajax call to a php file that will search the tweets
ajax.open( 'GET', 'getsearch.php', true);
// Process the data when the ajax object changes its state
ajax.onreadystatechange = function() {
if( ajax.readyState == 4 ) {
if ( ajax.status ==200 ) { //no problem has been detected
res = ajax.responseText;
//use eval to format the data
searchres = eval("(" + res + ")");
resdiv = document.getElementById("result");
//insert the first 10 items(user and tweet text) in the div
for(i=0;i<10;i++){
resdiv.innerHTML += searchres.results[i].from_user+' says:<BR>'+searchres.results[i].text+'<BR><BR>';
}
}
}
}
ajax.send(null);
} //end gettweets function
</script>
#search_word Tweets
<input type="button" onclick="gettweets();"value="search" />
<div id="result">
<BR>
</div>
</html>
PHP WHERE WE GET THE JSON DATA:
$jsonurl = "http://search.twitter.com/search.json?q=%23search_word&rpp=10";
$json = file_get_contents($jsonurl,0,null,null);
echo $json;
And that's it, in this way it works fine. I call the PHP file, it returns the JSON data retrieved from the search URL, and in the main HTML JavaScript functions I insert the tweets in the div. The problem is that at the first time, I tried to do it directly in JavaScript, calling the search URL with Ajax, like this:
MAIN HTML FILE:
//same code above
//ajax call to a php file that will search the tweets
ajax.open( 'GET', 'http://search.twitter.com/search.json?q=%23search_word&rpp=10', true);
//same code above
I thought it should return the JSON data, but it doesn't. I'm wondering why not and that is what I would like to ask. Does someone have any idea of why I can't get JSON data using the Ajax object? If the search URL http://search.twitter.com/search.json?q=%23search_word&rpp=10 returns JSON data, it should be obtained in the ajax object, right?
XHR requests are generally limited to same-domain requests; e.g, if you're on bertsbees.com, you can't use an Ajax method to pull data from twitter.com.
That said, Twitter's API supports a popular data transport method known as JSON-P, which is really just a glorified injection technique. You simply pass it a callback method, and the data returned will be wrapped in your desired function, so it gets eval'd and passed in.
You cannot make a cross domain request using javascript, unless you are doing from an browser addon.