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).
Related
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.
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 4 years ago.
Improve this question
I want the variable $con to get data(country) from a JavaScript function and save it in SQL database. the insert query is working fine without JavaScript code but when I want to add $con into my database using insert query, the insert query do not add data to my SQL database
Here is my code:
$con = "<script>
function jsonpCallback(data) {
var con = document.write(data.address.country) }
</script>
<script src='http://api.wipmania.com/jsonp?callback=jsonpCallback'></script>";
$sql = "INSERT INTO `searched1`
(`search`, `longitude`, `latitude`, `country`, `date`)
VALUES ('$phone','$lon','$lat','$con','$datetime')";
$result=mysqli_query($conn,$sql);
I don't know how you're initiating the SQL query but I would use a form:
<form>
<input name="con" id="con" value="">
<input name="submit" id="submit" value="Submit">
</form>
<script>
document.getElementById('con').value = data.address.country;
</script>
<?php
$con = $_POST['$con'];
$sql = "INSERT INTO `searched1`
(`search`, `longitude`, `latitude`, `country`, `date`)
VALUES ('$phone','$lon','$lat','$con','$datetime')";
?>
I'd like to add to the previous answer that Edward wrote, whats wrong with this is that you can never get a value from Javascript into a PHP variable like this.
That code is rendered on the server, and Js only renders in the 'viewers' browser.
At best this would just input a string containing your script function. You should use a form or Ajax to send data to the PHP script/function which executes the database insert query. That's the proper way.
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!
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.
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