I have button below on my index.html:
<button value="about_us.php" onClick="fNt(value)">About Us</button>
<button value="faq.php" onClick="fNt(value)">FAQ</button>
<button value="contact_us.php" onClick="fNt(value)">Contact Us</button>
which I want to use AJAX to get info from php page as of value. I know I can create 3 AJAX function to target 3 php page, but if I have more buttons later it will consume much space.
So, I wonder is it possible to write something like this?
<script>
function fNt(value) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","variable of clicked value",true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200{
document.getElementById("ajax").innerHTML = xmlhttp.responseText;}}}
</script>
I know the script above won't work, it is just to show you what I try to achieve, any idea how to do it? Pls help.
Try this, It will help you...
function fNt(url) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("ajax").innerHTML = xmlhttp.responseText;
}
}
}
<button onClick="fNt('about_us.php')">About Us</button>
<button onClick="fNt('faq.php')">FAQ</button>
<button onClick="fNt('contact_us.php')">ContactUs</button>
Happy Coding
Regardless, you will have to create a separate callback for each button (unless you want the action of clicking each button to do the exact same thing). Why not put the uniform ajax code in a function and pass to that function a url and a separate callback function. If you want to check the request object status, just pass it directly to the callback:
function doGet(route, callback){
var xhr = new XMLHttpRequest(),
method = "GET",
url = route; //If you need to massage the route or anything
xhr.open(method, url, true);
xhr.onreadystatechange = callback(xhr);
xhr.send();
}
Then to call it:
var route = "routedesired.com";
var callback = function(xhrObj){
if (xhrObj.readyState == 4 && xhrObj.status == 200{
console.log("HELLO WORLD")
}
}
Another Approach
I don't understand what exactly you are trying to do, but if you want to do something different for each link, you can just add the route to the callback function as well inside the doGet function I created:
function doGet(route){
var xhr = new XMLHttpRequest(),
method = "GET",
url = route; //if you need to massage the route or anything
var callback = function(routeParam){
if (xhr.readyState == 4 && xhr.status == 200{
switch(routeParam){
case "faq.php":{
//do some action if route is "faq.php"
}
break;
//continue with the same logic for other URL's
}
}
}
xhr.open(method, url, true);
xhr.onreadystatechange = callback(route);
xhr.send();
}
Then to call it:
<button onClick="doGet('about_us.php')">About Us</button>
<button onClick="doGet('faq.php')">FAQ</button>
<button onClick="doGet('contact_us.php')">Contact Us</button>
Ultimately, there are different ways to structure it to automate the process and reduce the amount of code that you need. A part of how you approach it is dependent on what you plan on doing after the request succeeds.
Related
I have an anchor link with no destination, but it does have an onClick event:
<li><a href onClick='deletePost()'> Delete </a> </li>
I understand that I cannot directly execure PHP code blocks in JavaScript due to the nature of PHP and it being a server side language, so I have to utilize AJAX to do so.
When the delete link is clicked, I need it to execute this query (del_post.php)
<?php include("connect.php");
$delete_query = mysqli_query ($connect, "DELETE FROM user_thoughts WHERE id = 'id' ");
?>
I have tried to understand AJAX using similar past questions, but due to being relatively new, I cannot completely grasp it's language. Here is what I have tried:
function deletePost() {
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
xmlhttp.open("GET", "del_post.php", false);
xmlhttp.send();
}
}
}
But clicking the link just changes the URL to http://localhost/.
I believe the (main) problem is your empty "href" attribute. Remove that, or change it to href="#" or old school href="javascript:void()" (just remove it, imo).
It's been a while since I used XMLHttpRequest and not something like jQuery's .ajax, but I think you need to do it like so (mostly you need to .open/send before you watch for the state change):
var xmlHttpReq = new XMLHttpRequest();
if (xmlHttpReq) {
xmlHttpReq.open('GET', 'your-uri-here.php', true/false);
xmlHttpReq.onreadystatechange = function () {
if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) {
console.log('success! delete the post out of the DOM or some other response');
}
else {
console.log('there was a problem');
}
}
xmlHttpReq.send();
}
Can you please provide your : del_post.php file?
Normally you can show a text or alert in a
<div id="yourname"></div>
by using callback in an AJAX request :
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("yourname").innerHTML = xmlhttp.responseText;
}
This response is coming from your PHP file for example :
function remove_record(ARG){
if ($condition==true)
echo "TRUE";
else
echo "FALSE";
}
You should remove href attribute from anchor tag and style the element with CSS.
Also, your script should look like this:
<script>
function deletePost() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Do something if Ajax request was successful
}
};
xhttp.open("GET", "del_post.php", true);
xhttp.send();
}
</script>
You are trying to make the http request inside the callback.
You just need to move it outside:
function deletePost() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "del_post.php", false);
xmlhttp.send();
}
Removing the href attribute will prevent the refresh. I believe that is valid in HTML5.
Ok... I'm just a hobbyist, so please forgive me any inaccuracies in the typing but this works: A format I use for an ajax call in an <a> element is:
<a href="javascript:" onclick="functionThatReallyCallsAjax()">
So that I have more flexibility(in case I need to check something before I send the ajax). Now, for an ajax call you need:
What file to call
What to do with the response from the file you called
What to do if an I/O error happens
So we have this function - not mine, leeched amongst thousands from somewhere - probably here :) - and probably well known, my apologies to the author, he is a genius: This is what you call for the ajax thing, where 'url' is the file you want to 'ajax', 'success' is the name of the function that deals with results and error is the name of the function that deals with IO errors.
function doAjaxThing(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
You will naturally need to include the success+error functions:
function dealWithResponse(textFromURL)
{
//textFromURL is whatever, say, a PHP you called in the URL would 'echo'
}
function ohNo()
{
//stuff like URL not found, etc.
alert("I/O error");
}
And now that you're armed with that, this is how you compose the real call inside the function you called at the <a>:
function functionThatReallyCallsAjax()
{
//there are probably many scenarios but by having this extra function,
//you can perform any processing you might need before the call
doAjaxThing("serverFile.php",dealWithResponse,ohNo);
}
One scenario might be when you need to pass a variable to the PHP you didn't have before. In this case, the call would become:
doAjaxThing("serverFile.php?parameter1=dogsRock",dealWithResponse,ohNo);
And now not only you have PHP sending stuff to JS, you have JS sending to PHP too. Weeeee...
Final words: ajax is not a language, its a javascript 'trick'. You don't need to fully understand what the first 'doAjaxThing' function does to use this, just make sure you are calling it properly. It will automatically 'call' the 'deal WithResponse' function once the response from the server arrives. Notice that you can continue doing your business (asynchronous - process not time-tied) till the response arrives - which is when the 'deal WithResponse' gets triggered -, as opposed to having a page stop and wait (synchronous - time tied) until a response arrives. That is the magic of ajax (Asynchronous JAvascript and Xml).
In your case you want to add the echo("success") - or error! - in the PHP, so that the function 'dealWithResponse' knows what to do based on that info.
That's all I know about ajax. Hope this helps :)
I need to download a file from a link I am given. In order to do this I must make a get request to that link. It can have 3 states:
1. Code 200 and the download will begin once the request landed
2. Code 202 which means I must repeat the request because the file is being uploaded
3. Error code and I must create a dom element that shows that.
How it works:
I make a request to this rails action:
def by_month
export_form = Commissions::ByMonthForm.new(current_user)
if export_form.submit(params)
#export = export_form.export
else
show_errors export_form.errors
end
end
This in turn starts the file upload. Which I don't know when it's ready(depending on how big the file it is). Now I must create a javascript get request to a link that follows the indications I have given at the beginning of the post. And integrate it in the by_month.html.erb view from rails . The javascript I managed to write is:
function httpGetAsync(theUrl){
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
redirect_to_main();
}
else if(xmlHttp.status == 202) {
httpGetAsync(theUrl);
}
else {
make_error_css();
}
}
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
However I don't think it works. Any ideas of how I can do this?(redirect_to_main and make_error_css are functions that I will implement myself later).
Update As per the comments below
Can you try this,
function httpGetAsync(theUrl){
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
redirect_to_main();
}
else if(xmlHttp.status == 202) {
setTimeout(
makeRequest(theUrl),
3000);
}
else {
make_error_css();
}
}
}
//makeRequest(xmlHttp, theUrl);
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
function makeRequest(theUrl){
httpGetAsync(theUrl);
}
makeRequest() is where the request is made again if the status is 202.
The javascript code will be launched from www.example.com through the url bar in google chrome so i cannot make use of jquery. My goal is to pass the full html source code of www.example.com/page.html to a variable in javascript when i launch the code in www.example.com. Is this possible? If so how? I know to get the current page source it's just document.documentElement.outerHTML but i'm not sure how i'd do this. I think it's possible by using responseText somewhere in the following code:
http.send(params);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://www.example.com/page.html",true);
xmlhttp.send();
data = ""
url = "http://www.example.com/page.html"
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4){
data = xhr.responseText
}
}
xhr.send();
function process(){
url = "http://www.example.com/page.html"
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4){
alert(xhr.responseText)
}
}
xhr.send();
}
this is how i run script from the address bar.. I do it all the time..
i create a bookmark like this
javascript:script=document.createElement('script');script.src='http://10.0.0.11/clear.js';document.getElementsByTagName('head')[0].appendChild(script); void(sss=1);
then i host the js file on my computer.. i use analogx simpleserver... then you can use a full page for your script
I'd like to make a popup preview of a textarea, using a PHP function inside the popup.
Let's say you type "Hello world" in the textarea, then you click "preview" and you get your text converted to "Hey you" by a PHP function in a popup (of course the function is not that simple, that's the reason why I can't adapt this in pure javascript).
Is it possible to do so ?
I know it could easily send the form to an intermediate page, but I must keep the form in background... that's why I need a quick preview on fly.
I did the following:
function PreviewMe() {
var newWin = window.open("", "_blank");
newWin.document.write("<html><body>"+document.getElementById('myText').value+"</body></html>");
newWin.document.close();
}
and
<textarea id="myText" ... />
<input type="submit" ... onclick="PreviewMe();">
Obviously it works without reformatting anything, so how to reformat this result in the popup please ?
Would it be possible (and mayber a better option) to use XMLHttpRequest ?
Thx !
Yes , you should use an XHR request to send data to a script which will return you data to be manipulated on the client side.
Thanks, it was by far easier in the end.
In case it might help others, here is what I've done.
Js function became :
function PreviewMe() {
var xhr = null;
if (window.XMLHttpRequest || window.ActiveXObject) {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
} else {
xhr = new XMLHttpRequest();
}
} else {
alert("XMLHTTPRequest not supported...");
return;
}
xhr.open("POST", "page.php", true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
document.getElementById('show').innerHTML = xhr.responseText;
}
};
xhr.send("var="+document.getElementById('myText').value+"");
return;
}
Of course page.php includes my PHP function, show is the id of the div where the result is printed.
Why does my post data appear on a new blank page rather than the div I specified? This script is in the head of a page called order.php. I want the data submitted to be written in the "message" div I created on order.php. But when I submit, I am redirected to update.php where the data is written on a blank page.
<script type="text/javascript">
function insert() {
if (window.XMLHttpRequest) {
xmlhttp = new XLMHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("message").innerHTML = xmlhttp.responseText;
}
}
parameters = 'child_name'+document.getElementById('child_name').value;
xmlhttp.open('POST', 'update.php', true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(parameters);
}
</script>
you current page is order.php and your posting it to update.php by doing this xmlhttp.open('POST', 'update.php', true);
This might be due to normal form submission event.
use a simple jquery
$("#form").submit(function(){
$.post("update.php",{paramertes:'child_name_'+$("#child_name").val()},function(data){
$("#message").html(data);
})
return false;//don't forget to use this
})