I'm trying to retrieve user's city info by using the coordinates. There is a javascript function that takes latitude/longitude and sends it across to a php file with ajax:
Javascript function
if (navigator.geolocation) { //Checks if browser supports geolocation
var Clatitude = "no";
var Clongitude;
navigator.geolocation.getCurrentPosition(function(position) {
Clatitude = position.coords.latitude;
Clongitude = position.coords.longitude;
$.ajax({
type: "POST",
url: "../wp-content/themes/Avada-child/test_BLZ.php",
data: {'latitudine': Clatitude,'longitudine': Clongitude},
success: function(data) {
console.log(data);
},
dataType: "JSON"
});
},
function(error) {
alert(error.message);
}, {
enableHighAccuracy: true,
timeout: 5000
});
}
Server side script written in PHP
<?php
$latitudine = $_POST['latitudine'];
$longitudine = $_POST['longitudine'];
$geolocation = $latitudine.','.$longitudine;
$request = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.$geolocation.'&sensor=false';
$file_contents = url_get_contents($request);
echo ($file_contents);
function url_get_contents ($Url) {
if (!function_exists('curl_init')){
die('CURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
?>
The problem is that the response is not displayed in my console. I tried to ge the response with file_get_contents and still was not able to retrieve the response
Except for this, the rest of the code works fine. In fact as soon as I remove curl's stuff or file_get_contents from the php file, the rest of the code functions smoothly. I even managed to retrieve a (fake) response in ajax success function.
Can someone help? Thanks ;)
---edit
my curl execution time is very long, i run the same code on another server and these are the differences:
server with long curl execution time
{
"url": "http://maps.googleapis.com/maps/api/geocode/json?latlng=45.644843,8.9986268&sensor=false",
"content_type": "application/json; charset=UTF-8",
"http_code": 200,
"header_size": 377,
"request_size": 119,
"filetime": -1,
"ssl_verify_result": 0,
"redirect_count": 0,
"total_time": 127.26954,
"namelookup_time": 0.001964,
"connect_time": 127.23926,
"pretransfer_time": 127.239265,
"size_upload": 0,
"size_download": 11729,
"speed_download": 92,
"speed_upload": 0,
"download_content_length": -1,
"upload_content_length": 0,
"starttransfer_time": 127.269424,
"redirect_time": 0,
"certinfo": []
"request_header":"GET \/maps\/api\/geocode\/json?latlng=45.644843,8.9986268&sensor=false HTTP\/1.1\r\nHost: maps.googleapis.com\r\nAccept: *\/*\r\n\r\n"
}
server with short curl execution time
{
"url": "http://maps.googleapis.com/maps/api/geocode/json?latlng=45.644843,8.9986268&sensor=false",
"content_type": "application/json; charset=UTF-8",
"http_code": 200,
"header_size": 377,
"request_size": 119,
"filetime": -1,
"ssl_verify_result": 0,
"redirect_count": 0,
"total_time": 0.116182,
"namelookup_time": 0.012194,
"connect_time": 0.027452,
"pretransfer_time": 0.027473,
"size_upload": 0,
"size_download": 11729,
"speed_download": 100953,
"speed_upload": 0,
"download_content_length": -1,
"upload_content_length": 0,
"starttransfer_time": 0.114101,
"redirect_time": 0,
"redirect_url": "",
"primary_ip": "172.217.**.**",
"certinfo": [],
"primary_port": 80,
"local_ip": "192.168.**.**",
"local_port": 51393
"request_header":"GET \/maps\/api\/geocode\/json?latlng=45.644843,8.9986268&sensor=false HTTP\/1.1\r\nHost: maps.googleapis.com\r\nAccept: *\/*\r\n\r\n"
}
What is the matter with my server? I notice that in the first case there aren't ip references!
As your response from server is not in in form of JSON, so you should not set dataType:"JSON" from AJAX call.
Please comment it out from AJAX call.
$.ajax({
type: "POST",
url: "../wp-content/themes/Avada-child/test_BLZ.php",
data: {'latitudine': Clatitude,'longitudine': Clongitude},
success: function(data) {
console.log(data);
},
//dataType: "JSON" <-- COMMENT this out
});
OR
Another option is that you should send JSON encoded response from server.
$file_contents = url_get_contents($request);
echo (json_encode($file_contents));
Related
I'm trying to verify a very simple ajax request in WordPress (in order to diagnose a probem with a bigger form), and wp_verify_nonce keeps failing on my staging server, but on my localhost it works perfectly!
My setup is like this:
In my plugin __construct function I have:
wp_register_script('request-quote', plugins_url('scripts/request-quote.js', $this->root), array('jquery'));
wp_enqueue_script('request-quote');
wp_localize_script('request-quote', 'pqimageupload',
[
'ajax_url' => admin_url('admin-ajax.php'),
'security' => wp_create_nonce( 'my_text' )
]);
add_action('wp_ajax_prq_checknonce', [$this, 'prq_checknonce'] );
add_action('wp_ajax_nopriv_prq_checknonce', [$this, 'prq_checknonce'] );
Then in my request-quote.js I have this:
$('#verify_nonce').on('click', function(){
console.log('checking nonce');
let data = {
action: 'prq_checknonce',
security: pqimageupload.security,
}
$.ajax({
url: pqimageupload.ajax_url,
type: 'POST',
data: data,
cache: false,
dataType: 'json',
success: function (data, textStatus, jqXHR) {
console.log(data);
}
});
return false;
});
My prq_checknonce function is:
function prq_checknonce()
{
$response = [];
$response['nonce'] = $_REQUEST['security'];
$response['verify'] = wp_verify_nonce($_REQUEST['security'], 'my_text');
$json = json_encode($response);
echo $json;
die();
}
My HTML link:
Verify nonce
So it's about as simple as you can get! And when I click on the link on my local server: http://abc.localhost/form/' the console log shows thatverifyis 1, however when I upload this to my staging serverhttps://abc.myserver.com/form/` console log shows verify as false!
Does anyone have any ideas?
Much appreciated
Lar
Gaaahhh I'm so stupid!!! It was a caching issue, so whilst I was removing my temp files, I didn't delete my cookies... deleting my cookies did the trick!!
I'm trying to create a forum and jquery throws an 'illegal invocation' error.
Here is my jquery code:
$('#formSumbit').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: 'data-get.php',
type: 'POST',
data: new FormData(this),
contentType: false,
dataType: 'json',
success: function(value) {
var serialize = $.parseJSON(value);
if (serialize.success == 'false') {
$('.alert').fadeIn().delay(3000).fadeOut();
$('.alert-msgText').html(serialize.datamsg);
}
}
});
});
And here is my PHP code:
<?php
$user = $_POST['user'];
$msg = $_POST['message'];
if(empty($user)&&empty($message)) {
$data = array(
'success' => 'false',
'datamsg' => 'Please fill the textboxes'
);
echo json_encode($data);
} else {
mysqli_query($con,"INSERT INTO forums(name,message) VALUES ('$user','$msg')");
$data = array(
'success' => 'true',
'datamsg' => 'Done!'
);
echo json_encode($data);
}
exit();
?>
When the textboxes are empty and i click the submit button, nothing seems to work and jquery throws an illegal invocation error. I don't understand what the problem is. Can you please help?
And thanks in advance!
1) You have a typo mismatch between your form and your JavaScript:
<form id="formSubmit" and $('#formSumbit') - it should be $('#formSubmit') to match the spellings.
2) Unless you are trying to upload files via this AJAX request, then you can simplify things by replacing data: new FormData(this), contentType: false, with just data: $(this).serialize(). This will get rid of the illegal invocation error.
3) Writing dataType: 'json' means that jQuery will automatically try to parse the data coming from the server as JSON, and convert it. Therefore, in your "success" function, value will already be parsed and converted to an object. In turn therefore, using $.parseJSON is not necessary. You can just access value.success directly, for instance.
Here's a fixed version:
$('#formSubmit').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: 'data-get.php',
type: 'POST',
data: $(this).serialize(),
dataType: 'json',
success: function(value) {
if (value.success == 'false') {
$('.alert').fadeIn().delay(3000).fadeOut();
$('.alert-msgText').html(value.datamsg);
}
}
});
});
Working demo: https://jsfiddle.net/khp5rs9m/2/ (In the demo I changed your URL for a fake one, just so it would get a response, but you can see where I have altered it and left your settings in the commented-out part).
Need access to REST API from JS code, using jQuery ajax:
function tryQwintry () {
var data = {
"params[weight]" : "100",
"params[dimensions]" : "100x100x100",
"params[delivery_pickup]" : "msk_1",
"params[insurance]" : "false",
"params[items_value]" : "350",
"params[retail_pricing]" : "1"
};
$.ajax({
url: "http://logistics.qwintry.com/api/cost",
type: "POST",
dataType: "jsonp",
contentType: "application/json",
headers: {"Authorization":"Bearer " + MY_API_KEY},
data: data,
success: function (cost) {
console.log("стоимость доставки $"+cost);
},
error: getErrorMsg
});
}
Documentation of API (all examples are PHP):
<?php
define('SITE_URL', 'logistics.qwintry.com');
define('API_KEY', 'YOUR_API_KEY'); //don't forget to set your key!
$url = 'http://'. SITE_URL .'/api/cost';
$data = array (
'params' => array(
'weight' => 5, // in lb
'delivery_pickup' => 'msk_1', // full list of pickup points can be retrieved from /api/locations-list
'insurance' => true,
'items_value' => 500, // declaration items total cost in USD
'retail_pricing' => true // retail / wholesale pricing?
),
);
$data_string = http_build_query($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. API_KEY));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
Same thing I've coded in Java:
public double getCostPickup(String weight, String dimensions, String toPickup, String insurance, String value) throws Exception {
Map<String, Object> params = new HashMap<>();
params.put("params[weight_kg]", weight);
params.put("params[dimensions_cm]", dimensions);
params.put("params[delivery_pickup]", toPickup);
params.put("params[insurance]", insurance);
params.put("params[items_value]", value);
params.put("params[retail_pricing]", RETAIL_PRICING);
String url = BASE_URL+"/api/cost";
HttpResponse<JsonNode> jsonResponse = Unirest.post(url).fields(params).asJson();
return getCost(jsonResponse, insurance);
}
Have problems with configuring data of ajax request.
So any help would be greatly appreciated.
UPDATE: Changed my JS code:
function tryQwintry () {
var data = {
"params[weight]" : "100",
"params[dimensions]" : "100x100x100",
"params[delivery_pickup]" : "msk_1",
"params[insurance]" : "false",
"params[items_value]" : "350",
"params[retail_pricing]" : "1"
};
$.ajax({
url: "http://logistics.qwintry.com/api/cost",
type: "POST",
dataType: "json",
contentType: "application/json",
headers: {"Authorization" : "Bearer"+MY_API_KEY, "Access-Control-Allow-Origin" : "true"},
data: JSON.stringify(data),
success: function (cost) {
console.log("стоимость доставки $"+cost);
},
error: getErrorMsg
});
}
Getting this error in Chrome's developers mode:
Are you using CORS request?
If no then change datatype to "json" instead "dataType: "jsonp".
if you are doing CORS then enable CORS request then you need to add the php code to allow CORS request.
header("Access-Control-Allow-Origin: *");
check this link CORS with php headers
Json data format:
var data = {
weight : 100,
dimensions : "100x100x100",
delivery_pickup : "msk_1",
insurance : false,
items_value : 350,
retail_pricing : 1
};
$.ajax({
url: "http://logistics.qwintry.com/api/cost",
dataType: "jsonp",
contentType: "application/json",
headers: {"Authorization":"Bearer " + MY_API_KEY},
data: JSON.stringify(data),
success: function (cost) {
console.log("стоимость доставки $"+cost);
},
error: getErrorMsg
});
Note: method: "POST" is not allowed with JOSNP
I am attempting to create a method to take a CSV file, parse it into JSON, then send it to BigCommerce using their REST API. Initially I was going to use Javascript to do the whole thing, and everything up until actually connected to BigCommerce to PUT the data worked. BigCommerce doesn't allow CORS, resulting in a 401 response from the server and none of my data actually being sent. Because of this, I was going to switch to do it with PHP but being able to get the specific JSON object is much harder than it was with Javascript. The solution I've come up with would be for me to parse the data in Javascript, send it line by line to the PHP script and the PHP script would then connect to BigCommerce and send it for me.
First off, is this possible?
Here is some of my Javascript code:
$(document).ready(function () {
$('[type=file]').change(function () {
if (!("files" in this)) {
alert("File reading not supported in this browser");
}
var file = this.files && this.files[0];
if (!file) {
return;
}
i=0;
Papa.parse(file, {
delimiter: ",", // auto-detect
newline: "", // auto-detect
header: true,
dynamicTyping: true,
preview: 0,
encoding: "",
worker: false,
comments: false,
step: function(results, parser) {
console.log("Row data:", results.data);
console.log("Row errors:", results.errors);
currentID = results.data[i]["id"];
currentResult = results.data[i];
sendToBC(currentID, currentResult);
i+1;
},
complete: function(results, file) {
console.log("Parsing complete:", results, file);
$("#parsed_JSON").css("display", "block");
$("#ready_btn").css("display", "block");
$("#select_file").css("display", "none");
$("#retry_btn").css("display", "block");
},
error: function(error, file) {
console.log("Parsing failed:", error, file);
alert("Parsing failed. Check file and refresh to try again.");
},
download: false,
skipEmptyLines: true,
chunk: undefined,
fastMode: undefined,
beforeFirstChunk: undefined,
withCredentials: undefined
})
});
function sendToBC(id,data) {
jQuery.ajax({
type: "PUT",
url: "https://store.mybigcommerce.com/api/v2/products/" + id + "/discountrules.json",
data: data,
xhrFields: {
withCredentials: true
},
headers: {
'Authorization': 'Basic ' + btoa('username:key')
},
dataType:"json",
async: false,
success: function() {
alert("success")
},
error: function(xhr, status, error) {
console.log(error);
}
});
}
You'll notice I had to do something weird with the i=0 and the i+1 in the middle of the papa code but that was because I couldn't do a for loop in the step function.
My php is just the basic curl functions:
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $api_url );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array ('Accept: application/json', 'Content-Length: 0') );
curl_setopt( $ch, CURLOPT_VERBOSE, 0 );
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt( $ch, CURLOPT_USERPWD, "username:key" );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
curl_setopt($ch, CURLOPT_POSTFIELDS, $complete);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
$response = curl_exec( $ch );
curl_close ($ch)
I dont have the most experience with PHP especially with passing values into it through AJAX, so any help would be great. I'm not really certain how passing values between the files really works and how I can send this data to the PHP the best way programatically.
Thanks.
Considering you get an string object like {"id": "77", "min": "1", "max": "6", "price": 10}. and you want to retrieve id (77) from the JSON object.
$str = '{"id": "77", "min": "1", "max": "6", "price": 10}';
$jsonObj = json_decode($str);
$jsonObj->id; // the id.
Here $jsonObj->id is the id via which you can call your API.
Alright, so the way I ended up doing it was just using PHP and building a JSON string on my own with the values retrieved from the array by their key. So I did:
contents[$i]['id']
to get the id of the current item and stored it in a variable and did that for all the other columns of the csv. Then I built a string like this:
$jsonObject[] = '{"min": '.$min.',"max": '.$max.',"type": "'.$type.'","type_value": '.$value.'}';
and sent it through the API to Bigcommerce using CURL.
I'm trying to send JSON data from a web page using JQuery, like this:
$.ajax({
type: "post", // Request method: post, get
url: "http://localhost/ajax/login",
data: '{username: "wiiNinja", password: "isAnub"}',
dataType: "json", // Expected response type
contentType: "application/json",
cache: false,
success: function(response, status) {
alert ("Success");
},
error: function(response, status) {
alert('Error! response=' + response + " status=" + status);
}
});
In cake2.2, I have a controller named Ajax that has a method named "login", like this:
public function login($id = null)
{
if ($this->RequestHandler->isAjax())
{
$this->layout = 'ajax'; // Or $this->RequestHandler->ajaxLayout, Only use for HTML
$this->autoLayout = false;
$this->autoRender = false;
$response = array('success' => false);
$data = $this->request->input(); // MY QUESTION IS WITH THIS LINE
debug($data, $showHTML = false, $showFrom = true);
}
return;
}
I just want to see if I'm passing in the correct data to the controller. If I use this line:
$data = $this->request->input();
I can see the debug printout:
{username: "wiiNinja", password: "isCool"}
I read in the CakePHP manual 2.x, under "Accessing XML or JSON data", it suggests this call to decode the data:
$data = $this->request->input('json_decode');
When I debug print $data, I get "null". What am I doing wrong? Is my data passed in from the Javascript incorrect? Or am I not calling the decode correctly?
Thanks for any suggestion.
============= My own Edit ========
Found my own mistake through experiments:
When posting through Javascript, instead of this line:
data: '{username: "wiiNinja", password: "isAnub"}',
Change it to:
data: '{"username": "wiiNinja", "password": "isAnub"}',
AND
In the controller code, change this line:
$data = $this->request->input('json_decode');
To:
$data = $this->request->input('json_decode', 'true');
It works.
Dunhamzzz,
When I followed your suggestions, and examine the "$this->request->params" array in my controller code, it contains the following:
array(
'plugin' => null,
'controller' => 'ajax',
'action' => 'login',
'named' => array(),
'pass' => array(),
'isAjax' => true
)
As you can see, the data that I'm looking for is not there. I've already got the the proper routes code. This is consistent with what the documentation for 2.x says here:
http://book.cakephp.org/2.0/en/controllers/request-response.html
So far, the only way that I found to make it work, is as stated above in "My own Edit". But if sending a JSon string to the server is not the right thing to do, I would like to fix this, because eventually, I will have to handle third party code that will send JSon objects.
The reason you are struggling wit the data is because you are sending a string with jQuery, not a proper javascript object (JSON).
$.ajax({
type: "post", // Request method: post, get
url: "http://localhost/ajax/login",
data: {username: "wiiNinja", password: "isAnub"}, // outer quotes removed
dataType: "json", // Expected response type
contentType: "application/json",
cache: false,
success: function(response, status) {
alert ("Success");
},
error: function(response, status) {
alert('Error! response=' + response + " status=" + status);
}
});
Now the data will be available as a PHP array in $this->request->params.
Also for sending a JSON response, please see this manual page. Most of your code there can be reduced to just 2 lines...
//routes.php
Router::parseExtensions('json');
//Controller that sends JSON
$this->set('_serialize', array('data'));