ajax call is not responding - php

I am using ajax for retrieving data from my remote server when i am posting the ajax url directly in the address bar of browser, i am getting the data but when i am doing ajax call to that url in javascript file , it is showing error.I am pasting my code here.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$.ajax({
url:"http://www.appitechture.com/api/index.php?action=getContactDetails&id=96",
type:'get',
datatype:'json',
success:function OnSuccess(data , status){
alert(data);
} ,
error: function OnError(request , status , error){
alert('error');
}
});
</script>
</head>
<body>
<div id="images"></div>
</body>
</html>
so please if any one knows its solution please tell me.
Thank's
puneet

Are you trying to do a crossdomain AJAX request? Bad idea, read this article http://en.wikipedia.org/wiki/Same_origin_policy

If it is not the same domain, you need to use JSONP (JSON with padding). This is due to Same Orgin Policy, as Bogdan Burim states.
jQuery.getJSON can help you with this in a easy way. It will include a script tag like this on your page.
<script type="text/javascript"
src="http://example.com/jsonp?callback=parseResponse">
</script>
You will also need to change the response of the remote server to include the callback var like this:
parseResponse({"bar": "foo", "foo2": "bar2"});
You can also have a look at easyXDM:
easyXDM is a Javascript library that enables you as a developer to
easily work around the limitation set in place by the Same Origin
Policy, in turn making it easy to communicate and expose javascript
API’s across domain boundaries.
Wikipedia have a nice article about JSONP.

Related

Lengthy jQuery AJAX request freezes browser

I have an AJAX request, processing of AJAX request is complex and lengthy. The problem is that this lengthy request freezes browser. I mean when AJAX request is in process then no matter if I click any link/button from page or type some Url of same website in browser address bar it does nothing and keep waiting fro AJAX request response, once AJAX response arrives back other processes start working. I am using async: true with AJAX request.
Here is the code I am using. Its a simple page having nothing else but this jQuery AJAX request. My server side PHP.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test Page</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: 'http://www.mywebsite.com/doprocessing',
async: true,
success: function () {
alert('done');
}
});
});
</script>
</body>
Why this is happening? How can I solve this?
PS: Before you mark this duplicate, I have checked almost all similar questions on StackOverflow. No solution is working in my case (though solution in most cases was using async: true which I am already doing.
Thanks in advance,
The reason, why any of the links of the same website are not working during ajax, is that your script is locking the session in the server.
You could either not to use session for this script, or finish session after you are sure that this is correct user etc, but before starting sending emails (or doing anything else lengthy).
Use session_write_close() before starting sending emails in PHP for this.
Alternatively you can implement your own asynchronous session handler.

getJson not working on webhosting

I have a slight problem. I am connecting to a web service which provides JSON results and trying to parse the results. The code is working fine on my localhost (wamp server) but code doesn't run on any of the web hosting accounts I tried.
Here is the url providing JSON
http://mohamedbadr.com/webservice/list.php
And here is my file which is trying to fetch results:
http://contestlancer.com/web/getList.php
Here is the code of the Getlist file:
<!DOCTYPE HTML>
<html>
<head>
<title>Hotel Promotion List</title>
<script type="text/javascript" src="jquery.js"></script>
<link rel="stylesheet" type="text/css" href="style.css"/>
<script type="text/javascript">
function getList()
{
var i=0;
var ntable="<table><thead><tr><th>Image</th><th>Name</th><th>Rating</th><th>Highlights</th></tr></thead><tbody>";
$.getJSON("http://mohamedbadr.com/webservice/list.php", function(data){
$.each(data.promos, function(key, value) {
ntable+="<tr><td><a href='promotion.php?id="+value.promo.id+"'><img src='"+value.promo.image+"' height='100' width='150'/></a></td><td><a href='promotion.php?id="+value.promo.id+"'>"+value.promo.name+"</a></td><td> "+value.promo.stars+"</td><td> "+value.promo.highlights+"</td></tr>";
});
ntable+="</tbody></table>";
$("#content").html(ntable);
});
}
</script>
</head>
<body onLoad="getList()">
<div id="wrapper">
<div id="content"></div>
</div>
</body>
</html>
Most probably the url is not being opened what is the solution to this? Any help will be highly appreciated
It's not working because you are making a cross domain request. Domain A to Domain B.
Try adding this to http://mohamedbadr.com/webservice/list.php before any output is printed.
header('Access-Control-Allow-Origin: http://contestlancer.com');
As mentioned by Nadh, this is due to a cross-domain request. More info # HTTP Access Control. Understanding Same Origin Request.
Since you are using jQuery getJson(), you may alternatively try this approach
var url = "http://mohamedbadr.com/webservice/list.php";
$.getJSON(url + "?callback=?", null, function(data) {
... Success Logic here...
});
The ?callback=? at the end of the url, will convert your request to a JSONP. And if you remove it, this will be a plain Ajax call.
Understanding JSONP
-- Arvind.

Making HTTP requests on button click

Need to make a HTTP request on click of a button on a webpage! , please guide me with an Example that whether using AJAX + PHP is the way out or Javascript will be able to do the same alone?
The easiest way is to bind onclick to the button
`onclick='location.href="mynewpage.html"`
AJAX is actually part of JavaScript.
For simplicity, you might want to use a library such as jQuery.
Put this in the <head> section to load jQuery...
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
And to execute an AJAX request, include this too...
<script type="text/javascript">
$('#id-of-your-button').onClick(function() {
$.ajax({
url: "backend.php"
}).success(function(data) {
// do something here
});
}
</script>
For more details on this function, refer to jQuery.ajax() here.

Facebook auto-refresh

What technology does Facebook use to auto-update information on a page without reloading it?
For example, while someone is viewing his profile if he receives a new message the inbox number auto-updates in the top bar. Same with wall posts, etc. Code-wise how is this managed?
They are using several new technologies like AJAX and History API.
I strongly recommend you to use jQuery or another framework for AJAX and History.js for the History API.
the core javascript function set_timeout() is the man! Every x seconds the server is queried to fetch new results, updates etc. FB uses AJAX to get the info from the server and JS to update the page.
Facebook open a connection using AJAX which then hangs and hangs. The server doesn't send anything or respond to your browser unless, of course, a notification. Eventually, your browser may give up and disconnect from Facebook in which case the javascript will create a new connection and the process continues.
This is superior to polling the server every few seconds as it reduces load and makes load more predictable too.
Here's more info: http://en.wikipedia.org/wiki/Comet_%28programming%29
use setInterval on a function which makes an Ajax call to a file in which you have a MySQL query which checks something.
setInterval( "refresh();", 60000 );
refresh = function(){
var URL = "file.php";
$.ajax({ type: "GET",
url: URL,
succes: function(data){
if(data){
//change stuff
}
}
});
}
that should be a good starting point
coba gunakan script ini..
autocallajax.php
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script>
$(document).ready(function(){
var callAjax = function(){
$.ajax({
method:'get',
url:'load.php',
success:function(data){
$("#sample").html(data);
}
});
}
setInterval(callAjax,5000);
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<?php
<div id='sample'>100 </div>";
?>
</body>
</html
load.php
<?php
mysql_connect("localhost","root","siantarman");
mysql_select_db("konsultasi") or die("<br><br><hr width=350 size=1 align=left>
<font color=red><b>Database belum tersambung!</font></b>
<br>Hubungi administrator anda!<br>" . mysql_error());
$sql_info=mysql_query("select jumlah from data_konsultasi where id = '9'");
$r_data=mysql_fetch_array($sql_info);
echo"$r_data[jumlah]";
?>
selamat mencoba..

dynamic loading of html via php javascript not executing

i have a simple setup, with php pulling html content from a database. if i go to my template page, it loads the data and returns it to the browser via a simple php echo ... not rocket science.
now, i've written an html file using jquery and an ajax call. i load the html file in my browser and the javascript / ajax query works.
when i load the html into the database and print it out via the php / echo, the content is the exact same when i view the source, but the ajax query doesn't execute.
<html>
<head>
<title>random query - api - get</title>
<script src="http://code.jquery.com/jquery-1.5.min.js"></script>
</head>
<body>
<pre>
executing the GET method
<script language="javascript" type="text/javascript">
$.ajax({
type: "GET",
url: "http://some-rand.om.api.com",
data: "011b38b8-011f-4b03-bb21-4c5bb26600b3",
success: function(msg){
alert( msg );
}
});
</script>
</pre>
</body>
</html>
Any comments / suggestions would be great. What I find bizarre, is i have no problem copying the source of http://jquery.com/ and pasting it into the db and doing the php / echo. this works fine. maybe an onLoad() would help...hm.
The issue is outlined in the following url:
XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin
When I load the javascript console in chrome I get this:
XMLHttpRequest cannot load http://some-rand.om.api.com/user?011b38b8-011f-4b03-bb21-4c5bb26600b3. Origin http://localhost is not allowed by Access-Control-Allow-Origin.
To resolve the problem, on the api vhost, in the code that serves the content accessed by the ajax query, i added this (it is also php):
header('Access-Control-Allow-Origin: http://some-rand.om.client.com');
Now when I access it, it's all good and loads as expected. So, infact, it wasn't related to it being stored in the database, php or javascript. It was related to cross site scripting.
Or, to be super lazy (probably not a great idea...):
header('Access-Control-Allow-Origin: ' . $_SERVER["HTTP_ORIGIN"]);
If in your description of the problem you are listing the whole of the code, then the JavaScript should be wrapped in a $(document).ready(function(){ ... });.
i.e.
$(document).ready(function(){
$.ajax({
type: "GET",
url: "http://some-rand.om.api.com",
data: "011b38b8-011f-4b03-bb21-4c5bb26600b3",
success: function(msg){alert( msg );}
});
});

Categories