So I need to pass long string variable from JavaScript to PHP, but the URL shows me that its too long. I use this method:
function Fillup(id){
var answer = $('.nicEdit-main').html();
$.get('submit.php?id='+id+'&answer='+answer,
function(data){
$('.answer-div').html(data);
});
};
And grab them at the PHP file:
$id = $_GET['id'];
$answer = $_GET['answer'];
But there are times that answer variable are long html codes. For example I created textarea with text editor options, witch you can see is .nicEdit-main and if there is picture added, then my variable is too long to be passed trough URL. Can someone please suggest me a better method?
You can try this:
function Fillup(id){
var answer = $('.nicEdit-main').html();
$.post('submit.php',
{
id: id,
answer: answer
},
function(data) {
$('.answer-div').html(data);
}
});
};
And in PHP side :
$id = $_POST['id'];
$answer = $_POST['answer'];
Related
First, I put the array in localStorage into the variable.
var urls = JSON.parse(window.localStorage.getItem("urls"));
Now I need to transfer this array to a variable in php in the same page.
The ways I tried;
$urls = array();
for($i=0;$i<$count;$i++){
array_push($urls, "<script>document.write(urls[$i]);</script>");
}
Actually it kind of works.
<?php echo $urls[$i];?>
Normally when I say print to the screen, the variable works the way I want.
But
<a href="download.php?urls=<?php echo $urls[$i]; ?>" style="text-decoration: none">
When I say, the variable returns empty.
Or, when I say <img src = "<?php $urls [$i]; ?> it also returns blank.
AJAX
I tried very hard with Ajax and could not reach the result I wanted. My code is working. The problem is: I'm returning the variable with JS, but I can't use the variable over and over in php. I want to keep the variable in php and use it in php on the same page.
COOKIES
It worked for me perfectly. It meets what I want.
But
Data overload happened and crashed.
I do not intend to use it.
In short, I need to transfer an array in javascript to an array in PHP. I will use the array I transferred to PHP among php codes continuously.
Or isn't what I want is possible because php is a server-side language?
NOTE: My knowledge of JavaScript or PHP is limited. The primary language I use is SWIFT. I have been working on this problem for a long time. Thank you for your support.
In JavaScript you can fetch.
fetch("https://yourapi.api",
{
headers: {
"Content-Type": "application/json",
},
method: "POST",
body: JSON.stringify({
url: [
"https://otherurl1.url",
"https://otherurl2.url",
"https://otherurl3.url"
]
})
});
If window.localStorage.getItem("urls") is array you can put url:JSON.stringify(window.localStorage.getItem("urls"))
and In PHP you can get
$content = trim(file_get_contents("php://input")); //this will catch POST from JavaScript
$decoded = json_decode($content, true); //this will decode from JSON to PHP array
foreach($decoded['url'] as $url){
echo $url;
}
$decoded will be your array as PHP array
in PHP you can also check if post was sent as JSON
if ($_SERVER["CONTENT_TYPE"] === "application/json") {
$content = trim(file_get_contents("php://input"));
$decoded = json_decode($content, true);
}
To see as function/method, JavaScript will look like this
let fetchApi = () => {
fetch("https://yourapi.api",
{
headers: {
"Content-Type": "application/json",
},
method: "POST",
body: JSON.stringify({
url: window.localStorage.getItem("urls")
})
});
};
and PHP, you can use this everywhere
public static function get_data_from_js(){
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
$decoded = [];
if ($contentType === "application/json") {
$content = trim(file_get_contents("php://input"));
$decoded = json_decode($content, true);
}else{
//You can do here anything
}
return $decoded;
}
So basically what I'm doing is auto filling a textbox using AJAX to grab information from a PHP script that calls a C function.
This is what I've found in theory: (Assuming receiving only one value)
$(document).ready(function(){
window.setInterval(function(){
var ajaxurl = 'php/portserverclient.php',
$.post(ajaxurl, NULL, function (response) {
$('#v1').val(response);
});
}, 5000);
});
Now, if this works, which I believe it will. If I receive an array of values, then the input inside of function cannot be response, correct? So what would I have to change it to make it an array?
Just to be clear, my PHP script is using echo to output its information. I'd rather output in such a more "standard" manner as in V1 = 120, V2 = 120, etc. but PHP is new to me and that I am currently researching. Thank you.
EDIT:
Just to make it clearer
Would something like this work?
$(document).ready(function(){
window.setInterval(function(){
var ajaxurl = 'php/portserverclient.php',
$.post(ajaxurl, NULL, function (response[]) {
$('#v1').val(response[0]);
$('#v2').val(response[1]);
$('#v3').val(response[2]);
});
}, 5000);
});
Since you echo on PHP side, the response just can be a string.
But if that string if formed as a valid JSON, you will be able to use it like you wish.
So on PHP side, make sure the json format is valid:
$array = [120,340,800];
echo json_encode($array);
Then in JS... You received a string... You have to parse it to make it an array.
$(document).ready(function(){
window.setInterval(function(){
var ajaxurl = 'php/portserverclient.php',
$.post(ajaxurl, NULL, function (response[]) {
var responseArray = JSON.parse(response);
$('#v1').val(responseArray[0]);
$('#v2').val(responseArray[1]);
$('#v3').val(responseArray[2]);
});
}, 5000);
});
Per the OP update, you could try something like this to map each item of the array up to its corresponding text box you could do.
$.post(ajaxurl, NULL, function (response) {
for (var i = 0; i < response.length; i++) {
$("#v" + (i + 1)).val(response[i]);
}
});
This would map each index of the array returned from the JSON endpoint, to a corresponding text box.
If the JSON being returned from your endpoint is a valid JSON array, your response variable should already be an array!
Send your array as json:
echo json_encode(array($value1, $value2, $value3));
JS
$.post(ajaxurl, NULL, function (response) {
// selectors in same index order as response array
$('#v1, #v2, #v3').val(function(i){
return response[i];
});
},'json');
The easiest way (for me) to communicate between javascript and PHP is JSON.
So your PHP script have to generate an answer in this format.
PHP code
// At the top of your PHP script add this
// that will tell to your browser to read the response as JSON
header('Content-Type : application/json', true);
// Do your logic to generate a PHP array
echo json_encode($yourArray);
HTML code
<div class="someClass"></div>
Javascript code
var container = $('.someClass');
$.post(ajaxurl, NULL, function (response) {
console.log(response); // for debuging
for (let i = 0; i <= response.length; i++) {
let myItem = response[i];
container.append('<p>' + item + '</p>');
}
});
It's cleanest to generate dynamically the p elements because you don't know how many results your PHP file will return you.
I'm not sure of the javascript code, you maybe will received a json string that you have to transform to a Javascript Array
Before link you javascript to php script, try some call with postman (or others http client) to ensure that your 'webservice' is working as excepted
I have a Javascript function that pulls in the users latitude/longitude and stores it in an array for later use. What I'm trying to do is take the users latitude/longitude and run a distance comparison to several other latitude/longitudes which are stored in a database. What I'm trying to do, and I could be thinking about this all wrong, is make a call with AJAX within that Javascript, to a specific function within a PHP file (the function pulls just the latitude/longitude of each related store from the database). Normally, this should be easy, but there are multiple functions within the PHP file so I'm wondering if this can even be accomplished this way.
Thank you in advance for any help you can provide. I'm still new to all of this so your patience is appreciated.
This is the code I have so far (I'm brand new to AJAX so I don't have any AJAX code written yet):
function userPosition() {
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
currentPos.push(lat, lng);
}, function(error) {
alert('Error occurred. Error code: ' + error.code);
// error.code can be:
// 0: unknown error
// 1: permission denied
// 2: position unavailable (error response from location provider)
// 3: timed out
});
};
Here's the code within the PHP file:
public function get_closest_location() {
$addresses = array();
$i = 0;
//Get primary address
$addresses[$i]['lat'] = $this->dealer_info['lat_1'];
$addresses[$i]['lng'] = $this->dealer_info['lng_1'];
//Get Dealer Addresses
global $wpdb;
$results = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->gdp_dealers_addresses WHERE dealerId = %d", $this->dealer_info['dealer_id'] ), ARRAY_A );
foreach($results as $res){
$i++;
$addresses[$i]['lat'] = $res['lat'];
$addresses[$i]['lng'] = $res['lng'];
}
return $addresses;
}
The answer is Yes and No, so the solution is not totally straight forward
As you can only get AJAX to directly run a PHP script and not a function inside it, all you need to do is add some information to the POST data that you send to the PHP script to tell it what function within your PHP library you want to run.
So you add something like this to the posted variables
var params = {.........};
$.ajax({
method: "POST",
url: "some.php",
data: { toRun: 'userPosition', anyData: params }
})
.done(function( msg ) {
alert( msg );
});
Then in your PHP that is the first thing you test for
<?php
// check for existance of all required post variables
switch ($POST['toRun']) {
case : 'userPosition'
// get any other parameters out of POST array you may need
$params = array(.....);
userPosition();
break;
case : 'otherFunction'
...
...
default :
echo 'Huston we have a problem';
This is a basic outline and you will of course have to add some more code to look after passing back data, but this is the basic outline
}
Php essentially runs from top to bottom. Calling the file ftom the browser does just that.
If the file contains function definitions, but no calling code, nothing will be run.
To handle your problem, you need to:
Identify the function to be called
Check it is an allowed function, to avoid malichious code injection
Call the function
To do that, you can send the required function as a get parameter, check it against a whitelist, and call it:
//example.php
function somefunc(){}
function anotherfunc(){}
function privatefunc(){}
function onLoad(){
$func = isset($_GET['func']) ? $_GET['func'] : false;
$allowed = ['somefunc','anotherfunc'];
if(in_array($func, $allowed){
call_user_func($func);
}
}
//call onload function when script is executed
onLoad();
To call a function you would use the correct query string in your ajax request, eg /example.php?func=somefunc
I would recommend you pass a GET parameter to the php script. This would look as follows:
javascript:
$.post( "script.php?action=userPosition", { lat: "2.0123123", long: "2.0319239123" })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
append this to your php file:
if (isset($_GET["action"]) && $_GET["action"] == "userPosition") {
echo get_closest_location($_POST["lat"], $_POST["long"]);
exit;
}
you would need to modify the arguments of the php function obviously, but then this would be all it takes.
my javascript won't go into my Database.php file.
Anyone knows what's wrong?
I know there is another thread with this question but it just doesn't work for me.
I have this in javascript
var Score = 5;
//Score insert
var postData =
{
"Score":Score
}
$.ajax({
type: "POST",
dataType: "json",
url: "Database.php",
data: {myData:postData},
success: function(data){
alert('Items added');
},
error: function(e){
console.log(e.message);
}
});
and this in php
function InsertScore(){
$table = "topscores";
if(isset($_POST['myData'])){
$obj = json_encode($_POST['myData']);
$stmt = $conn->prepare("INSERT INTO " + $table + " VALUES (?)");
$stmt->bind_param('s', $obj);
$stmt->execute();
}
else{
console.log("neen");
}
$result->close();
change this line
success: function InsertScore(data){
to this
success: function(data){
the success parameter of jquerys ajax method has to be a anonymous function (without a name) or one defined in javascript but definitely not a php function.
You should read up on variable scope, your $table variable is not defined in the scope of your function.
You also have an sql injection problem and should switch to prepared statements with bound variables.
You are trying to send an object to your PHP file instead of a JSON data type.
Try 2 use JSON2 to stringify your object like this :
var scoreINT = 9000;
var usernameSTRING = "testJSON"
var scoreOBJ = {score:scoreINT,username:usernameSTRING};
var jsonData = JSON.stringify(scoreOBJ);
this would give you the following result "{"score":9000,"username":"testJSON"}"
You would be able to send this with your AJAX if you change ( if you follow my variable names ofcourse )
data: {myData:postData}
to
data: {myData:jsonData}
This would already succesfully transfer your data to your PHP file.
regarding your error messages and undefined. the message "e.message" does not exist. so thats the "undefined" you are getting. no worries here.
I noticed the succes and error are called incorrectly. I've just deleted them because there is no need to.
Next. moving up to your PHP.
you would rather like to "DECODE" then to encode your encoded JSON.
you could use the following there :
$score = json_decode($_POST['json'],true);
the extra param true is so you are getting your data into an array ( link )
or you could leave the true so you are working with an object like you already are.
Greetings
ySomic
This question already has answers here:
Javascript array for AJAX POST send
(2 answers)
Closed 9 years ago.
I need help, I can't find the solution. I have a javascript array which I need to pass to a php script that will store all the array values (max 3) on Session variables. My javascript array comes from a string.split call:
var indentificators = id.split("_");
What I need is some help on how to do the Ajax call and then how to get every element of the array one by one.
My main problem is the format that this data has to be sent and how to retrieve it.
PD: I would post my current ajax call code but I think it would not help, it´s all messed up.
JSON is your answer here.. Are you using a javascript library like jQuery or MooTools?
jQuery:
How do I encode a javascript object as JSON?
url = 'target.php';
data = {identificators: JSON.stringify(identificators) };
jQuery.post( url, data, , function( response ) {
//response handling
});
MooTools:
url = 'target.php';
data = { identificators: JSON.encode(identificators) };
howto post (Async) in mootools:
http://mootools.net/docs/core/Request/Request
In php:
$phpArray = json_decode($_POST['identificators']/$_POST['identificators']);
You can format your answer to send as JSON String
For example:
Javascript array:
var indentificators = id.split("_"); // [0] => 'Stack', [1] => 'Overflow'
so you can do this:
var response_to_send = "{\"var1\":" + indentificators[0] + ", \"var2\": " + indentificators[1] + "}";
here you receive this string in your php script (supposing the ajax request is successful and the value of the string in POST is 'values'):
$values = json_decode($_POST['values'])
echo $values[0]; // This print 'Stack' echo $values[1]; // This print 'Overflow'
I hope this is what your searching
var array = id.split("_");
data = JSON.stringify(array);
var url = 'you/url'
$.ajax({
type: "POST",
url: url,
data: {array: data},
});
Finaly I solved it:
var identificadors = id.split("_");
$.ajax({
url: './phpScripts/comunicador.php?method=sessioList',
type: "POST",
data: ({data: identificadors}),
success: function(){
alert('cool');
}
});
Then at my php page:
function sessioList() {
$data = $_POST['data'];
$_SESSION['list_id_product'] = $data[0];
$_SESSION['list_id_tarifa'] = $data[1];
$_SESSION['list_index'] = $data[2];
}
As I said, my main problem was the format for the data to be sent and how to get it.
Thanks all, I really appreciate it.