Jquery $.ajax to website, return value - 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!

Related

Pass external URL into ajax javascript

I am trying to fetch the contents of an external XML URL, into the javascript's ajax script, but it simply won't accept it, due to CROSS domain issue. I have searched through google regarding this issue, but nothing good so far, everything I've read so far stated that I need to incorporate PHP as well, but with that, the page would take reload.
I simply want that when a user enters a number that number gets passed as an argument in the URL, then displays the XML content in the screen without reloading.
SO any help will be highly appreciated.
Here's my code so far.
<script>
function myFunction() {
$("#dvContent").append("<ul></ul>");
$.ajax({
type: "GET",
url: "http://lx2.loc.gov:210/lcdb?operation=searchRetrieve&recordSchema=marcxml&version=1.1&maximumRecords=1&query=bath.isbn%3D9781452110103",
dataType: "xml",
success: function(xml){
$(xml).find('record').each(function(){
var sTitle = $(this).find('datafield[tag="245"]').find('subfield[code="a"]').text();
var sAuthor = $(this).find('datafield[tag="100"]').find('subfield[code="a"]').text();
var sIsbn = $(this).find('datafield[tag="020"]').find('subfield[code="a"]').text();
$(".mypanel").html(text);
});
$("<li></li>").html(sTitle).appendTo("#dvContent ul");
$("<li></li>").html(sAuthor).appendTo("#dvContent ul");
$("<li></li>").html(sIsbn).appendTo("#dvContent ul");
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
}
</script>

Sending data using Ajax to local PHP script, receive response but if-condition in php file is never met

I have a draggable div-container and whenever I drop it, its location is to be send to a local php script.
$(function() {
$( "#fenster" ).draggable({
stack: "#fenster", stop: function(event, ui){
var pos_x = ui.offset.left;
var pos_y = ui.offset.top;
$.ajax({
type: "POST",
contentType: "application/json",
data: {'x': pos_x},
url: "index.php",
}).done(function(msg){
alert("data Saved: " + msg);
});
}
});
});
In the php file (index.php) I check whether $_POST['x'] is set. Unfortunately, no matter what I do, the condition is never met.
if((isset($_POST['x']))){
$_SESSION['xLoc'] = $_POST['x'];
echo "Test";
}
Upon dropping the window, I get a response (alert of the msg shows output) and according to FireBug, the request DOES contain x.
The PHP superglobal $_POST, is only available when you use these content types
application/x-www-form-urlencoded (standard content type for simple form-posts) or
multipart/form-data-encoded (mostly used for file uploads)
You are using application/json which means you need to get the stream with...
$rawData = file_get_contents("php://input");
$d = json_decode($rawData);
if((isset($d['x']))){
$_SESSION['xLoc'] = $d['x'];
echo "Test";
}
Or if you dont actually need to be submitting JSON, just remove the contentType from your jquery, and you should be able to retrieve the $_POST on the php side, using the code you already had.
$.ajax({
type: "POST",
data: {'x': pos_x},
url: "index.php",
}).done(function(msg){
alert("data Saved: " + msg);
});
Or change your php to the code above, to retrieve the raw stream, if you need to be sending json data to the server
I had two redirects that killed the POST request. After making adjustments to the if-conditions, this no longer happens and the data sent by the Ajax request is now also being successfully processed by PHP.
Thank you all that took the time to help me, it's greatly appreciated.

jquery not post data in IE

i create one simple form in which i have one combobox when i am selecting any thing i put one function onchange event so its call.
then i send this data in one helper file through jquery
<script type="text/javascript">
$.noConflict();
function Searchwine(obj,str) {
{queryString: ""+str+""}, function(data){
jQuery.post("http://www.site.com/search/helper/autosuggest.php", {queryString: ""+str+""}, function(data){
if(data.length >0) {
jQuery('#windatano').html(data);
}
</script>
i am using this code for post data in autosuggest from through javascript and print replay of jquery in windatano id
--> its working fine in crome and ff and other all browser but in IE its not working
Can any help?
Thanks,
You're using jQuery improperly.
The proper syntax is (for POST)
$.post([URL], {
var: value,
var2: value
}, function(data) {
//callback goes here
}
);
If you want to pass in the querystring as though it's a GET, just append it to the URL after a ?.
E.G.:
"http://www.site.com/search/helper/autosuggest.php?" + str
IE does not support cross domain ajax calls regardless if its getJSON or not. learned that the hard way... i ended up adding a local php file that used curl to get the results and return them to the script, its the only way to make ie work with cross domain requests.
You can't do cross domain ajax requests, if the request url is in another domain, this fail, if the domain is the same, use a relative path:
jQuery.post("/search/helper/autosuggest.php"....
If you need Cross domain ajax request, you have to use jsonp (http://api.jquery.com/jQuery.getJSON/#jsonp)
And if you are using post method, the queryString define a get vars, you need use data option
jQuery.ajax({
url: '/search/helper/autosuggest.php',
type: 'POST',
data: data,
sucess: function (data) {
if (data) jQuery('#windatano').html(data);
}
});
When data can be the object format:
var data = {
a_var = 'value',
other_var: 'other value'
};
Sorry my English

Difference between a form post and jquery post

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

jQuery Mobile -> Load content from external server

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.

Categories