I sent some data using ajax from test.php to another page order.php, but when i navigate to order.php and try to echo the data, I get the " Undefined index..." error message.
I have done console.log in the text.php file and confirmed that the data values were successfully set. But it doesn't reflect on the order.php file. I also started session in both files.
NOTE: Before i can send ajax data to DB, I will need to get the data via $_POST['data'] in order.php and save in a variable so that i can proceed to insert the values in the DB. In this case, I CAN'T even get the data. For some reason, the data posted to order.php did not get to the file. That's the issue I want to resolve. How can I get my ajax post data to order.php so that i can use it for something else?
Please what could be wrong with my code? See Code Below:
test.php
<script type="text/javascript">
$(document).ready(function(){
$(".addItemBtn").click(function(event){
var $form = $(this).closest(".formclass");
var qty = $form.find(".naira-input").val(); //form input`
var total = $('.amount').html(); //from javascript innerhtml
$.ajax({
url:'order.php',
method:'post',
data:{grandTotal:total, nairaRate:qty}, // dont worry about this. The values are succesfully set in console.log
success:function(response)
{
console.log(response+' values were sent successfully');// I tested and confirmed that data was sent successfully
}
});
});
});
</script>
order.php
<?php
session_start();
$_SESSION['grandTotal']= $_POST['grandTotal'];
$_SESSION['nairaRate']=$_POST['nairaRate'];
echo $_SESSION['grandTotal']; // I get Undefined index error here
echo $_SESSION['nairaRate']; // I get Undefined index error here
?>
When you navigate to order.php the code which assigns values to the session runs again, only thing time you haven’t made a post request so the values aren’t set.
Don’t use the same endpoint for displaying the data as you do for setting it.
Related
In my index.php I have the following jQuery code for responding to clicking an image:
<script>
$(document).on('click',".i-give-up", function() {
$("#take-a-guess").load("get_snippet.php");
[...snip...]
generate_HSK2_circle(<?php echo $answer_data["HSK2level"]; ?>);
});
</script>
When I click the image, it loads get_snippet.php which performs and processes a MySQL query. Moreover, if I add
echo "<script>console.log('get_snippet[new] HSK2 level: " . $answer_data["HSK2level"] . "' );</script>";
to the end of get_snippet.php, I can see the correct variable for $answer_data["HSK2level"] in get_snippet.php.
The problem is that the variable $answer_data["HSK2level"] in index.php does not change as a result of loading get_snippet.php.
Question: How do I ensure a PHP variable is available in index.php after being changed in a second php file (via a jQuery load())?
It seems to me that you are actually wanting to store the php value of $answer_data["HSK2level"] in a javascript variable so each time you call generate_HSK2_circle() you pass in the most current value
Note that ajax is asynchronous also so you need to use a complete callback before proceeding with new data
To do that your js would look like:
<script>
// new js variable recieves value on page load from php
var answer_data = <?php echo $answer_data["HSK2level"]; ?>;
$(document).on('click',".i-give-up", function() {
// use complete callback of load to assure new data loaded
$("#take-a-guess").load("get_snippet.php", function(){
// new data has loaded
[...snip...]
// use the js variable in function call
generate_HSK2_circle(answer_data);
});
});
</script>
Then in your new script tag (from load) update that js variable value
echo "<script>answer_data=". $answer_data['HSK2level']. "</script>";
If this new script tag is the only data being sent from server in load() a more appropriate approach would be to send json and use $.getJSON and manually update the js variable from the response object
The index.php file is not going to change after it is already rendered, unless PHP is processed on the server.
In order to pass this data, you may want to look into using a query string and redirecting back to index.php with a get variable.
https://www.php.net/manual/en/reserved.variables.get
Then in your get_snippet.php, you would direct to index.php?answer=... and retrieve it via htmlspecialchars($_GET["answer"])
Thank you for your time reading this. Ok, so I know how to pass a jquery variable to php with no action needed on the same page but now I need the opposite and I do not seem to find any documentation about it. Imagine the simpliest possible thing. I pass the name Jack to jquery like this:
<?php
$my_name = "Jack Goodman";
?>
<script>
$(document).ready(function(){
var my_name = <?php echo json_encode($my_name); ?>;
alert(my_name);
});
</script>
The question is how do I get the name from jquery back in php variable after?
<?php
$my_name = ?
?>
You need to understand how pages are constructed. PHP is a server side language, that means that all the PHP is executed prior to being sent to the client (i.e. the persons browser). Your PHP is parsed and what is sent to the client is:
<script>
$(document).ready(function(){
var my_name = 'Jack Goodman';
alert(my_name);
});
</script>
That is then executed on the client's PC. The PHP has completely finished, there is no way for the client to change the value of the PHP variable, it doesn't exist any more. The only way to pass information from the client to the server is to open a new connection (e.g. a new page) and set the information you want to send to the server as a GET or POST variable.
Imagine going to a page on your website, you enter a URL in the browser such as http://www.mywebsite.com. We can include variable information by using GET variables, so if we wanted to pass the name in it would be something like http://www.mywebsite.com?name=My%20Name (%20 is a space). In your PHP you can then access this using the $_GET superglobal, e.g. $name = $_GET['name'] and use it as you need.
So if you have some information you need sending to the server, traditionally you would use a form:
<form action="mypage.php" method="get" id="myform">
<input type="text" name="name" id="myname" value="Jack Goodman">
<button type="submit">Submit</button>
</form>
However you can also send data asynchronously using AJAX. That means we don't have to open a new page, or submit a form to send data to the server. AJAX allows us to send some data to the server and read its response. So to send the name variable we can use jQuery's AJAX plugin.
// We intercept the submission of the form
$('#myform').submit(function () {
$.ajax({
url: 'mypage.php',
type: 'GET',
dataType: 'JSON',
data: { name: $('#myname').val() }
}).success(function (response) {
alert(response);
});
return false; // This stops the form submitting so the page doesn't reload.
});
response will contain whatever the PHP page outputs. So if your PHP page looked like this:
<?php
$name = $_GET['name'];
// ... do something with $name
$response = ['result' => 'success', 'name' => $name];
echo json_encode($response);
We're passing back a JSON string, so response will contain that JSON string. However because we know that it's a JSON string and we tell jQuery to expect a JSON string response (by using dataType: 'JSON') jQuery will automatically convert that to an object for us, so response contains an object with the properties result and name.
I got the following ajax where I want to send data from a < form > to a PHP page, where the data will be stored in a DataBase and then I will return a password generated in the PHP to the AJAX, but seems that I can't succeed
$.ajax({
type:'POST',
url:'register.php',
data:$('#form_register').serialize(),
});
I'm new to AJAX and every answer I saw was just a PHP page with a few lines of code, it's impossible to use the JSON response in a PHP page with more code?
If you want to return some data from your register.php, you have to output it in this file:
<?php
// register.php
/* Do whatever has to be done here */
echo json_encode(<your data-array here>); // Encode the data you want to return here
In your script where the ajax request is made you have to handle the response from register.php
$.ajax({
type:'POST',
url:'register.php',
data:$('#form_register').serialize()
}).done(function(returnedData) {
// Process the returnedData
});
So I have the following code that someone else helped me get:
function updateEpisodeSeen() {
var anime_id = <? php echo $anime_id; ?> ;
var anime_list_entry_id = <? php echo $anime_list_entry_id; ?> ;
jQuery.post("/path_to_it/my_php_file.php", {
firstParam: anime_id,
secondParam: anime_list_entry_id
}, function (data) {
//this is your response data from serv
console.log(data);
});
return false;
}
Now the .php file that is ran, I update some information and echo two variables out.
So in the console.log(data); those two variable values are shown properly. I am just wondering how I can show these values in my actual php code? Since these values are updated on the backend, I want to show the users their updated values on the front end as well. So if I could possibly set a php variable to those responses and then echo those instead, but php code isn't ran until a page refreshes so that might not be the way to go since I want the values to update without the page refreshing.
if you want to assign the response to some PHP variable you can follow this
jQuery Ajax response variable from php
if you want assign to a html variable you can do that using Jquery
$('#ID OF FIELD').val(data.text);
or
$('#ID OF FIELD').html(data.text);
I am creating a web application and have the following problem.
In my application the user is working within a single page, they draw on a canvas. There is a single button called "Save". This takes the users ID and whatever they have created in the canvas and sends it to a database. This all works fine. The save function resemebles this:
$.ajax({
url: "/database/write.php",
type: "POST",
data: {
docName: name,
docData: document_Data,
docMode: "new"
},
success: function(html) {
alert("Successfully Saved NEW document");
set_Mode();
},
});
The above AJAX request does send the three values to the PHP script which then successfully creates a new document in the database, what i need to do now is change the application mode from saving a new document to editing the previously saved document. This means that when a user saves again, they will write to the same row, overwriting the previous version of the document.
When i send the data to the write.php it does write the data to the DB and the queries the database for that inserted document and retrieves its unique document ID. with that ID the application can the select that document and overwrite it. To retrieve the document ID from the query, i use the following code in write.php
write.php
$_SESSION['DOCUMENT_ID'] = $DOCUMENT_ID;
This $DOCUMENT_ID is the document ID retrieved from the SELECT query. The script then finishes and transfers control back to the main application page.
Back on the application page i try to retreive the value but it doesnt seem to work. I can retrieve $_SESSION values that were set when the user first accesses the application (id) but now values set by the write.php (DOCUMENT_ID) page. For example, below shows the function called after the AJAX request has been successful:
function set_Mode()
{
var PHPvar_01 = <?php echo($_SESSION['id']); ?>;
alert(PHPvar_01); //WORKS FINE
var PHPvar_02 = <?php echo($_SESSION['DOCUMENT_ID']); ?>;
alert(PHPvar_02); //DOES NOT WORK.
};
How should i go about sending data retrieved from the PHP query script to the application, because $_SESSION does not seem to work here.
Thanks for any feedback.
at the end of write.php :
echo json_encode(array('id'=>$_SESSION['id'], 'DOCUMENT_ID'=>$_SESSION['DOCUMENT_ID']));
in your ajax call :
success: function(data) {
data = eval('('+data+')');
alert("Successfully Saved NEW document");
set_Mode(data.id, data.DOCUMENT_ID);
},
this should do the tricks !
In your write.php, you should echo the $DOCUMENT_ID at the end of the page, and then your success function will receive that in the html argument. Then you should call set_Mode with the html variable that was passed into the success function.
You can't call set_Mode until after the page is loaded, and after you know the document ID. You are writing the document ID into the set_Mode function before you know it, in the initial page load.
Well, your PHP code gets executed only once upon the initial loading of the page. The server detects a request to your site, loads the PHP document internally, parses it and delivers it to the client.
Therefore, when the AJAX call returns, the entire PHP script is not executed again, because the user didn't request the whole page but only sent a single request to your write.php.
Your write.php script must return the $DOCUMENT_ID in some way, e.g. echo it directly, then the success handler in the jQuery AJAX call can access it via the handler's parameter (see jQuery documentation).
You can't access variables on the server when the page is already loaded in the users browsers, other than with ajax.
You need to send something back, and in PHP all you have to do is echo something, and capture it in the success function of your Ajax call.
at the end of /database/write.php, do
echo $_SESSION['DOCUMENT_ID'];
and in JS
$.ajax({
url: "/database/write.php",
type: "POST",
data: {
docName: name,
docData: document_Data,
docMode: "new"
},
success: function(data) {
alert("Successfully Saved NEW document");
set_Mode();
if (data == 'something') {
//do something with the returned DOCUMENT_ID stored in the data variable
}
},
});