So, essentially I have this Javascript which interprets the JSON from my php code. It works great on the local server, however, when I try to move the script to a different server it will not work. I have added the
<?php header("Access-Control-Allow-Origin: *"); ?>
also i've declared my database connection as global within my PHP function.
I'm confused as to why these solutions aren't working.. Also, I understand some of the script is iffy, but I'm only interested in figuring out why its not working from different servers.
<script type="text/javascript">
$("document").ready(function(){
$(".sendText").submit(function(){
$("#sendButton").prop("disabled",true);
$(".errors").html("");
$(".success").html("");
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "jsonp", //new edit
url: "http://myurl.com/testing/jsonpost.php?callback=test", //new edit
data: data,
success: function(data) {
if(data["success"]=="yes") {
$(".success").html("Message Sent!");
$(".formContainer").html("" + data["json"] + "");
}
else {
if(document.getElementById("sendButton").disabled = true){ document.getElementById("sendButton").disabled = false; }
$(".errors").html("" + data["errors"] + "");
}
}
});
return false;
});
});
</script>
Some Info when I look at the web console from firebug:
Access-Control-Allow-Orig... *
Connection Keep-Alive
Content-Length 0
Content-Type application/json
Date Wed, 24 Sep 2014 04:22:57 GMT
Keep-Alive timeout=5, max=100
Server Apache/2.2.27 (Unix) mod_ssl/2.2.27 OpenSSL/1.0.1e-fips DAV/2 mod_bwlimited/1.4
X-Powered-By PHP/5.4.29
Looks like it is communicating with server but not able to interpret data? thoughts?
Also, this error comes up in the console from the remote server but not when I run on local server:
SyntaxError {stack: (...), message: "Unexpected end of input"}message: "Unexpected end of input"stack: (...)
Object {readyState: 4, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…
parsererror
The PHP code is pretty long (and I prefer not to release all of it) - however here is the shortened version:
<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
require "../database/db.php";
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "test": test_function(); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test_function(){
$c="1";
global $con;
$return = $_POST; //to reference post
$content=$return["content"];
//see if content is 140 characters or less
if(strlen($content)>140){ $c="0"; $lerror="<li>Your message must be 140 characters or less in length!</li>"; }
if($c=="0"){ //doesnt pass validation
$return["success"]="no";
$return["errors"]="$lerror";
}
if($c!="0"){ //passes validation
$return["success"]="yes";
}
if(isset($_GET['callback'])){ //jsonp edit
$return["json"] = json_encode($return);
echo $_GET['callback']."(".json_encode($return).")"; //jsonp edit
}
}
Also after converting to JSONP on remote server - get error -
"jQuery111006159528985153884_1411663761720 was not called"
When dealing with jQuery AJAX using a data type of JSON, any notice, warning or error produced by the server side script will cause issues. The reason being is the outputted PHP errors break the JSON encoding that jQuery is expecting.
I suspect the two environments are not identical, perhaps a different PHP version, missing PHP extension or different settings in the php.ini file.
The best thing to do is to use the provided jQuery AJAX error callback to console log any errors allowing you to essentially troubleshoot any issues being thrown by the server side script.
!!! EDIT 3 !!!
Client Code
$.ajax({
type: "POST",
dataType: "json",
url: "http://myurl.com/jsonpost.php",
data: data,
success: function(response) {
console.log(response);
},
error: function(xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
}
});
Server Side Code
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
echo json_encode(array('success' => 'yes'));
Using this bare bones version of your code I can successfully make a cross domain request and console log the response. If you implement this code and it still does not work there is something else at play at the server and/or network level.
You can make AJAX calls to a backend API, it needs to return JSONP format and not just JSON, otherwise you can get error. This is due to same origin policy:
https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy.
This discussion may be helpful to understand JSONP:
Can anyone explain what JSONP is, in layman terms?
However, one alternative is disable the security of Google Chrome browser, then it will work. But this is not a solution. It is better to use JSonP format.
Related
Hey I just installed script on same host, twice, just different accounts.
The scripts worked fine, but for random reason, one of them started to drop all AJAX requests, and print the following messsage in Mozilla:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.yoursite.com/vote/ajax/xmlhttp/claim. This can be fixed by moving the resource to the same domain or enabling CORS.
When I access the link directly, works fine, but with AJAX it just fails.. on the other account (host account) it works fine so far.
On my VPS and pc it works fine.
In PHP error log, it prints undefined variables, which is not really possible, how can AJAX affect this, especially in this random situation, where it works and sometimes now on this host.
My JS:
var reward = $("#rewards ul li");
var selected = [];
var limit = <?php echo $limit; ?>;
var errors = $(".error");
var timeout;
console.log(limit);
$("#claim").click(function() {
$("#claim").text('Checking...');
if ($("#username").val() == "") {
$("#claim").text('Claim my reward(s) now');
showError("Fill in your in-game username.");
return;
}
if (selected.length == limit) {
$.ajax({
type: "POST",
url: "<?php echo $post_url; ?>",
data: {username: $("#username").val(), rewards: JSON.stringify(selected)},
success: function(data) {
$("#claim").text('Claim my reward(s) now');
if (data.substr(0, 6) == 'error:') {
showError(data.substr(6));
}
else {
$("#claim").text('Success!');
$(".section").html(data);
}
}
});
}
else {
showError("You must select " + limit + " rewards(s) to continue.");
}
});
Let me know if you need the functions I used too.
What is causing this problem?
I tried adding the following response:
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
But it's bad because it will still have undefined variables in it, and still process the response which will cause JavaScript syntax errors.
Thanks in advice.
if i understood you right you are trying to pass data between to different servers;
the answer to this is JSONP, it works like JSON but should pass that CORS problem.
to do so you need to change a little bit your php code and ajax code.
in php you need to wrap the JSON data in a callback and in AJAX you need to define - dataType: "jsonp", read more about jsonp here: What is JSONP all about?.
it worked for me!
im having a problem trying to get an ajax call to trigger a php function and then return successfully. As far as i can see my syntax is correct.
But all i get back is failed! Any ideas?
EDIT
I have changed my AJAX request to send without using data, just to rule out that being a problem and i have implemented some of the things people suggested below but to no avail, heres what my 2 files look like now:
ship.js:
function set_ship()
{
//var datastring = {'ship':'true'};
$.ajax({
type:'POST',
url:'soap/classes/class.ship.php',
success: function(success){
alert('success');
},
error: function(fail){
console.log(fail);
}
});
}
And my PHP class.ship.php:
<?php
var_dump("hello");
header('Content-type: application/json');
echo json_encode(array("result"=>"true"));
From the var_dump on my PHP script i can see that the class.ship.php isnt even being called for some reason.
Thanks
Please try this
json_encode(array("result"=>"true"));
because
json_encode(true) // will return just "true" which is not a valid json
Also try serializing the dataString , by doing
data: datastring.serialize();
lowercase JSON_ENCODE
success: function(success), error: function(fail)
check what is returned in network tab of firebug.
You need to set the content header to json header('Content-type: application/json'); and make sure you request return only json coz ajax is waiting only for "JSON" and it will throw parse error
if(isset($_POST['ship']) && $_POST['ship'] == "true"){
$result = "result";
header('Content-type: application/json');
echo json_encode(true);
}
I would suggest that you check what it being actually returned by the server.
The error callback receives one argument representing the xhr object, so you can inspect that directly by placing a breakpoint or using console logging, like this
error: function(xhr) {
console.log(xhr);
}
Likewise, the success callback receives three parameters: the status, the returned data and the XMLHTTPRequest Object, so you can check those in the very same way:
success: function(status, data, xhr) {
console.log(status, data, xhr);
}
You should look for the response status code and the response text in the xhr object to understand what is going wrong. If you're seeing a 200 OK response status, the data returned from the server is probably not being interpreted correctly as JSON data, so you should try setting the response header server side to application/json.
An error might occur also if something else is appended or prepended to your response. This happens especially when warnings occur in the code before returning and you have error reporting set to ON.
$.ajax({
url: 'http://intern-dev01:50231/api/language',
type: 'GET',
dataType: 'json',
success: function() {
console.log('It Works!');
},
error: function (request,status, error) {
console.log(error);
alert(status);
}
});
Why do this ajax call not work ?? if i call in browser it works fine :/.
This is what fiddler returns:
HTTP/1.1 200 OK
Content-Length: 122
Content-Type: application/json; charset=utf-8
Server: Microsoft-HTTPAPI/2.0
Date: Fri, 26 Apr 2013 06:56:40 GMT
[{"LanguageId":1,"LanguageName":"Dansk"},{"LanguageId":2,"LanguageName":"Tysk"},{"LanguageId":3,"LanguageName":"Engelsk"}]
You have to check ajax response if it is valid or not. When you specify in ajax:
dataType: 'json',
jQuery will fire the error event if the response cannot be parsed as JSON, even if server returns 200 OK. Check the data returned from the server and make sure it is valid JSON (try JSONLint service).
If the returned data is not JSON or it has syntax errors then fix them in your server side code. You can just return {} from the server side script.
Also try this.
$.ajax({
url: 'http://intern-dev01:50231/api/language',
type: 'GET',
cache: false,
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
console.log(error);
alert(status);
}
else {
console.log('It Works!');.
}
}
});
There is a parsing error since the status shows 200 OK. The problem lies in the datatype:json. To test this, remove the line and it should work. In order to fix this, you can change it to the datatype:text. See this link too for similar question
Check the url parameter and make sure its the same as the loaded page. You might be doing a cross-domain ajax call. If you were wanting to make a cross-domain ajax call, notice that the only dataTypes allowed to make cross-domain requests are "script" and "jsonp".
Ran into this issue in a dev environment where the URL was an IP address and the page loaded a domain-name pointing to that ip.
I know I'm a little late, but I just ran into the same problem and this is one of the top search results on Google. I managed to fix it by moving datatype above url like this:
$.ajax({
type: 'GET',
dataType: 'json',
url: 'http://intern-dev01:50231/api/language',
success: function() {
console.log('It Works!');
},
error: function (request,status, error) {
console.log(error);
alert(status);
}
});
If you are testing locally with a different web app and web API applications , then debug your application and test API send data correctly and app calls to API via AJAX and return data.
since domains are not similar when run application AJAX call doesn't hit to success function. because browser prevents Cross Site request. If you publish both app in local and debug , it's work fine.
hope this would be helpful someone.
My web application does Ajax request to a Codeigniter-php code in a remote server. It works in localhost but not with a specific controller in remote host. It is strange because works in localhost for both controllers.
The request:
$.ajax({
async:true,
type: "POST",
dataType: "json",
url:"/CI/site/index.php/contact/submitContact",
data: "", //data example
success:arrived,
error:problems });
function arrived(data){
var dataJson = eval(data);
}
function problems(){
$("#result").text('Problems.');
}
I check the arrived with log_message. With the next function works fine:
function submitContact(){
log_message('error', 'submitContact. ');
//If data are received
if($_POST){
log_message('error', 'data. [application/controllers/contact.php]');
}
}
However, If I change the request to url:"/CI/site/index.php/control/controlHome", there isn't any log message and the output is the next:
POST http://www.page.com/CI/site/index.php/control/controlHome 500 (Internal Server Error)
The function /application/controllers/control.php is the next:
function controlHome(){
log_message('error', 'controlHome. [application/controllers/control.php]');
//If data are received
if($_POST){
log_message('error', 'data. [application/controllers/control.php]');
}
}
Also I've tried with complete url in the ajax code but the result is the same. Any setting is required?
Check this AJAX csrf protection with codeigniter 2. This solve my same problem
http://aymsystems.com/ajax-csrf-protection-codeigniter-20
UPDATE:
I checked your control.php file on my test server.
if($_POST) { /* i only commented gangway library functions */
} else { /* only replace the load->view with an print_r $data; and its work */ }
And put to comment the gangway library on construct. And control/controlHome works normaly without any error. Check your gangway library THAT's cause error 500.
I'm trying to process captcha in form validation using google's reCaptcha. Basically, my validation function is called using onSubmit in the form tag, and then calls a second function to work with the recaptcha api.
Here's the code:
var returnValue;
var myData = {
privatekey : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
remoteip : ip,
challenge : challenge,
response : response
};
$.ajax({
url: "http://www.google.com/recaptcha/api/verify",
type: "POST",
data: JSON.stringify(myData),
dataType: "text",
success: function(data) {
var result = data.split("\n");
if (result[0] == "true") {
returnValue = true;
}
else {
returnValue = false;
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert("There was an error submitting the captcha. Please contact an administrator. \n\nError:\n" + textStatus, errorThrown);
returnValue = false;
},
complete: function(jqXHR, textStatus) {
return returnValue;
}
});
Using LiveHTTPHeaders in firefox, I can see the request go out to the service, and it looks like everything is being sent correctly. I get an HTTP/1.1 200 OK response back, and yet every single time the code goes to the error function. When the error function runs, jqXHR is:
Object { readyState=0, status=0, statusText="error"}
textStatus is "error", and errorThrown is ""
I've tried doing this a number of ways, including $.POST, and using .done(), .fail(), .always(), and it always behaves the same.
I've seen some other postings here having to do with problems with cross-domain requests, but none of those situations really seem to be relevant, because I actually am doing a cross-domain request, and those seemed to be issues where they were making requests to a file on the same domain, and it was being handled incorrectly as a cross-domain request.
I'm at my wits end here.. any help would be greatly appreciated.
I've seen some other postings here having to do with problems with cross-domain requests, but none of those situations really seem to be relevant, because I actually am doing a cross-domain request
When I run that code I get the error:
XMLHttpRequest cannot load http://www.google.com/recaptcha/api/verify.
Origin http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin.
So it is a cross-domain issue. You might want to make a cross domain request, but Google isn't set up to allow it.
I'm pretty sure that recaptcha needs to be implemented with server side code. If you do it entirely on the client with JS then the client can lie and say it has passed the captcha when it hasn't.
function check(){
$.post('check.php',{
'check':1,
'challenge':$('#recaptcha_challenge_field').val(),
'response':$('#recaptcha_response_field').val()},
function(a){
console.log(a);
});
}
check.php:
if($_POST){
if(isset($_POST['check'])){
$url = 'http://www.google.com/recaptcha/api/verify';
$data = array(
'privatekey'=> "**********************************",
'remoteip' => $_SERVER['REMOTE_ADDR'],
'challenge' => $_POST['challenge'],
'response' => $_POST['response'],
);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
echo print_r($data,true);
die(file_get_contents($url, false, stream_context_create($options)));
}
}
Warning: You have only one choice to check! (Ref.)