Pass jquery variable to php within same jquery [closed] - javascript

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.

Related

Not able to transfer variables from javascript to php using ajax [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I tried sending data stored in an array(emp) using ajax and other string variables like 'gtotal' in code but data has not been transferred to the PHP file. It doesn't show any error but when I removed the isset() function it says unidentified index. I tried with different variables but no luck so far. Console function is working in HTML file and returning the values passed but data has not been collected in PHP file-like return value of $_POST shows empty array.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script >
$('#btn').click(function(){
var grandtotal=document.getElementById("gt");
var x =grandtotal.textContent;
var gtotal= String(x);;
var emp={};
emp.name=gtotal;
if(x=== '₹0'){
alert("Add to your cart")}
else{ $.ajax({
method: "POST",
url: "connect2.php",
data: emp,
success: function(data){
console.log(data);
}
});
// location.href='connect2.php'
}});
</script>
<?php
print_r($_POST);
if(isset($_POST['gtotal']))
{
$gtotal = $_POST['gtotal'];
echo $gtotal;
}
?>
The problem is that no item called gtotal is being sent in the $_POST.
Do a var_dump($_POST) to check exactly what is being sent.
You asked for an object to be sent which has an item name. If you see that in the dump then you need to use $_POST['name'] not $_POST['gtotal']

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.

How to call php method in javascript? [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 already doing research in here.
Many people say ajax is better.
But I want to ask something first because I never use ajax.
I want to delete some row in database if I push yes on the windows.confirm using javascipt.
My HTML button
<button onclick="deleteFunction()">Del</button>
My Javascript function
<script type="text/javascript">
function deleteColumn(id)
{
if (confirm("Are you want to delete?") === true) {
// Do delete method in PHP
} else {
// Cancel delete
}
}
</script>
My delete method in Storage class
class Storage
{
public function delete($condition)
{
// Delete from database with condition
}
}
Do I must use ajax to call PHP method?
It's important to have two concepts clear, execution in server side and execution in client side.
Server side, like php, the code is interpreted in the web server.
Client side, like javascript, the code is interpreted in the browser of the user.
AJAX is really good to make the two sides work "together" without disturbing the user experience.
Using AJAX in this case isn't a must. AJAX is useful when you want to make an action without reloading all your site. If what you want to do is that, try using some jQuery function, like:
$.ajax({
url: "yourPHPfunction.php",
data: {
row: 123
}
}).done(function() {
alert("The row was deleted.")
});
in your js delete() function.
If you don't want to use AJAX, make a GET or POST request (via js) to the PHP file where you had coded the delete function.
It will be good if you take a look to jQuery API documentation here.
But before, to have a background about AJAX, it's good to read that.
This should give you basic flow:
<!-- the form sample -->
<form method="POST" action="your_php.php" onsubmit="return confirm('Are you want to delete?');">
ID: <input type="text" name="id" /><br/>
<input type="submit" name="submit" />
</form>
In PHP:
<?php
class Storage
{
public function delete($id)
{
// should be better if this is another class
$connection = new mysqli('localhost', 'your_db_username', 'db_password', 'database_name');
$stmt = $connection->prepare('DELETE FROM `table` WHERE id = ?');
$stmt->bind_param('i', $id);
$stmt->execute();
}
}
if(isset($_POST['submit'])) {
$id = $_POST['id'];
$storage = new Storage();
$storage->delete($id);
}
?>
I would answer with a simple phrase :
Look this video : How PHP Works
You will understand yourself, why what you are asking is not possible without AJAX.
Enjoy the video, and see you :)
I hope this answer will help you to figure out why you cannot do what you want to, without using AJAX or similar ;)
The php code need the php interpreter to run.
The browser cannot find the php interpreter to run your code in the javascript. So you must call a php server to help you.It will run your code and return your result.Using ajax is a better idea!

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

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.

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