I am executing an index.html file from the server test1.com. Mootools library file is included in this index.html file.
Following is a script that calls a PHP page:
<script>
var request = new Request.JSON({
url: 'http://test1.com/ajaxtest.php',
onSuccess: function(data) {
// the request was completed.
alert(JSON.stringify(data));
}
}).send();
</script>
ajaxtest.php
<?php
$arr['age'] = 30;
$arr['place'] = 'London';
echo json_encode($arr); exit;
?>
While executing index.html, I'm getting the correct output"
{"age":30,"place":"London"}
Now, ajaxtest.php is residing on another server, say test2.com. How to change the above script to make it work as earlier?
Not sure if this will be helpful to you now.
You need to use the Request.JSONP Class object to make cross site request:
new Request.JSONP({
url: "http://search.twitter.com/search.json",
data: {
q: "Arsenal"
},
onComplete: function(tweets) {
// Log the result to console for inspection
console.info("Twitter returned: ",tweets);
}
}).send();
Related
I am trying to send a "POST" request to my backend PHP code, which resides in functions.php in Wordpress. I get a readystate:4 and bad request(400 status) error when I run the code, if I change the "POST" to "GET" it works.
This is not the first time I encounter this, but previously it has been in my spare time projects, this time it is for work. as mentioned above I can "solve" it by changing the method to "GET", but that is not the method you are supposed to use when you add to your database. I've tried to comment out the lines with "dataType", "contentType", and "processData", but it doesn't make a difference I still just get a bad request(400) error. I have several "GET"s that work fine elsewhere in functions.php and urlen is pointing directly to functions.php.
JS
function AddToTable(){
Data={"action":"CreateProduct","Password":Password.value,"Varenr":Varenr.value,"Produkttype":Produkttype.value,"Navn":Navn.value,"Billede":Billede.value,"BilledeAlt":BilledeAlt.value,"Farve":Farve.value,"Tykkelse":Tykkelse.value,"Pris":Pris.value};
jQuery.ajax({
type: "POST",
url: urlen,
dataType: "json",
contentType: "application/json",
processData: false,
data: JSON.stringify(Data),
success: successfunction,
error: errorfunction,
});
function successfunction(data){
RefreshTable();
}
function errorfunction(data, status) {
alert("error: "+status+" Content: " + JSON.stringify(data));
};
}
Functions.php
<?php
function CreateProduct(){
exit;
}
add_action('wp_ajax_CreateProduct','CreateProduct');
add_action('wp_ajax_nopriv_CreateProduct','CreateProduct');
?>
I expect it to send the data to the server function, so I can do more with it there. But I get a readystate:4 and state 400 errorcode.
UPDATED: to include the Functions.php part of the code.
I guess your data to be posted is malformed.
You have prepared it like
Data={"action":"CreateProduct","Password":Password.value,"Varenr":Varenr.value,"Produkttype":Produkttype.value,"Navn":Navn.value,"Billede":Billede.value,"BilledeAlt":BilledeAlt.value,"Farve":Farve.value,"Tykkelse":Tykkelse.value,"Pris":Pris.value};
Variables to be posted should not be in quotes so your code there should begin like
Data={action:"CreateProduct",Password: Password.value,Varenr: Varenr.value, .....
and so on
A GET request to a URL will simply tell you whether or not it exists, in basic terms. If you send a GET request to cnn.com it will respond with a 200, if send a GET to cnnbootyshort.com, you will get no response.
In your case, rather than using exit, you could try using die(), along with an echo of what you want to send back to the browser.
<?php
function CreateProduct(){
echo "200";
die();
}
add_action('wp_ajax_CreateProduct','CreateProduct');
add_action('wp_ajax_nopriv_CreateProduct','CreateProduct');
?>
And your JS
function successfunction(data){
console.log(data); // for debugging
RefreshTable();
}
function errorfunction(data, status) {
console.log(data); // for debugging
alert("error: "+status+" Content: " + JSON.stringify(data));
};
Alternatively you can use wp_die() if you want to use a Wordpress specific function. Here is some documentation regarding its use.
<?php
function CreateProduct(){
wp_die();
}
add_action('wp_ajax_CreateProduct','CreateProduct');
add_action('wp_ajax_nopriv_CreateProduct','CreateProduct');
?>
#People downvoting this issue: what's wrong with it? Which info am I not providing?
I'm trying to do a cross-domain service call via javascript from domainA to domainX, but somehow the line console.log('OK'); is never hit. The line console.log('1'); is hit.
How can I make sure the line console.log('OK'); is executed?
www.domainA.com/test.aspx
<script type="text/javascript">
(function () {
var ttScript = document.createElement('script'); ttScript.async = true;
ttScript.src = '//www.domainX.com/js/test.js?v=1';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ttScript);
})();
</script>
www.domainX.com/js/test.js
(function () {
console.log('1');
$.ajax({
url: "//www.domainX.com/iplookup.php",
data: null,
type: 'GET',
async: false,
crossDomain: true,
dataType: 'jsonp'
}).done(function (data) {
console.log('OK');
});
})();
I tried jsonp and json as dataType. But when setting it to json or setting crossDomain to false I get:
XMLHttpRequest cannot load http://www.domainX.nl/iplookup.php?callback=jQuery1102023322901595383883_1419031985295&_=1419031985296. Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers.
www.domainX.com/iplookup.php
I tried with and without Access-Control-Allow-Origin
<?php
header('content-type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
$data = json_encode($_SERVER['REMOTE_ADDR']);
echo "jsonp_callback($data);";
//print json_encode($_SERVER['REMOTE_ADDR']);
?>
With the above configuration I get NO errors in my Chrome console.
Under network I see that the test.js is loaded succesfully when requesting page www.domainA.com/test.aspx
I checked under Net tab under the Response tab and I see the call being made to //www.domainX.com/iplookup.php" which returns the value I'd expect, in this case an IP address.
What more can I do?
When using jsonp you are atually requesting a file like this:
jsonp_callback(yourDataHere);
And this file is included into your document making the values accessible when the function is called.
So your php-file has to echo something like this:
<?php
$data = json_encode($_SERVER['REMOTE_ADDR']);
echo $_GET['jsonp_callback']."($data);";
?>
Note that you have to add the jsonp-function to the $.ajax:
$.ajax({
url: "//www.domainX.com/iplookup.php",
async: false,
jsonp: 'jsonp_callback',
dataType: 'jsonp'
}).done(function(data){
console.log(data);
});
Btw: Why would you do that call syncronous?
Edit: I wrote kinda crap. I updated my answer. The file you are requesting is just calling a function with your data as parameters. The callback is then the function itself. Jquery should normally handle that for you and make the data available in .done().
Read through the manual here!
My PHP script, 'getNews.php', (which works when I run it in the terminal and returns the correct data) is as follows:
<?php
header('Content-Type: application/json');
$db = new PDO('mysql:host=hostname;dbname=table', 'name', 'password');
$sql = "SELECT * from `news` ORDER BY date";
$result = $db->query($sql);
echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
?>
In my Javascript (I have JQuery loaded), I am attempting to pull this data in the following manner:
$(document).ready(function() {
$.getJSON("getNews.php", function(data) {
console.log(data);
});
});
which does nothing. When I change it to:
$(document).ready(function() {
$.get("getNews.php", function(data) {
console.log(data);
});
});
It writes the entire text of the php script to the console. Basically, it doesn't seem to be executing the php script or retrieving the json object at all. Thoughts?
Do you have a web server (like apache or nginx) installed? "It writes the entire text of the php script to the console." = You aren't invoking a PHP processor. Are you loading it like file:///something, or via http://something?
If you are using HTTP, make sure your web server knows to process PHP files. This usually involves editing a .ini or .cfg file; I can't tell which, because you don't mention what web server you are using.
It writes the entire text of the php script to the console
It could be that your server doesnt have php installed/configured. If thats not the case then see if this works for you
function prsJSN() {
$.ajax({
type: "get",
url: "getNews.php",
success: function(json) {
var dataArray = jQuery.parseJSON(json);
},
error: function(request, status, error) {
alert(request.responseText);
}
});
}
I am trying to connect to a remote server and basically run my application off files on that server. I am able to connect to the server but I don't know how to execute the php files on that server. Here's my javascript function on my local directory which connects to the server:
function test2(){
$.getJSON("http://sampleserver.com/check.php?var=test&callback=?", {
success:function(data){
alert("Working"); },
error: function() {
alert("Error");
}
});
}
This alerts "Working". Here's my check.php on the remote server:
<?php
echo "hello";
echo $_GET['jsoncallback'];
?>
Why is hello not being printed to the screen? How would I actually execute this script once I am connected?
Here is just one example:
var url = '/m.profile_msg/0/send/';
var dataString = 'msg_body='+ msg_body;
$.ajax({
type: "POST",
url: url,
data: dataString,
success: function(data) {
try {
//var data = jQuery.parseJSON(data);
alert(data);
} catch(e) {
alert(data);
}
}
});
And on the PHP side:
<?php
$xxarray = array('key' => 'value');
echo json_encode($xxarray);
?>
Your script IS already executing, but you're doing an AJAX call and simply alerting with your own message, you're not doing anything with the response, which would contain your hello text.
To run remote scripts - try doing your ajax call to a PHP script and have the PHP script shell execute something. But I wouldn't wait for the reply - rather return a status code back to the mobile device saying that the script is running.
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.