Ajax ready/notready button without refresh - php

I am pretty much new to coding but i am learning along the way. i managed to make my buttons in php etcetera but ofcource this refreshes the page which made it very annoying.
I looked around and came to know Ajax. i managed to get certain page parts to auto refresh it's data and i also managed to make a button that changes it's test from Ready / Not Ready and sending data to a php file that processes it and updates the database.
However i am facing with one problem. for example, if a user uses the button sometimes and the database value is set to Ready. if they refresh the page. or close and come back the button would say it's default value Ready while the database already has it set Ready.
The eventual goal is that a user can set his status to ready or not ready for a game match. where the database gets updated so that info can be shown to other users.
I will post my code below, sorry if the code is a mess i can understand it very well might be since i took the pieces from examples on the internet.
var xmlHttp_five = AJAX();
function ajaxFunction(pid) {
var getdate = new Date(); //Used to prevent caching during ajax call
if(xmlHttp_five) {
var txtname = document.getElementById("txtname");
xmlHttp_five.open("POST","includes/gather_buttons.php",true); //calling testing.php using POST method
xmlHttp_five.onreadystatechange = handleServerResponse;
xmlHttp_five.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp_five.send("txtname=" + txtname.value + "&pid=" + pid); //Posting txtname to PHP File
}
}
function handleServerResponse() {
if (xmlHttp_five.readyState == 4) {
if(xmlHttp_five.status == 200) {
if (document.myForm.button1.value == "Ready") {
document.myForm.button1.value = "Not Ready";
document.myForm.txtname.value = "Waiting";
} else {
document.myForm.button1.value = "Ready";
document.myForm.txtname.value = "Ready";
}
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
and the form below
<form name='myForm'>
<input type='hidden' name='txtname' id='txtname' value='Ready'/>
<input type='button' class='button2' id='button1' value='Ready' onclick='ajaxFunction($pid);' />
</form>
If i need to give more info please say so, sorry if i am not supposed to post this here.
Thank you in advance.
Best regards,
Johan

Your form should be generated by server-side script. So when user refreshes page, he gets actual data from the database.
Otherwise if you can't generate form by server-side script, you should use preloader: button's value initially should be "loading..." and script should request the value by Ajax.

Related

Comment section for each thread not loading comments properly

I'm building a website where people can leave comments on each event created by me. Each event has its own page eg. showthread.php?t=1, showthread.php?t=2 and so on..
I managed to create a comment section for each event but I got a problem with loading comment for each event. I used $_SESSION['id'] to pass the $_GET['t'] value to another php script
My code is like this:
showthread.php
$id=$_GET['t'];
$_SESSION['id']=$id;
main_function.php
$thread=$_SESSION["id"];
SELECT * FROM comment WHERE thread='$thread' ORDER BY timestamp DESC,
these codes are working fine but I need to refresh the page in order to load the right comment for each thread, is there a way for me to load it properly without refreshing each time I load an event? thanks in advance!
AJAX is javascript used to make requests to the server. You can use it to change your page without refreshing.
Learn more here.
An example of what it looks like:
//create the request object
var xhttp = new XMLHttpRequest();
//activates when you hear back from the server
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//xhttp.responseText is filled with what we get back from the server
document.getElementById("my-element-thing").innerHTML = xhttp.responseText;
}
};
//Type of request, url you're sending to, asyncronous
xhttp.open("GET", "www.google.com?p=myparam", true);
//Send your request to the server
xhttp.send();
Edit: The idea is you would also build a PHP page to accept this request. PHP would analyze it and then echo a response. Be sure that the PHP only contains what you want and nothing else (no tags etc).
Have you tried to use javascript AJAX?
https://www.w3schools.com/xml/ajax_intro.asp

how to refresh the Div part of my page using javascript after ajax call

i am submitting a form using Ajax and storing the data in the database. It is storing the data in the database and without reloading the page it is giving alert box showing that that content has been added.
The same page is showing the content of the database, i need that part to refresh automatically without reloading the page so that it can also fetch the just added information.
<script type="text/javascript">
function GetXmlHttpObject()
{
if(window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if(window.ActiveXobject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function submitformwithajax()
{
var myAjaxPostrequest=new GetXmlHttpObject();
var coursename=document.getElementsByName('cvalue')[0].value;
var parameter="cvalue="+coursename;
myAjaxPostrequest.open("POST", "process/do_course.php", true);
myAjaxPostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myAjaxPostrequest.send(parameter);
myAjaxPostrequest.onreadystatechange=function(){
if(myAjaxPostrequest.readyState==4){
if(myAjaxPostrequest.status==200){
if(myAjaxPostrequest.responseText=="true")
{
alert("Course Has Been Successfully Added To The Curiculum !");
var container = document.getElementById('c');
var refreshContent = container.innerHTML;
container.innerHTML = refreshContent;
}
}
else
document.getElementById("submitcourse").innerHTML="An error has occured making the request";
}
}
}
</script>
'c' is the ID of the div tag which has to be reloded.
Thanks
This seems a bit nonsense:
var refreshContent = container.innerHTML;
container.innerHTML = refreshContent;
That way you're not refreshing, the content is exactly the same.
I don't know exactly what do you mean by "DB content", assuming coursename is what you want to add to your DIV then you have to do something like:
container.innerHTML += '<p>'+ coursename +'</p>';
jQuery would benefit your work a lot, your current code via jQuery would look like
function submitformwithajax() {
var coursename = $("[name=cvalue]").val();
$.post("process/do_course.php", {cvalue: coursename}, function(response) {
if (response === "true")
{
alert("Course Has Been Successfully Added To The Curiculum !");
var container = $("#c");
// Not sure why you're setting the container to the container here
container.html(container.html());
}
else
$("#submitcourse").text("An error has occured making the request");
}, "text");
}
I don't know why you set the text of the container to the text in the container but that may be an issue you are having. If your server response returns the data that needs to be displayed in th area you can use jQuery (or if you really prefer, the DOM) to update the fields or elements (or add as needed) on the fly. If you need to refresh that section based off a GET request, then just make a GET request for the data in the success statement.
I would also recommend using JSON for the return type from the server instead of plain text. A {"success": true} will allow you to check if (response.success) instead of using string comparison there.
Also, as a final side note, in Javascript you should always prefer === over == as === verifies that value and type both match, the downside to this is that in Javascript 1 == "1" but 1 === "1" is not true.
EDIT
In response to your comment, should you not persue the jQuery route, you can still implement all of that which I have explained here however you'll have to manually parse the response:
var resposne = JSON.parse(myAjaxPostRequest.responseText);
From there you can still check if (response.success).
I, personally, recommend showing the students how to do it this long and complex way, and then teaching them how to do it with jQuery. Should any of them pursue a web development career then they will either use jQuery or something very similar in function to it and it's best they learn about these things early on instead of after they get hired. I also suggest JSON returns from the server because it's a more expressive way to return data, instead of just "true" (what is true?) you say {"success": true} so you can see the request was successful.
The easiest way to do this is going to be return the contents of the "c" element from the ajax call, and then replace the old contents of "c" with the content returned by the ajax call.
After seeing your code: You are not filling that table with AJAX. I can only give you this advice. Fill that table dynamically with Javascript.
Create function which will find div#c.
If div#c has some children, destroy them.
Create a new element table.
Fill that table with new rows.
This is how you can make a table dynamically with data from the server which is provided by Ajax. So after sending data from the form you can call this function and your table will be recreated.

Ajax call that will put a click event into a php variable to avoid the window.open() method

I have this jQuery scrip which counts the number of clicks on a certain div and then, at the second click, it redirects the user to a custom url.
The script works and counts the clicks even if the user leaves the page.
function traffic(){
var traffic = $('.model').data("traffic");
if(traffic){
var nbc = localStorage['nbc']||0;
$('.model a').click(function(){
localStorage['nbc'] = ++nbc;
if(nbc%2==0){
window.open(traffic, '_blank');
}
});
}
}
Now, I am a total newb with ajax (actually i do not know anything about it, I am a webmaster not a programer with an overdue deadline) and I need some help:
I need an ajax call that, on the time of the action, will send the second click into a php variable so I can use a code like the following (and avoid the "window.open" method which is in conflict with another script I use on the page):
if($number_of_clicks == 2){
echo 'my new link, a method which will save me from using window.open';
} else {
echo 'my ragular link';
}
Can it be done?
UPDATE
Let me explain, my fault for not being clearer.
User enters my site and clicks on a normal link. Jquery stores that event and the user goes to an internal page.
When he hits the home button, ajax sends that event to a php variable, so I'll have $myvar=1.
Now I can change that certain link on my site with:
if($myvar == 1){
echo 'my new link';
} else {
echo 'my ragular link';
}
And now, when the user clicks on that link, he will go to the new link.
Hope I've been a little clearer.
Ty!
The only way to get a click to PHP is to just an AJAX request. EG:
$.get('/clickonce.php');
and then in PHP you could do:
<?php
$myvar = 1;
?>
But this wouldnt be perfect. The clickonce.php code will be called, but there is a delay since it's a new page request, so with slow internet/server responds it could be more then a few seconds before it is actually logged.
Considering that your window.open is conflicting with another script, which I assume is javascript, i would go for a javascript solution.
var clickedOnce = false;
function traffic(){
var traffic = $('.model').data("traffic");
if(traffic){
var nbc = localStorage['nbc']||0;
$('.model a').click(function(){
localStorage['nbc'] = ++nbc;
if(nbc%2==0){
window.open(traffic, '_blank');
} else {
clickedOnce = true;
}
});
}
}
now in your other javascript script you can check for if (!clickedOnce) { //do something }
Well, you can simply make an AJAX get request using jQuery.
$.get('/your.php', function(url) {
// value echoed by your php page will be available in the url variable passed into this function.
// You can do what you want with it.
alert(url);
});

How to make PHP function run after javascript ends?

I have two PHP functions - one that builds a html form and another that handles it when it's submitted.
I want to add to the html a javascript onClick function that sends one of the form's fields to an external API (Google Maps) and saves the reply in a hidden field in the form so that the handling PHP function will get that data as well.
My question is - how do I make sure the handling PHP function only fires after the onClick function has finished?
Or maybe I can't and I have to use ajax?
You'll need 2 events to accomplish this.
the onClick event for your button that executes the google map request and saves the data into the local form
an onSubmit event for your form. You will use this event to see if the form is submittable. Basically, check to make sure that your google map request has been run and has completed before allowing the form to submit.
Example:
<script>
var googleMapsDone = false;
$('#gmap_button').click(function(event)
{
doGoogleMapThing(function()//callback from googlemaps
{
//save data to local form for processing by script once posted
googleMapsDone = true;
});
});
$('#form').submit(function(event)
{
//check to see if we did our google maps stuff, and that its done
if (false == googleMapsDone)
{
event.preventDefault();
return false;
}
});
</script>
With that code, any time the user is waiting for google maps and clicks submit, nothing will happen. They would have to wait on the response from GMaps, THEN click submit. This is okay for some things, but if you're trying to do background requests to GMaps that require no user input/interaction/feedback (maybe getting Long/Lat of their address when they submit a form), then you can modify the code a bit to post when you get the response. An example of that would be:
<script>
var googleMapsDone = false, submitWaiting = false;
$('#gmap_button').click(function(event)
{
doGoogleMapThing(function()//callback from googlemaps
{
//save data to local form for processing by script once posted
googleMapsDone = true;
/* check to see if submitWaiting is TRUE. If it is, automatically
post the form when we get the response.
*/
if (submitWaiting)
{
$('#form').submit();
}
});
});
$('#form').submit(function(event)
{
//check to see if we did our google maps stuff, and that its done
if (false == googleMapsDone)
{
event.preventDefault();
/* set our submitWaiting flag which we will use in our clalback
so when we get our google maps response, we post our form right
away
*/
submitWaiting = true;
/* You might want to display a modal or some other kind of notification
that the form post is 'working' or 'processing' so when the user
clicks it and doesn't see anything happening, they don't bail
or click it 800 times out of frustration
*/
return false;
}
});
</script>
edit: I realize my comment below on how this works are...hard to understand, so let me explain here, then show an alternative.
User fills out form
User clicks button to do stuff on google maps (example was written before I knew the scope/context of the GMaps request, so that's why it's done this way)
If user then clicks 'submit' before the GMap request is complete, we CANCEL the submit and set a flag submitWaiting
GMaps request returns, and executes our callback. Our callback knows how to look for submitWaiting and if it is set to true it submits the form
An alternative to this, instead of requiring user interaction for the GMaps request you could change the event to an onChange event for the input box of the address, or you can do it all via the submit button/event, like so:
<script>
$('#form').submit(function(event)
{
//lets look up our user's address!
doGoogleMapThing(function()//callback from googlemaps
{
//do stuff with your inputs, or whatever
$('#form').submit();
});
event.preventDefault();
return false;
});
</script>
edit note: the examples above assumes you're using jquery, and that your google map API request is done via javascript
If your google map api request is not using the google maps javascript library, this is STILL possible, just requires you to make a "proxy" script to the API via a php script on your local domain. (Browser restrictions). It'd be something like THIS:
<script>
function doGoogleMapThing(callback_when_done)
{
$.post("/path/to/proxy/script.php", { data: to, post: to_server }, function(response)
{
//check & parse response
callback_when_done(/* Data needed to populate form */);
});
}
</script>
note: both of these examples assume jquery usage. because...well..why wouldn't you.
Below is an implementation of your exact script. I changed it a bit to use jquery, because it makes things a bit less painful.
<script type=”text/javascript”
src=”http://maps.google.com/maps/api/js?sensor=false”></script>
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.6.min.js"></script>
<script type=”text/javascript”>
function codeAddress(callback)
{
var address = $('#address').val();
geocoder.geocode( { 'address': address}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
$('#latitude').val( results[0].geometry.location.latitude );
$('#longitude').val( results[0].geometry.location.longitude );
if (typeof callback != 'undefined') //call the callback.
{
callback(true);
}
}
});
/* Just in case google returns a bad response or doesn't return at all
we need to add a timeout that will call the callback after 10 seconds
just so we make sure our user doesn't hang.
*/
setTimeout(function(){
callback(false); //pass false indicating no/invalid response
}, 10000); //10000ms = 10s
}
/* We are using the reallySubmit variable as a flag here, to know when we finish
our call to google maps and that we want to really submit our form.
we have to do this because the form.submit() call fires the form's submit event
again, and we end up going into an infinite loop.
an alternative to this would be to bind your form processing to the form's submit
button's click event. that should also pick up any presses of the enter key, also.
the solution below also works.
*/
var reallySubmit = false;
$('#form').submit(function(event)
{
if (false == reallySubmit)
{
//lets look up our user's address!
codeAddress(function(success)//callback from googlemaps
{
reallySubmit = true;
$('#form').submit();
});
event.preventDefault();
return false;
}
});
</script>
This is fundamentally impossible - PHP runs on the server, JavaScript runs on the client. You will indeed need to use Ajax.
You can have a hidden IFRAME element where you load a php document as soon as your javascript ends. Simple, but effective (as long as your php document comes from the same URL).
AJAX is a must I am afraid. You need to redirect the user to a page with the script.
Once the server has run the PHP to generate the HTML, then sent it to the browser, there is no way to run it again, or indeed run anything from the server, without making a request to the server. That is the nature of a server side scripting language, of which PHP is.

Confused on the basics of AJAX

So right now, I'm just using a basic form to check a password. I want it to check the password and basically remain on page.html so I can use JavaScript to alert incorrect password or something. I'm not really sure how to do that. It seems it would bring me to check.php. I'm not too sure on the whole process, any help appreciated! Thanks!
Page.html
<form action="check.php" method="post">
<input type="password" name="password" />
<input type="submit" value="Submit" />
</form>
check.php
<?php
$password = $_POST['password'];
if ( $password != "testing" ) {
die();
}
?>
PHP runs at the webserver which usually runs at a physically different machine (the server side) than where the webbrowser runs (the client side). The machines are usually connected by a network. HTTP is a network protocol. The webbrowser sends a HTTP request. The webserver retrieves a HTTP request whose URL indicates that it should be forwarded to PHP for further processing. PHP retrieves the HTTP request and does the processing and returns a HTTP response. Usually in flavor of a plain vanilla HTML page. The webserver sends HTTP response back to the webbrowser.
JavaScript runs at the webbrowser and knows nothing about PHP since it runs at the webserver. PHP in turn also knows nothing about JavaScript (although it can produce some JS code which is in turn to be sent to the webbrowser over HTTP). The only way to communicate between JS and PHP is HTTP. One of the ways to let JS fire a HTTP request and retrieve a HTTP response is using XMLHttpRequest. This is the core technique behind Ajax.
I see in your question history that you're already familiar with jQuery. It's a JS library with a lot of convenient functions to fire ajaxical requests. In this specific case you would like to use $.post. E.g.
$('#formId').submit(function() {
$.post('check.php', $(this).serialize(), function(valid) {
if (valid) {
alert('Valid!');
} else {
alert('Invalid!');
}
});
return false; // Important! This blocks form's default action.
});
With in check.php:
<?php
echo $_POST['password'] != "testing";
?>
This is however not unobtrusive. If the user has JS disabled, then all will fail. Your best bet is to check in PHP if an ajaxical request is been fired by jQuery or not and handle accordingly:
if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
// Ajax.
} else {
// No ajax.
}
Alternatively you can let jQuery also reach a different URL or append an extra parameter.
Update: here is how the JavaScript would look like when not using jQuery:
document.getElementById('formId').onsubmit = function() {
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
if (xhr.responseText) {
alert('Valid!');
} else {
alert('Invalid!');
}
}
}
xhr.open('POST', 'check.php', true);
xhr.send(serialize(this));
return false; // Important! This blocks form's default action.
}
function serialize(form) {
var query = '';
for(var i = 0; i < form.elements.length; i++) {
var e = form.elements[i];
if (!e.disabled && e.name
&& ((e.type != 'checkbox' && e.type != 'radio') || e.checked)
&& (e.type != 'submit' || e == document.lastClicked))
{
if (query.length) query += '&';
query += e.name + '=' + encodeURIComponent(e.value);
}
}
return query;
}
document.onclick = function(e) {
e = e || event;
document.lastClicked = e.target || e.srcElement;
}
Bloated and verbose, yes ;)
You'll have to use ajax if you want to remain on the same page. I recommend using jquery and jquery's post function.
Basically you create a javascript function that gets called when the login button is clicked. The function will send a request to check.php. Check.php will output a status message (maybe 1 for succes, 0 for fail) that will be returned to the original script. From there you can output a message saying invalid password, or set a cookie if it was correct.
The simple solution to what you're trying to do (essentially AJAX) is:
Modify your php script to output something unique on success or failure.
Use JavaScript to submit the data to the php script, instead of the normal form POST.
Have the JavaScript alert the user if the password is invalid, or direct to an appropriate page if the password is valid.
Of course those are the broad strokes. In reality you'll need your php script to give one kind of response when an AJAX request (a request made by JavaScript) is made, and another response when the page is requested by a regular form POST - you do want it to work without JavaScript - right? You'll probably want the JavaScript to update the page contents instead of an alert box. You'll want your php script to set session variables so the next page they access knows they are logged in.
Broad strokes.
Reading the jQuery AJAX documentation may help.
When designing a web site, always add JavaScript after everything works fine without it. The reason for this is twofold. For one, some people browse without it turned on. The other reason is that JavaScript is always viewable and editable by the crackers out there.
This approach requires that you have a separate PHP file that validates the success of the password. Everything on the original page (HTML and JS) should only send the password and perhaps wait for the request. To keep things on the same page, you can use AJAX to send the input password and print out the response that it receives. jQuery makes AJAX easy if you don't want mind the overhead.
Using POST over HTTPS is better than using GET and HTTP. Of course, keep track of session variables and you might also want to limit the amount of time from when one first receives the form and when they actually submit it.

Categories