How to display a response from jQuery/ajax call in PHP - php

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);

Related

Sent data using Jquery Ajax to another page not working

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.

ajax data passing to php not working

Okay so, I've scoured stackoverflow for this answer and have come across several threads talking about how to do this, and well, they just haven't helped me yet.
This is all on one page, so that's probably the big problem. I really don't wanna send the post data to some other page and then redirect back to the one in order to get this to work, but I will if you guys cannot assist me in this endeavor.
Anyway, I have this page and I'm trying to pass data to the php via ajax, and I know that php is a server-side language, so the page would have to be reloaded once the data is passed.
php:
if (isset($_POST['location'])) {
echo $_POST['location'];
echo "hey";
}
jquery:
var whateva = "hello";
$.post('index.php', {'location': whateva}, function(){
//alert(data);
//window.location.reload(true);
});
alert(data); does get it to work and echo out given the isset (and also prints out all of the other html), but that is an alert which isn't practical, especially from a user standpoint. But that means that this ajax function is working. The problem here is that I want the same page to load, just with the $_POST['location'] variable set, so I had the bright idea of just reloading the page as the function in this case, which doesn't work. The isset never succeeds
Any help will be appreciated, besides telling me that combining php and javascript is a horrible idea as I already know that
Edit:
I was told to try making another page to post the data back which still didn't work, here's the code for that (with the main page ajax adjusted to direct it there instead):
window.onload = function(){
var inter = <?php echo json_encode($_POST['location']); ?>;
$.post('index.php', {location: inter});
}
I have tried it with and without quotes around location in the .post. Also I have tried to just have the plain javascript there, without the onload, still nothing. The response on the main page when changed to this
$.post('intermediary.php', {location: whateva}, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
it prints out the html of the hidden page, with the variable filled in (var inter = "hello" instead of having the php there, as it should), so the passing to that page works
Ok, here's the breakdown.
File one: index.html
This file is HTML and Javascript only, and is the page seen by the user. This could be a php page, but it does not need to be. Notice the quotes around the string 'whateva'.
<html><head></head><body>
<script>
$.post('intermediary.php', {location: 'whateva'}, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
</script>
</body></html>
File two: intermediary.php
This file is PHP only. It receives data silently through POST and returns data by echoing it.
<?php
if (isset($_POST['location'])) {
echo $_POST['location'];
echo "hey";
} else {
echo 'No data received!';
}
?>
Oh.... It's a simple mistake. your ajax syntax is wrong... Remove the quotes of ajax parameter inside the curly brackets. Just like
var whateva = "hello";
$.post('index.php', {location: whateva}, function(){
//alert(data);
//window.location.reload(true);
});
It will working fine.... But you might use variable to ajax paramete then, you should use variable name for ajax location parameter value. But you might use string for location parameter value, then you should use it value inside the quotes like this, $.post('yourfile.php',{location:'your_name'},function(){});. But you might use some value of location parameter use should type this code.$.post('yourfile.php',{location:30},function(){});

Refresh a div automatically when a PHP variable is updated

I have a div that calls a variable. When that variable changes, users need to refresh the page to see the new value. The variable is pulled from a separate PHP file.
I'm wondering if there's a way to use ajax to automatically update the div without the user refreshing the browser when it sees the PHP variable has been updated.
You could periodically check if there have been any change to the variable using ajax and if that is the case you could update the div.
var previousValue = null;
function checkForChange() {
$.ajax({
url: 'http://example.com/getVariableValue.php',
...
success: function(data) {
if (data != previousValue) { // Something have changed!
//Call function to update div
previousValue = data;
}
}
});
}
setInterval("checkForChange();", 1000);
I havn't tested the code, but it should be something like that. Will get data from http://example.com/getVariableValue.php, you'll have to fill in some information about the AJAX request. I'm assuming you know how to modify the code for your specific data format, be it XML, JSON or text.

php variables won't save properly

I'm posting to a php script, and I want to update some already existing variables in the script. My javascript is this :
$('.submit_html').click( function(e) {
e.preventDefault();
var requested = $('.page_select').val();
var text = new Array($('.edit_html').val(), $('.header_val').val());
$.post('data_handlers/get_content.php', {page: requested, action: 'update', text: text}, function(data) {
alert(data);
});
})
There really isn't anything complicated about the post, just a couple variables to tell the script what to do, and then a text variable, with the data in the first two spots of the array.
On the php side, I know it is getting the data correctly, but when I try to overwrite the current variable in the script, it doesnt stay saved after the php script completes.
php code:
if ($page == 'home') {
$home = $text[0];
$home_head = $text[1];
return;
}
So obviously, it is changing the variables during the execution, but reverting to the values that were manually saved in the script before. Is there anyway to actually have the values stay changed after the script ends?
It sounds like the session module is ideal for what you are trying to do.

decoding json value into a php variable

When I pass the results from getJSON to parseInfo() function just like the one below, is it possible to get results back into a php variable so that I could put the latter through another php function.
$.getJSON('getinfo.php', { id:id }, parseInfo);
function parseInfo(data) {
<?php
$some_var = json_decode(data);
function some_function($some_var) {
// rest of the script here...
}
?>
}
Can anyone please help me out with this? I would really appreciate it.
Cheers!
PHP runs BEFORE the page is sent. Javascript runs AFTER the page is sent. Therefore the only way to can run PHP is to request a page.
So, if you wanted to pass data to PHP, you would have to call another page like ajax.php:
<?php
$data = $_POST['data'];
// ... do stuff ...
?>
From your script:
$.post('ajax.php', data);
See this question.

Categories