i want my ajax code should appear with a fadeIn effect [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
this is my html code
<input type="text" name="query_post" id="textid" />
<input type="button" class="gbutton" style="-webkit-user-select: none; opacity:1 " id="shareImageButton" value="Share" onclick="Postquery()">
<div id="new_query_post">
</div>
css
.new_query_post{
display:inline;
}
js
function Postquery() {
// 1. Create XHR instance - Start
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
// 1. Create XHR instance - End
// 2. Define what to do when XHR feed you the response from the server - Start
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200 && xhr.status < 300) {
document.getElementById('new_query_post').innerHTML = xhr.responseText;
}
}
}
// 2. Define what to do when XHR feed you the response from the server - Start
var textid = document.getElementById("textid").value;
// 3. Specify your action, location and Send to the server - Start
xhr.open('POST', 'postquery.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("textid=" + textid);
// 3. Specify your action, location and Send to the server - End
}
php
<?php
$textid =trim($_POST["textid"]);
echo"
<div id='each_query'>
<span style='margin-top:1%; margin-left:3%;float:left;color: #3bb598'>Jan 26'14 </span>
<span style='margin-top:1%; margin-right:3%;float:right;color: #3bb598'>Hits : 39 Views : 60</span>
<br>
<table><tr>
<th><img src='propic/pro_pic.jpg' id='img' align='top'><br><span style='color:#3bb598'>Title</span> <br><span style='color:#3bb598'><a href='' id='tagid'>Travel</a></span></th>
<th></th><th></th><th></th>
<th style='text-align: justify;color: #212121;'>".$textid."
</th><th></th><th></th><th></th>
</tr></table>
</div>
";
?>
i want the new query should be posted with a fadeIn effect and should show some ajax loading before posting ......

It could be simpler with jQuery's post:
var jqXhr = function(e) {
var $id = $('#textid').val();
var $spinner = $('#spinner');
var $result = $('#new_query_post');
e.preventDefault();
$result.fadeOut(200);
$spinner.show();
$.post('postquery.php', { textid: $id }, function(response) {
$result.html(response).fadeIn(200);
$spinner.hide();
});
}
$('#shareImageButton').on('click', jqXhr);
And add a <div id="spinner">...</div> in your HTML (you can find some examples here for pure CSS spinners).

Related

Trying to read a JSON file with a script [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 days ago.
Improve this question
I'm trying to read a secure Json file on my server when I access the file directly through the URL I get this:
Access Denied
You don't have permission to access "xxxx.com" on this server.
Reference #18.2497f648.1675536275.16f2f2ad
What I'm trying to do is actually read the content in the file and when the file is updated with the specific word I'm looking for then I'll get a notification to my application
my code:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
var delay = null;
function loadXMLDoc(){
if (delay) {
clearTimeout(delay);
}
var sec = 2000;
const xhr = new XMLHttpRequest();
xhr.open('GET', 'test.json', true);
xhr.setRequestHeader('Referer', 'test.json');
xhr.SetRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onload = getJson;
xhr.send(null);
xhr.responseType = 'text';
xhr.onload = function(e) {
if (this.status == 200) {
const final = this.response;
if (final !== ""){
{
sec = 10000;
iff(final); // call to iff function - send to aplication.
}
}else{
document.getElementById("name").textContent = "אין התרעות כרגע";
}
delay = setTimeout(loadXMLDoc,sec);
}
}
xhr.send();
};
window.onload = function() {
loadXMLDoc();
}
</script>
<script>
function iff(final){
const object = JSON.parse(final);
for (let err of object.data) {
var zone = err;
document.getElementById("name").textContent = zone;
$.post("sendtofirebase.php", {zone: zone}, function(data) {
// returned from php
});
}
}
</script>
</head>
<body>
<text id="name"></text>
<meta http-equiv="refresh" content="3600">
</body>
</html>

AJAX check page return every 5 minutes [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I want to make a simple AJAX script but I don't know how to do that :
Every 5 minutes, the scripts check if the page "req.php?online_mode" returns the text "true" or "false". If it returns "true", it'll do anything, but if it returns "false", it will show a Javascript alert().
Any help please ? Sorry for bad english,
Cheers, MrZ
Take a look at $.ajax() and setTimeout().
make_call = function() {
setTimeout(function() {
$.ajax({url: "demo_test.txt",
success: function(result){
if (result == true) {
make_call();
} else {
alert("!!!");
}
}});
}, 300000);
}
If you want to use native Javasript:
var request = new XMLHttpRequest();
request.open('GET', 'demo_test.text', true);
request.onload = function() {
make_call();
};
request.send();
Puedes hacerlo de una manera fácil y rápida, así:
function ajaxCheck(url, minutes, text){
if(text == "false") return alert("Finalize!");
setTimeout(function(){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
xhr.readyState == 4 && xhr.status == 200 && ajaxCheck(url, minutes, xhr.responseText)
};
xhr.open("GET", url, true);
xhr.send()
}, 60*1000*minutes)
}
ajaxCheck("req.php?online_mode", 5)

Display PHP output in Ajax Popup

Hi All! So I'm a noob, and most of my code was done by a programmer for me. I can't get him to help me now.
I have a calculator that displays results (produced by calc.php) without relaoding the page. Demo is here: http://www.roofingcalculator.org/popup/popup.htm
Now I added Ajax popup (contact form) from here: http://dimsemenov.com/plugins/magnific-popup/ and it works.
What I want is to display the results of calc.php inside the Popop, but it does not work.
Details:
When user clicks "Calculate" button, the form sends info to CALC.JS using POST, which then sends info to CALC.PHP and diplays results back on the page with this tag:
<span id="CalcSum">Results:</span>
When I add the SPAN tag to popup, it does not display the result of PHP.
QUESTION How do I display results in AJAX Popup??
Please help - I really appreciate any help - Cheers!
Calc.js content:
var XmlHttp;
function GetXmlHttpObject() {
var XmlHttp = null;
try {
XmlHttp = new XMLHttpRequest();
} catch (e) {
try {
XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return XmlHttp;
}
function StateChanged() {
if (XmlHttp.readyState == 4 || XmlHttp.readyState == "complete") {
document.getElementById("CalcSum").innerHTML = XmlHttp.responseText;
}
}
function ShowSum(url, params) {
XmlHttp = GetXmlHttpObject();
if (XmlHttp == null)
return;
XmlHttp.onreadystatechange = StateChanged;
XmlHttp.open('POST', url, true);
XmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
XmlHttp.setRequestHeader("Content-length", params.length);
XmlHttp.setRequestHeader("Connection", "close");
XmlHttp.send(params);
}
function GetInfo() {var str =
"size1=" + escape(encodeURI(document.getElementById("size1").value)) +
"&size2=" + escape(encodeURI(document.getElementById("size2").value));
ShowSum('http://www.website.com/calc.php', str);
}
calc.php
<?php
$size1_val = empty($_POST['size1']) ? '0' : $_POST['size1'];
$size2_val = empty($_POST['size2']) ? '0' : $_POST['size2'];
$total_size = $size1_val * $size2_val;
print "Result: ". round($total_size). "";
?>
HTML Form:
<table>
<script type="text/javascript" src="calc.js"></script>
<form id="formcalc" action="javascript:GetInfo();" accept-charset="UNKNOWN"
enctype="application/x-www-form-urlencoded" method="post">
<tr>
<td height="24" ><strong>Sizes:</strong>
</td>
<td height="24" valign="top" width="50%">
<input id="size2"/> x <input id="size1" s/> ft.
</td>
</tr>
<tr>
<td COLSPAN="2">
<input name="calc" type="submit" value="Calculate" />
<span id="CalcSum">Results:</span>
</form>
</td>
</tr>
</table>
Add $('.popup-with-form').magnificPopup('open'); to your stateChanged function as below. Works for me on your example. Changed both results spans and opens the pop up.
function StateChanged() {
if (XmlHttp.readyState == 4 || XmlHttp.readyState == "complete") {
$('.popup-with-form').magnificPopup('open');
document.getElementById("CalcSum").innerHTML = XmlHttp.responseText;
document.getElementById("CalcSumPopup").innerHTML = XmlHttp.responseText;
}
}
Update: more documentation here http://dimsemenov.com/plugins/magnific-popup/documentation.html if you need it.
Is the html for the Ajax popup on the same page as the form? If so, add
<span id="CalcSumPopup">Results:</span>
to the popup where you want the result to go and add
document.getElementById("CalcSumPopup").innerHTML = XmlHttp.responseText;
after document.getElementById("CalcSum").innerHTML = XmlHttp.responseText; in Calc.js.
If it is not on the same page this will not work.
EDIT:
This works because id's are meant to be unique. getElementById will find the first occurrence of the specified id and then stop, so if you want multiple places to be changed you need to give them unique id's.

Data not getting passed via Ajax to PHP script

I'm trying to send the value of a variable number via ajax to a PHP script. But the PHP script is not printing the desired output on opening on a browser. Tried but couldn't find whats wrong here.
Any pointers ?
index.html
<button type="submit" class="btn btn-success" id = 'first' onclick='process();'>Submit</button>
<script>
var number = 0;
function process()
{
number++;
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "num=" + number;
xhr.open("POST", "index.php", true);
xhr.send(data);
}
</script>
index.php
<?php
session_start();
$number = $_POST['num'];
$_SESSION['numb'] = $number;
echo $_SESSION['numb'] ;
?>
Editing my long winded lame answer since you fixed the close curly bracket... but bloodyKnuckles is right you also need something in your 'process' function to take the response from your PHP page and output it... or whatever you want to do. You can basically use the method 'onreadystatechange' in the XMLHttpRequest object and then look for a 'readyState' property value of 4 which means everything is done. Here is a simple example of that just outputting the results to the console (which you can view using developer tools in your browser of choice).
<script>
var number = 0;
function process()
{
number++;
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "num=" + number;
xhr.onreadystatechange = function(){
if (xhr.readyState==4 && xhr.status==200){
console.log('xhr.readyState=',xhr.readyState);
console.log('xhr.status=',xhr.status);
console.log('response=',xhr.responseText);
}
else if (xhr.readyState == 1 ){
xhr.send(data)
}
};
xhr.open("POST", "ajax-test.php", true);
}
</script>
As you go further you may want to update your PHP page to only update the session when the POST value is there.
<?php
//ini_set('display_errors',1);
//ini_set('display_startup_errors',1);
//error_reporting(-1);
if(isset($_POST['num'])){
session_start();
$_SESSION['numb'] = $_POST['num'];
echo $_SESSION['numb'];
}
?>
You can uncomment those ini_set and error_reporting lines to try to figure out what is going on with your PHP script.
This is because you are not sending header information with request...
Append this code
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", data.length);
xhr.setRequestHeader("Connection", "close");
after
xhr.open("POST", "index.php", true);

Second Part to Dialog Closing [duplicate]

This question already has answers here:
I Created A Dialog, Now How Can I Close It?
(5 answers)
Closed 9 years ago.
This is a 2nd thread of a first I started here: I Created A Dialog, Now How Can I Close It?
I'm creating a new thread so I can include updated code.
First of all I'd like to give an enormous THANKS to all whom have helped me in the post linked above but as I stated, I'm starting this thread so I can add code samples.
I have a dialog on some of my pages that appears onscroll but I'm having some trouble.
This dialog can be seen here: (The semi transparent box that appears) http://classifieds.your-adrenaline-fix.com/detail.php?fatherID=37&TypeID=42&ListingID=42
On detail.php I have:
(in the head)
<script type="text/javascript">
function loaddiv(thediv, thefile) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject ('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById(thediv).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', thefile, true);
xmlhttp.send();
}
</script>
Below That:
<body onscroll="loaddiv('div2', 'do-you-have-a-dirt-bike-for-sale.html')">
Then:
if (!Has_Seen_DB_For_Sale_Dialog($user_ip)){
echo "<div id='div2'></div>";
ip_add($user_ip);
}
Above that (in an include file) I have:
function Has_Seen_DB_For_Sale_Dialog($ip){
global $user_ip;
$query ="SELECT `IP` FROM `DB_For_Sale_Dialog` WHERE `IP`='$user_ip'";
$query_run = mysql_query($query);
$query_num_rows = mysql_num_rows($query_run);
if($query_num_rows==0){
return false;
} else if($query_num_rows==1){
return true;
}
}
function ip_add($ip){
$query = "INSERT INTO `DB_For_Sale_Dialog` VALUES('', '$ip') ";
#$query_run = mysql_query($query);
}
And the file that is displayed looks like:
<div id='div2'>
<div class="DoYouHaveADirtBikeForSaleBox" id="DoYouHaveADirtBikeForSaleBox">
<h2>Got A Dirt Bike You Want to Sell?</h2>
<p class="DirtBikeForSaleBannerButton">
Yea, Show Me How
</p>
<p class="DirtBikeForSaleBannerButtonNoThanks">
<a onclick="javascript:var div = document.getElementById('div2');div.parentNode.removeChild(div);">Nope, Get This Out of The Way</a></p>
</div>
</div>
I'm VERY Grateful of the help provided me in my last thread and mean NO disrespect in starting a new thread but What I'm now having trouble with is:
When I hover over the right button to close the box, the pointer doesn't turn into a hand as it does with other links.
When the dialog box is closed and the page is scrolled, the box reappears. (the function to display the box is called onscroll but I only want the box to appear ONCE.
If anyone wouldn't mind commenting on this I'd be most appreciative and I certainly look forward to your responses.
Thanks So Much,
Stuart K
Use this aproach:
<script type="text/javascript">
function loaddiv(thediv, thefile) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject ('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById(thediv).innerHTML = xmlhttp.responseText;
window.onscroll = null;
}
}
xmlhttp.open('GET', thefile, true);
xmlhttp.send();
}
</script>
--------I made this little test--------------
function loaddiv() {
alert('hiiii');
window.onscroll = null;
}
The body call:
<body onscroll="loaddiv();">
And works just once xD
Saludos.

Categories

Resources