I am working on a seemingly basic mobile app (first). But I want to enable the application to request information from our 'head' server. To make sure it has the latest information.
I'm currently running a jQuery script like this.
$.ajax({
url: 'http://www.domain.com/list.php',
dataType: 'json',
crossDomain: true,
success: function(data) {
// Remove all content first
$(contentId +' li').remove();
// Load Data
$.each(data.items, function(index, list){
$(contentId).append('<li><a href="details.html?id=' + list.homeId + '" >' + list.name + '</a></li>\n');
});
// Reload View
$(contentId).listview('refresh');
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('Error: '+ jqXHR + textStatus + errorThrown);
}
});
And actually on that LIST.PHP file, it does return a JSON string. But what I did for security was by adding this as a header
header("Access-Control-Allow-Origin: *");
Or I could change * to a domain/url to add better security. But if I don't add that header() code in their, my javascript breaks and won't run properly.
I guess what i'm truly wondering is, am I doing this properly? or is there a better way to do this? I have tried JSONP, but I can't seem to get that to work for cross domain.
Is my solution sound? or total crap? Any thoughts or direction would be greatly appreciated!
I think you should look into JSONP. It's not that hard. On the client side, jQuery already handles it out of the box, just append a ?callback=? to the URL. On the server, instead of just responding with JSON, e.g.:
{
"foo": "bar"
}
Look for the query parameter callback, and if it exists, wrap your JSON output in a function call with the name being the value of the callback parameter, so, for callback=foo:
foo({
"foo": "bar"
})
When responding with JSONP, send Content-Type: text/javascript. This should work without setting Access-Control-Allow-Origin or anything like that.
Related
I have the below function that I used in two different pages and worked perfectly in both cases. Suddenly my pages stopped updating and I got the error $.ajax not a function.
function update_report(data) {
var request = $.ajax({
url: "report?poids="+data,
type: "GET",
dataType: "html"
});
request.done(function(msg) {
$("#yw2").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
req ="a";
}
I then changed the $ to jQuery. Then it started sending AJAX requests but it didnt get the relative URL. Like I was generating the request from a page like /index.php/link1 and my code was sending request to /index.php/report rather then /index.php/link1/report
So, then I changed my url: to "link1/report=?"+data then it started sending request to the right page but couldnt update the response as it didnt find the div #id. Got error
TypeError: $(...) is null
What can cause all this issue and how to fix this? And why $.ajax suddenly stopped working, though I didnt make any changes?
JQuery can be not available by $.ajax(). Check if jQuery.ajax() is available or you included jquery twice.
You should not require jquery manually. The best way to include jquery is using Yii::app()->clientScript->registerCoreScript('jquery'). Path for library is set in config/main.php.
I'm trying to post to my own domain through a Greasemonkey script on another webpage. The script pull some info from the webpage, uses ajax to post to my domain and my domain sends back a value.
I always get readyState = 0?
$.ajax({
url: "http://botsunauthorized.net/bots4captcha.php",
data: {
url: str
},
success: function(data,success) {
alert(data+'-'+success);
},
error: function(data,success) {
$.each(data, function(key,valueObj){
alert(key + "/" + valueObj );
});
}
});
When I use the $.each function, it says readyState = 0 and I get no value from my domain. I've done some research and it may be because the scripts are not on the same server? Is there an easy way to get around this or am I not going to be able to do this?
Thanks!
My AJAX request to pings the server, and the URL but returns an error because it doesnt like the '<' as the open tag for the php script.
AJAX script.
$.ajax({
url: "data.php",
type: "POST",
data: JSON.stringify({"data":transaction}),
dataType: "json",
success: function(data, textStatus, jqXHR){
alert("success");
currentProcesses -= 1;
$("<span>").html("Ajax Call Complete. Releasing lock for process").appendTo($(body));
},
error: function(jqXHR, textStatus, errorThrown){
alert("error with ajax call "+textStatus+" "+errorThrown);
}
});
php script
<?php
$win = $_POST['data'];
?>
Am I using the wrong flag settings for the AJAX call?
The body of your POST request is encoded as application/json instead of application/x-www-form-urlencoded.
You aren't doing anything to make the request say that the data is encoded in JSON and you aren't doing anything in PHP to try to parse JSON.
As a result, PHP fails to populate $_POST, because the data is in the wrong format.
The solution is: Don't send JSON. Just give the data property an object as its value, and jQuery will serialise it to application/x-www-form-urlencoded data for you.
data: { "data": transaction },
(Assuming that transaction is not a complex data type (like an array or object).
Additionally, the body variable is undefined. You should either use a string (to make it a selector: "body") or pass the body element directly: document.body.
Is it choking on what it's receiveing? Try this...put an id attribute on your span tag, and reference that.
In the page:
<span id="someName">...</span>
In your ajax call:
$("#someName").html(...
Try making the span more unique using class or id like
<span id="output"></span>
and try this.
$("#output").html("Ajax Call Complete. Releasing lock for process").appendTo($(body));
}
I need to know the exact difference between:
<form method="POST" action="https://mywebsite/signon.php">
<input name="harv_acc" value="940322903" type="hidden" />
<input name="harv_eml" value="a#b.com" type="hidden" />
<input type="submit" value="SignOn" />
and
var url = "https://mywebsite/signon.php";
$.ajax({
url: url,
type: 'POST',
//dataType: 'html', -- this was something I tried later
//data: "harv_acc=" + accountnumber + "&harv_eml=" + email , this is also what I tried last but below is what I tried first
data: { harv_acc: account, harv_eml: email },
success: function (data) {
closePopup("div_PleaseWait");
alert(data);
//window.location = encodeURI('<%= Url.Action("DownloadDocument", "Documents") %>?DocumentID=' + documentID + '&DownloadType=' + downloadType + '&DownloadPath=' + data);
}
});
When I post the latter I get a 200 but no response. If I submit the first one I get the correct response.
From the comments:
I'm posting to another site
Aha! There's your issue. Browsers block AJAX to external websites for security reasons. Sorry, but you're not going to issue that request via an XHR request.
If the other website wants you to communicate with them, they could expose this part of the site via JSON-P, which works something like this:
My site adds <script src="http://othersite.com/signon.js?username=foo&password=bar&callback=myCallback"> to the source code (yeah, it's messy to use GET for this, but JSON-P can't work any other way), and creates a function named myCallback to handle the response data.
The other site signs in, then returns something like myCallback({success: false, errorMessage: "Incorrect password, try again!"})
That script is run on my site, calls myCallback, and everything is happy.
JSON-P is a powerful protocol, but only works if the remote site agrees to it. Still, if they do, jQuery has a nice shortcut for it: just set dataType: "jsonp" and it will handle the whole callback thing for you.
But if you're not closely involved with this website, that's unlikely to happen, and you'll probably just be stuck with having to give up on this kind of cross-site interaction. Sorry, but this kind of cross-domain policy is critical to online security. (I don't want other sites issuing requests to bankofamerica.com on my behalf, kthx.)
The first parameter passed to your complete function will be a jqXHR object, which is a wrapper around the browser's XMLHttpRequest object. A more convenient way to handle the response is to use the done method:
var url = "https://mywebsite/signon.php";
$.ajax({
url: url,
type: 'POST',
dataType: 'html',
data: "harv_acc=" + accountnumber + "&harv_eml=" + email
}).done(function(data) {
closePopup("div_PleaseWait");
alert(data);
});
Cross domain ajax requests are not supported by browser. But there is another way to get around this.
You can use JSONP for cross-domain requests. It is easy to use and allows you to request anything (as long as it is in JSON format) from any server/script that supports the callback. The good thing about JSONP is that it works in older browsers too.
The only serious limitation seems to be that it always uses the HTTP GET method
Can you please check with this too.
Try sending ther data as a key:value object. This is an example from the jQuery docs
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
Update: as user Matchu pointed out, this is not the problem, as the data will be converted into a query string anyway, as stated in the jQuery docs:
"The data option can contain either a query string of the form key1=value1&key2=value2, or a map of the form {key1: 'value1', key2: 'value2'}. If the latter form is used, the data is converted into a query string using jQuery.param() before it is sent. "
So yeah, some rash answering on my part there. At least I learned something! ;)
when using POST method you should ,in your case, Post your data as JSON
var url = "https://mywebsite/signon.php";
$.ajax({
url: url,
type: 'POST',
dataType: 'html',
data: {
harv_acc : accountnumber,
harv_eml : email
},
success: function (data) {
closePopup("div_PleaseWait");
alert(data);
//window.location = encodeURI('<%= Url.Action("DownloadDocument", "Documents") %>?DocumentID=' + documentID + '&DownloadType=' + downloadType + '&DownloadPath=' + data);
}
});
NOTE : i used dataType : JSON
I am using a simple ajax loader to get content on wordpress.
$("#page_preview").load("ajaxloader/", function(response, status, xhr) {
if (status == "error") {
alert("Sorry but there was an error");
}
else
{
$('#page_preview').fadeIn(300);
}
});
return;
When I load a specific post that has a google map embedded, obviously something goes wrong BUT instead of going inside the if statement, the firebug shows that it goes beyond this code. Neither if or else hit.
Using the eclipse debugger I found that the page load successfully, but when it returns the data to the .load() method, the last breaks.
Any ideas on what might going on?
How
<script>
// as of jQuery 1.5.x ++
var pagePreview = $("#page_preview");
$.get("ajaxloader/").success(
function(response, status, jqXhr) {
alert("Success!");
pagePreview.empty();
pagePreview.append(response);
// i feel you need to parse the response for the google map div, and perform another $.get() of the google url?
}).error(function(response, status, jqXhr) {
alert("These are not the droids you are looking for. move along.");
}).complete(function(response, status, jqXhr) {
alert("Complete!");
});
</script>
#Why
jQuery.load() will get you on the documentation. .load is equivalent to this
It is roughly equivalent to $.get(url, data, success) except that it
is a method rather than global function and it has an implicit
callback function. When a successful response is detected (i.e. when
textStatus is "success" or "notmodified"), .load() sets the HTML
contents of the matched element to the returned data.
You need to register in $.ajax( complete:function(responseText, textStatus, XMLHttpRequest)){}); and check the textStatus value. if ok, then load the data into the destination $('selector') yourself. Or fix the .load() by watching your network xmlHttpRequests in chrome (ctrl + shift +j) or some network tab in firebug and debug the issue with your 'url' value in $('selector').load( 'url', function(response, status, xhr){})
A simple way to debug this is to look at the XHR requests with the firebug console tab. There might be a problem with the request URL and you might not get any data back, or maybe you get an error or something. With firebug you could easily see what the server returns.
Since .load only load on success, you could add a
console.debug("In .load function");
at the begging of the function. Again, checking with firebug you could find out if the .load callback is actually fired.
use $.ajax function
eg
$.ajax({
url: "test.html",
context: document.body,
success: function(){
//when Successfully executed
},
error: function(){
//When Error Fires
}
});