Best way to pass a PHP array to JavaScript [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I wondering what the appropriate way is to bring in an array created in PHP and make it available to JS/jQuery (my front end)?
Dont get me wrong.. it 'works'..as far as functionality.. but I have a HUGE openly defined (multi-dimensional, object array) displayed in the source code...etc Nature of the beast? or a better/different way?
quick example
<?php
$totalEntries = mysql_num_rows($result);
$totalEntriesArray2 = json_encode($totalEntriesArray);
?>
<script>
var totalEntriesArray = <?= $totalEntriesArray2 ?>;
</script>
this works. I access the array as intended (multi-dimensional, object array..etc)
Is there a better/cleaner/simpler way similar to above?

I would propose using an Ajax request on the frontend that fetches the JSON array whenever the page is loaded.
A simple way of doing it would be via jQuery.
Backend PHP file (getarray.php) :
<?php
$totalEntries = mysql_num_rows($result);
totalEntriesArray2 = json_encode($totalEntriesArray);
echo $totalEntriesArray2;
?>
Frontend Javascript file (either in page or seperate .js file) :
// Execute Ajax request
$.ajax({url: "/getarray.php", dataType: "json"})
// When complete do something with data
.done(function(data) {
console.log(data);
});

You can get the array using AJAX in jQuery, so you won't have this array shown in your source code.

Related

Fetch json data if json still not created [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
This is a sample of my form in php:
echo "<form method='GET' action='queries.php'>
<label>name1</label>
<input type='checkbox' name='name1'/>
<label>name2</label>
<input type='checkbox' name='name2'/>
<label>name3</label>
<input type='checkbox' name='name3'/>
<input type='submit' name='sendData' value='Send'/>
</form>";
I take all the values in $_GET and i want to pass them in json to the frontend
$data = isset($_GET) ? $_GET : 0;
if (count($data)>0) {
$res = $data;
echo json_encode($res);
} else {
$noData -> Message = "No data passed";
echo json_encode($noData);
}
The problem is when i try to fetch with any http request the json generated from the form. I always get the $noData json instead of $res.
I need to use the data generated on a subsequent request. What would you suggest me to use to do that?
You need to store the data somewhere more permanent. Maybe in a file, or a database perhaps.
Or, if you only need the data for this user within their current usage session, then you could store it in the PHP Session. It depends on your exact requirements.
But the important thing to learn from this is that web applications are stateless - and therefore information held in ordinary PHP variables does not persist between different HTTP requests. If you want to keep the information submitted by the user, you need to have code to store it (and then more code to retrieve the correct information on a subsequent request).

How to convert PHP function to become called using Ajax [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Edit: I am not directly trying call a PHP function using Javascript. The application routing will help frontend to hit the correct function.
I think my problem might have a simple solution, but I am not able to figure it out.
I have a bunch of PHP functions that output HTML. Something like:
<?php
function sample1($param1)
{
//make DB query and loop and print HTML
?>
<div class='some-class'>
Some dynamic output here...
</div>
<?php
}
?>
So like I said there are a bunch of such functions. And I want to call them using Ajax so that their values can be returned and I can print them/update DOM using Javascript. I know that I can update all the functions so that the HTML they generate can be stored into a string and then I can each that string. But is there an easier, cleaner solution to this problem?
Because you are not providing me the javascript ajax call i will focus on the php side.
I am using a simple get Ajax call:
$.get( "https://someKindofLink.php?callFunction=Hallo&doctor=who", function( data ) {
alert( data );
});
On the php side we need to check is the function exists and the run it with all variables in $_GET:
if (isset($_GET['callFunction'])) {
if(function_exists($_GET['callFunction'])){
echo $_GET['callFunction']($_GET);
exit;
}
}
function hallo($params)
{
return "Goodbye".$params['doctor'];
}
I would not advise this approach for security reasons but it should get the job done.

Multiple files not appearing on server side [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have a problem when I'm trying to upload files to my server. I have done this many times before so I'm not sure why this is happening now. Nothing has changed to my knowledge.
What's happening is the following:
submit the 1, 2, etc... files through the uploader
check the headers it clearly shows N amount of files.
test php file and put the line print_r($_FILES); it will show only one file, the last one on the file stack specifically.
Just for reference I am using the jquery plugin Bootstrap File Input by Krajee.
file input plugin docs
http://plugins.krajee.com/file-input
JS
$.ajax({
url : '../assets/server/trade/submitTradeForm.php',
type : 'post',
data : data,
dataType : 'JSON',
success : function(response){
if(!response.errors){
if($('#images').get(0).files.length > 0){
$('#images').on('filebatchuploadsuccess', function(event, data, previewId, index){
//$('#tradeForm')[0].reset();
bootbox.alert(data.response.success_message);
});
$('#images').on('filelock', function(event, filestack, extraData){
extraData['trade_form__id'] = response.trade_form__id;
});
$('#images').fileinput('upload');
}else{
bootbox.alert(response.success_message);
}
}else{
bootbox.alert(response.error_message);
}
}
});
PHP
<?php
print_r($_FILES);
if(!empty($_FILES)){
if(!empty($_FILES)){
$names = array();
$files = array();
$mime_types = array();
foreach($_FILES['file']['name'] as $name){
array_push($names, $name);
}
foreach($_FILES['file']['tmp_name'] as $temp){
array_push($files, $temp);
}
foreach($_FILES['file']['type'] as $type){
array_push($mime_types, $type);
}
}
?>
Thank you ahead of time for any and all assistance!
Since the form wasn't posted along with how your file inputs are named, the name attribute for each file requires it to be accessed via an array.
For example:
<input type="file" name="file[]"> with the square brackets.
The brackets declares/signifies it as an array.
Therefore, PHP took in a file alright, only one and is the last one used because of the missing array declaration.
References:
http://php.net/manual/en/language.types.array.php
http://php.net/manual/en/features.file-upload.multiple.php

Pass jquery variable to php within same jquery [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am beginner on coding I need help on passing jquery variable to php inside the same jquery
<script language="javascript">
$(document).ready(function(){
$("#option1).change(function(test));
$("#option2).change(function(test));
function(test){
var select1 = $("select1").val();
var select2 = $("select2").val();
var phpselect1 = '<?php $select1 = '+select1+'?>';
var phpselect2 = '<?php $select2 = '+select2+'?>';
}
});
</script>
I want to pass the the jquery variable to php in this way but I can't pass it anyway. Is there any way to pass the variable like this to php? please help me. ...
Here is an example
AJAX:
var select1 = $("select1").val();
var select2 = $("select2").val();
$.ajax({
url: 'yourphpfile.php',
data: {data1 : select1, data2 : select2},
type: 'POST',
success: function(data){
//do something with the returned data
}
});
Server-side PHP (yourphpfile.php). To assign a value passed from AJAX, do the following;
$phpselect1 = $_POST['data1']; //should be value of select1 from JS
$phpselect2 = $_POST['data2']; //should be value of select2 from JS
PHP is handled server side (step 1). Javascript is done on the client-side (step 2). You're trying to tell the page to do something on the step that has already been done.
Also, you're trying to assign PHP variables using JS? If you need data to get to PHP, use GET/POST variables and pass relevant data to the PHP upon a page load/refresh.
You are doing it wrong. You need to use Ajax to send a Get or Post request to the server. In that request you can put your variable.

Proper way of adding multiple parameters for a jquery function to use [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am new to jquery and im trying to create a web client for a mobile social network. I would like to allow users to approve friend requests without refreshing, but the api request for approving a friend request requires 3 parameters to be successful. So how am i suppose to go about hiding these parameters in the html so that i can grab them via jquery when the button is pressed?
Are you want to make some server post back (to perform the request approval) and you need this without refreshing the page?
If this is the case use AJAX, you can do server post back without refreshing the page and manipulate the HTML tags. Regarding the parameter you can send more then three parameters in AJAX call.
Here is a sample of jQuery AJAX.
$.post("test.php", "{para1: "para1Value", para2: "para2Value", para3: "para3Value"}",
function(data) { alert(data); },
"json"
);
Guess you are asking this. :)
Below is reply for your comment:
To store the param in HTML property:
1. Create a function which get and set the value with passed argument
function myParas(para1,para2,para3)
{
this.para1=para1;
this.para2=para2;
this.para3=para3;
}
2. create a new object of myParas object and pass values to the parameters
var myObj=new myParas("para1Value","para2Value","para3Value");
3. access the property of the object and get the values
myObj.para1 //<= value will be para1Value
myObj.para2 //<= value will be para2Value
myObj.para3 //<= value will be para3Value

Categories

Resources