How can I pass a javascript variable as an variable in my php loop:
Something like this(obviously does not work):
var myJsVar = 100;
#for ($i = 0; $i<myJsVar; $i++)
... some code
#endfor
Further I tried solving this with ajax:
/**
* Get slider value
*/
$.ajax({
type: 'GET',
url: myUrl,
data: myJsVar,
success: function (option) {
console.log(myJsVar);
}
});
It returns me the success function,
Further I did this in my Controller:
public function prod(Request $request)
{
if ($request->ajax()) {
$ajax = "AJAX";
dd($ajax);
} else {
$ajaxN = "NO Ajax";
dd($ajaxN);
}
}
It did not work.
I am not sure how to proceed, hope for some help.
PHP has finished doing its work even before the page hits your browser, so passing a variable from Javascript to PHP without doing another request is simply impossible. Consider
A) Moving your loop to Javascript. Consider using some UI library like Vue.js, Angular or React.
B) Move the contents of myJsVar to PHP. If it depends on user input or browser rendering, that impossible.
C) Performing the rendering logic through an Ajax-request
$.ajax({
type: 'GET',
url: myUrl,
headers: {'X-Requested-With': 'XMLHttpRequest'},
data: {value: myJsVar},
success: function (response) {
$(someContainer).html(response);
}
});
And in your controller:
public function prod()
{
$value = Request::get('value');
return view('view-with-a-loop')->with('value', $value);
}
Be careful with the latter method XSS-wise.
I use a section in blade to add the javascript then pull that into the layout. The example below shows passing of integer/string/collection of models, eg:
// blade template
#extends('layouts.app')
#section('javascript')
<script type="text/javascript">
var myInteger = {!! $myInteger !!};
var myString = '{!! $myInteger !!}';
var myObject = {!! json_encode($models) !!};
</script>
#endsection
#section('content')
...
#endsection
// Layout (the javascript can go anywhere in the layout, ie the head or body:
<!DOCTYPE html>
<html>
<body>
#yield('content')
#yield('javascript')
</body>
</html>
One way you can do it is to render your value into a meta tag, like so:
<meta name="myJsVar" content="100">
Then use JavaScript to read that value via DOM:
var myJsVar = parseInt(document.querySelector("meta[name=myJsVar]").content);
Related
One php file with php and javascript inside. I have a multidimensional array defined in the javascript part. I can see the proper output of "key" and "value" in the console but I do no get the array into php after submitting my form.
What I am doing wrong?
<?php
echo "Postcmd: ".$_POST["postcmd"];
print_r($_POST["postcmd"]);
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
var postcmd =[];
var key;
function formsubmitplus(ele) {
postcmd.push({"key": ele.id, "value": ele.value});
for (key in postcmd) {
if (postcmd.hasOwnProperty(key)) {
console.log(postcmd[key])
}
}
request = $.ajax({
url: "/index.php",
type: "post",
data: postcmd
});
}
</script>
Not even this simple and often found script example works for me - what else might be the issue? Are there other (basic) things to know about js->PHP?
<?php
// index.php
?>
<html>
<head>
<title>Pass JS array to PHP.</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
var arrayfromjs = "123";
$.ajax({
type: "POST",
url: "index.php",
data: { testArray : arrayfromjs},
success: function() {
alert("Success");
}
});
</script>
</head>
<body>
<?php
echo "<br>Pass JS array to PHP.<br>";
$myArray = $_POST['testArray'];
print_r($myArray);
?>
</body>
</html>
Per the jQuery documentation,
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
Thus, your data field must contain an object (such as {foo: bar, foo_again: bar_again}; in PHP, this would read as $_POST['foo'] == "bar"). However, your code submits an array with one element: the object specified. In addition, PHP does not magically turn your JS array/object into a PHP array. You have to parse the string passed into PHP and turn it into the array you need.
If you print $_POST, you can see what exactly is being passed into your PHP. That might help you see what is happening.
You are creating the following structure using the push method:
[
{
"key":"first_name",
"value": "Bob"
}
]
Using your code, all you need to do is index the postcmd variable to the object. You also had some indexing issues with your loop. The key variable would just be index 0. So you would need to set it to postcmd[key] to check for the key named "key".
function formsubmitplus(ele) {
postcmd.push({"key": ele.id, "value": ele.value});
for (key in postcmd) {
if (postcmd[key].hasOwnProperty("key")) {
console.log(postcmd[key].key)
}
}
request = $.ajax({
url: "/index.php",
type: "post",
data: postcmd[0]
});
}
Using the above snippet, jQuery will then parse the data into the correct key value pairs. Without specifying the index, the data would be posted as undefined=Bob
On the PHP side you should be able to grab those values as such:
<?php
echo $_POST['key'].PHP_EOL;
echo $_POST['value'];
?>
Alternative Method - JSON Submission
You could make the following modification to post the data as JSON:
function formsubmitplus(ele) {
for (key in postcmd) {
if (postcmd[key].hasOwnProperty("key")) {
console.log(postcmd[key].key)
}
}
request = $.ajax({
url: "/index.php",
type: "post",
contentType: 'application/json',
data: JSON.stringify(postcmd)
});
}
Then on the PHP side you can grab the POST body using the following:
<?php
echo "<pre>";
$json_data = json_decode(file_get_contents('php://input'), true);
print_r($json_data);
?>
If you would rather work with a PHP Object vs an Associative array. Just change true to false.
Ad the end I found a solution without jquery which works for me the best.
It is "playing" with HIDDEN form fields.
Maybe someone finds it helpful:
function submitform() {
Object.getOwnPropertyNames(postcmd).forEach(function(val, idx, array) {
var outarrayoutput = val + ' ==== ' + postcmd[val];
console.log(outarrayoutput);
var newHidInp = document.createElement('input');
newHidInp.type = 'hidden';
newHidInp.name = 'outArray[]';
newHidInp.value = outarrayoutput;
maintable.appendChild(newHidInp);
});
document.maintable.submit();
}
On my website I am trying to basically generate a random code (which I will set up later) and then pass that code into a PHP file to later retrieve it when the client needs it. But my code just isn't working.
Here is the code:
Javascript/HTML:
function init() {
var code = "12345";
$.ajax({
type: 'POST',
url: 'codes.php',
data: { code: code},
success: function(response) {
$('#result').html(response);
}
});
}
PHP:
<?php
$code = $_POST['code'];
echo $code
?>
So what I understand that is supposed to happen is that the code is uploaded or 'posted' to the php file and then the #result is the echo $code. None of that happens and I have no idea.
Your code working perfect with some basic changes.
You need a html element with id 'result'.
And then you need to call your init() as per requirement.
<div id="result"></div>
<script>
function init() {
var code = "12345";
$.ajax({
type: 'POST',
url: 'codes.php',
data: { code: code},
success: function(response) {
$('#result').html(response);
}
});
}
init();
</script>
I tried this on my server in the head of my document, and it worked :)
I used on complete instead of on success.
<script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script>
<script>
function init() {
$.ajax({
type: "POST",
url: "codes.php",
data: {
'code': '12345'
},
complete: function(data){
document.getElementById("result").innerHTML = data.responseText
},
});
}
init();
</script>
with codes.php the same as you have :)
just a few notes:
Make sure you point your url to the correct file. You can check it by using the console network. Or you can simply print anything out, not just the $_POST data. e.g:
echo 'Test info';
Open browser developer panel, to see if is there any client code issue. For example, document with id 'result' existed, or you have not included jquery in. The developer console will tell you everything on the client side. For Chrome, check it out here https://developer.chrome.com/devtools
Have you actually called init() ?
I am using the well known ajaxForm Jquery Form Plugin (http://jquery.malsup.com/form/). I 'll present to you my code:
HTML code:
<script type="text/javascript">
$(document).ready(function() {
$('#users_form1').ajaxForm({
dataType: 'json',
success: processJson
});
});
function processJson(data) {
$("#first").val(data[1].elem1);
$("#second").val(data[1].elem2);
}
</script>
PHP code:
...
$result=$db->query($query);
if ($result->num_rows>=1)
{
$counter=0;
while ($row = $result->fetch_assoc()) {
$counter++;
$data1=$row["req_created"];
$data2=$row["subject"];
$temp[$counter] = array(
'elem1' => $data1,
'elem2' => $data2,
);
}
echo json_encode($temp);
}
As you may see from the above code, $temp is passed to var data inside function processJson. I'd like to know if array $temp is accessible outside processJson? For example, I want to choose $temp[3]["elem2"] upon a button click, however is it possible to get this data without searching again the database? If yes, how?
Thank you very much
You can have the data in variable, this will be like temporary storage.
<script type="text/javascript">
$(document).ready(function() {
$('#users_form1').ajaxForm({
dataType: 'json',
success: processJson
});
});
var tem_data;
function processJson(data) {
$("#first").val(data[1].elem1);
$("#second").val(data[1].elem2);
tem_data = data;
}
// Use tem_data anywhere;
</script>
But only last requested data will be the tem_data.
If you want all data then do it in array with array push method
I would like to know how I can pass a Javascript array from Javascript to PHP through Jquery/Ajax. In fact I created two files: t1.html and moslem3.php . The code of each file is below:
The code of t1.html:
<html>
<head>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
var table = ["actor", "subject", "object"];
$.ajax({
type: "POST",
url: 'moslem3.php',
data: table
});
});
</script>
</body>
</html>
The code of moslem3.php:
<?php
$myArray = $_REQUEST['table'];
echo $myArray;
?>
The file moslem3.php displays this message:
Notice: Undefined index: table in C:\wamp\www\test1\moslem3.php on line 2
So my question is: where is the wrong here exactly?..Is there any one who has any idea?
Thanks in advance.
PHP doesn't inherently know anything about the JavaScript variables being used, such as var table. Its insights for the $.ajax() request are completed limited to the data structure.
So, for PHP to know about a 'table' parameter in $_REQUEST, the data needs to include it that as a named value:
data: { table: table }
This defines the data as an Object with a property table assigned to the value of the variable by the same name.
You can witness the difference using $.param(), which $.ajax() uses:
var table = ["actor", "subject", "object"];
console.log($.param(table));
// "undefined=&undefined=&undefined="
console.log($.param({ table: table }));
// "table%5B%5D=actor&table%5B%5D=subject&table%5B%5D=object"
Change Jquery
<script type="text/javascript">
$(document).ready(function() {
var table = ["actor", "subject", "object"];
$.ajax({
type: "POST",
url: 'moslem3.php',
data: {t_name:table },
success:function(data){
console.log(data);
}
});
});
</script>
Change in moslem3.php
<?php
$myArray = $_REQUEST['t_name'];
print_r($myArray);
?>
Output:
Try this :
$.ajax({
type : "POST",
url: 'moslem3.php',
cache:false,
async:true,
global:false,
data : {
"table": table }
}).done(function(msg) {
alert(msg);
})
i have a html page, which contains a form and i want when the form is successfully submited, show the below div:
<div class="response" style="display: none;">
<p>you can download ithere</p>
</div>
i also have a jquery function:
<script type="text/javascript">
$(function() {
$('#sendButton').click(function(e) {
e.preventDefault();
var temp = $("#backupSubmit").serialize();
validateForm();
$.ajax({
type: "POST",
data: temp,
url: 'backup/',
success: function(data) {
$(".response").show();
}
});
});
});
</script>
and in my views.py (code behind) i create a link and pass it to html page. i have:
def backup(request):
if request.is_ajax():
if request.method=='POST':
//create a link that user can download a file from it. (link)
variables = RequestContext(request,{'link':link})
return render_to_response('backup.html',variables)
else:
return render_to_response('backup.html')
else:
return render_to_response("show.html", {
'str': "bad Request! :(",
}, context_instance=RequestContext(request))
backup = login_required(backup)
my problem: it seems that my view doesn't execute. it doesn't show me the link that i send to this page. it seems that only jQuery function is executed. i'm confused. how can i make both of them to execute(i mean jQuery function and then the url i set in this function which make my view to be executed.)
i don't know how to use serialize function. whenever i searched, they wrote that:
The .serialize() method creates a text string in standard URL-encoded notation and produces query string like "a=1&b=2&c=3&d=4&e=5.
i don't know when i have to use it, while i can access to my form field in request.Post["field name"]. and i don't know what should be the data which is in success: function(data) in my situation.
thank very much for your help.
You have to get and display the data from your ajax post function, where data is the response you render through your DJango server, for example:
t = Template("{{ link }}")
c = Context({"link": link})
t.render(c):
Your JS / jQuery should become something like this:
<script type="text/javascript">
$(function() {
$('#sendButton').click(function(e) {
e.preventDefault();
var temp = $("#backupSubmit").serialize();
validateForm();
$.ajax({
type: "POST",
data: temp,
url: 'backup/',
success: function(data) {
// 'data' is the response from your server
// (=the link you want to generate from the server)
// Append the resulting link 'data' to your DIV '.response'
$(".response").html('<p>you can download ithere</p>');
$(".response").show();
}
});
});
});
</script>
Hope this helps.