Passing Javascript variable to PHP and then reloading page without refresh - javascript

How do you reload a page without re-fresh after sending a javascript variable to PHP via Ajax.
Below is an image of a webpage I'm creating which analyses asset performance.
What I'm trying to do is the following.
When a user selects a test block with in the graph, the selcection box is updated with all subtests within that specific test block. However, I do not want to refresh the page. I have managed to send the the selected tested block to the PHP code via ajax, but can not get ajax to reload the page without a refresh.
Currently, when a test block is selected, the label is return to PHP and is stored in the $_SESSION['label'] variable. This is then used in the panel header #subtest-chart-select. However the label will not update without a page refresh which is what I want to avoid.
Ajax:
$("#test_block_chart").click(
function(evt){
var activePoints = myNewChart.getElementsAtEvent(evt);
if (activePoints[0]) {
var chartData = activePoints[0]['_chart'].config.data;
var idx = activePoints[0]['_index'];
var label = chartData.labels[idx];
//alert(label);
$.ajax(
{
url:'test_performance.php',
type: 'POST',
datatype: 'json',
data: {'label':label}, // post to location.php
success: function(label) {
// success
},
error: function(label) {
alert("There may an error on uploading. Try again later");
}
});
}
});
});`
PHP:
session_start();
if(isset($_POST['label']))
{
$_SESSION['label'] = $_POST['label'];
}
PHP echo HTML
<?php
echo '<div class="row">
<div class="col-lg-12 subtest-select">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title" id="subtest-chart-select"><i class="fa fa-bar-chart-o fa-fw"></i>' . $_SESSION['label'] . ' Subtest Select </h3>
</div>
<select class="form-control">
<option>1</option>
</select>
</div>
</div>
</div>'
?>
I'm still to write the PHP code to update the options of subtests within the selected test block.
Any help will be greatly appreciated as I've been trying to get this working for what seems like forever.

In $.ajax() set
dataType: 'text',
In your $.ajax() success function say:
success: function(data) {
$('.inside_whereever_you_want_to_show_this').html(data);
}
Edit:
To update only one value on page you can:
a) in PHP print out only this value (so that whole page would be only this value).
<?php echo $_SESSION['label']
and in HTML put a span around the bit you want to update (avoid constructing longer strings in javascript, all constant parts should be in HTML)
<h3 class="panel-title" id="subtest-chart-select"><i class="fa fa-bar-chart-o fa-fw"></i><span class="subtest-updateable">' . $_SESSION['label'] . '</span> Subtest Select </h3>
then you can update only your needed bit with whole response
success: function(data) {
$('.subtest-updateable').html(data);
}
b) better (in systematic approach means) would be use json response, where you can return more isolated variables as well:
Set dataType to json.
Success function would use $('.subtest-updateable').html(data.label)
In PHP print json_encode(array('label' => $_SESSION['label'], 'someelse' => $someother_variable ))
You still should put span (or some other html element) around updateable bits of your page (to avoid writing constants into your javascript)

In your success function you need to update the part of the DOM that you want to change. On the PHP side just return your blade partial or whatever HTML you want to display.
$(document).on('submit', 'form#form-grad', function (e) {
e.preventDefault();
var context = $(this);
var thisForm = context.closest('form');
$.ajax({
url: thisForm.attr('action'),
method: 'PUT',
data: thisForm.serialize(),
success: function (response) {
$('#updatearea').html(response.pt_html);
// Close grading form
}
});
return false;
});

Related

How to display a mysql database without refreshing the page with data from GET data without clicking button

My Problem is trying to display value from the database without refreshing the page.
Ok, My Code consist of value retrieve from page 1 to page 2 using GET methods, let's say the value is captured from the data-name "location" which consist of the value of 3.
The value of "location" on page 2 is then used to grab the information of the user on which location is stored and display the data that needs to display on a table on page 2 without clicking any button, basically on page load, it will display the data.
Then to make the data automatically update without refresh, I tried using a method that needs me to use Ajax that uses a GET to page 3 which supposedly have all the PHP to select database MySQL scripts.
In the PHP to select database MySQL scripts, my codes require to use the "location" data from page 2 that retrieve from page 1.
Since I need to POST using an ajax script, I added a PHP script into my Ajax script with a return value from page 3 data as well.
But it does not show the value that needs to be shown. Your help or guidance is highly appreciated. Thank You in advance.
Here are my codes for Page 2 (display page)
$locationID = #$_GET['location'];
$sqlCheckVisitors = "SELECT * FROM visitor_list WHERE visitor_EventChooseID = '$locationID'";
$resultCheckVisitors = $conn->query($sqlCheckVisitors);
$calCheckResult_visitor = mysqli_num_rows($resultCheckVisitors);
if($calCheckResult_visitor > 0)
{
$value_originalVisit = $calCheckResult_visitor;
}
else
{
$value_originalVisit = 0;
}
<div class="row">
<div class="form-group col">
<label class="form-control form-control-lg text-8 text-center">Live Balance : <br>
<div id="live_totalbalance"></div>
/
<div id="live_totalpreset"></div>
</label>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
// Display Total Live Balance
$.ajax({
url: "livedata_totalbalance.php?locationID=<?php echo $locationID ;?>",
type: "GET",
dataType: "html",
cache: "false",
success: function(data)
{
$('#live_totalbalance').html(data);
}
});
});
</script>
Here are my codes for Page 3 (livedata_totalbalance.php)
<?php
include "database.php";
$locationID = #$_GET['locationID'];
$sqlEventList = "SELECT * FROM event_list WHERE event_id ='$locationID'";
$resultEventList = $conn->query($sqlEventList);
$dataEventList = mysqli_fetch_array($resultEventList);
$event_data = $dataEventList['event_data'];
echo $event_data;
?>
If you want to change the data in a certain period of time Or change it for example after user landed on you page without refreshing the page, you could put your ajax in a JS timer like this:
setTimeout(() => {
$.ajax({
url: "livedata_totalbalance.php?locationID=<?php echo $locationID ;?>",
type: "GET",
dataType: "html",
cache: "false",
success: function(data)
{
$('#live_totalbalance').html(data);
}
});
}, 2000);
this will get new data after 2 Seconds (2000 ms).
or even if you want to change data in every 2 seconds, you can put this code in a for or while loop.
Hope it works :)

Add HTML code triggered by selection changed

I have a simple select into my HTML code (a dropdown menu).
HTML
<select name="razza" onchange="razzaChanged()">
<?php while ($row = gdrcd_query($result, 'fetch')){ ?>
<option value="<?php echo $row['id_razza']; ?>" <?php if(gdrcd_filter('get',$_POST['razza'])==$row['id_razza']){ echo 'SELECTED'; } ?>>
<?php echo gdrcd_filter('out',$row['nome_razza']); ?>
</option>
<?php } ?>
JavaScript
<script>
function razzaChanged()
{
alert("I am an alert box!");
}
</script>
When the selection of the dropdown is chosen, I have to add some information below the dropdown. The information I have to add is a bit complex and pretty formatted (I need to do some query to retrieve data and then add text and another dropdown after the info).
How can I achieve this? I can register via JavaScript that the selection changed but then I don't know how to go further.
You could use ajax methods. Get value from select using oninput/onchange, use that value as data in ajax request. If request is successful then show server's response in a container where ever you want.
HTML
<select name="razza" id="razza">
<option value="1">Some Option</option>
<option value="2">Another Option</option>
<!-- Use your loop here and remove these options -->
</select>
Javascript
$("#razza").on('input change',function(){
var value = $(this).val();
// Ajax Request
$.ajax({
type: 'post', // you can also use 'get'
url: '/link/to/your/server/file',
data: {
key: value // use key required by backend
},
success: function(response) {
$('#your-container-div-id').html(response);
}
});
});
Please note that I have used code without 'onchange' attribute, as this is better. Feel free to ask...
There are few ways to achieve this. One would be to use what jquery library offers.
Here are just some very rough steps of how one could do it:
In your razzaChanged() function establish which value is selected:
function razzaChanged()
{
var val = $('select[name="razza"] option:selected').val();
// step 2 here
}
Now use this value to fetch data from the server with the help of AJAX:
$.ajax({
type: "GET",
url: '/your-url-to-call',
data: 'your_value=' + val,
success: function(data) {
// step 3 here
}
});
Now having data from server (i.e. json format) build your new select dropdown, i.e.:
var newSelect = $('<select>').appendTo('body');
$(data).each(function() {
newSelect.append($("<option>").attr('value', this.some_property).text(this.some_text));
});
It's definitely not a ready-to-use code as you would have to make sure you return properly formatted data on server side or change the code accordingly. Also
make sure jquery library is loaded and the code is wrapped with its ready function (easy to find example on internet).
Hope this helps.
You will need to do an AJAX POST or GET request to retrieve data from your database and you will need to use document.createElement("elementtype"); to create an element to add to your page.
With jQuery, your AJAX would look something like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$.ajax({
type: "POST",//can be GET or POST
url: "yoururl",
statusCode: {
404: function() {
alert( "page not found" );
},
data: {key: value},//you can have multiple keys and values
success: function(res){
//add elements to the page
$('#yourelememntid').html(res.someattribute);
}
}).done(function() {
//AJAX request finished
});
</script>

Setting PHP session variables with ajax

Want to change value of SESSION variable "fullname" without refreshing the page.
My implementation using ajax:
Page 1 html:
<input type="text" name="fullname" id="fullname" placeholder="Full name">
<button onclick="setSession()"> GO </button>
Page 1 script:
<script>
function setSession(){
var fullname = $("#fullname").val();
var dataString = 'fullname=' + fullname;
$.ajax({
type: "POST",
url: "Page2.php",
data: dataString,
cache: false,
success: function( data ) {
if(data === 'True'){
alert("<?php echo $_SESSION['fullname'];?>");
}
}
});
}
</script>
And in Page 2:
session_start();
$_SESSION["fullname"] = $_POST["fullname"];
echo 'True';
exit();
It doesn't change the value of the session variable.
Both pages have session_start().
Your code should already be changing the value in the PHP session. You just don't have your client-side script set up properly to show that.
Return some kind of indicator in your PHP script:
<?php
// Page2.php
session_start();
$_SESSION["fullname"] = $_POST["fullname"];
echo 'set session fullname to ' . $_POST['fullname'];
Then in your AJAX success function, show that response:
...
success: function( response ) {
alert(response);
}
...
When you use alert("<?php echo $_SESSION['fullname'];?>"); in your success function, PHP will fill in the $_SESSION['fullname'] value in that alert box once when the page loads, and it will never change until the page is reloaded, even if you do successfully update the session value via AJAX.
First, have you watched the AJAX request / response in the browser's developer tools? Have you included the jQuery library in the project? Are there any errors reported? Are you running this on a web-server?
Second, you're starting a session in a remote page. That session data will not be available in the current page until you reload the current page. In addition you have some wonky quoting in your alert, it should be:
alert("<?php echo $_SESSION['fullname'];?>");
Page 1 HTML
<input type="text" name="fullname" id="fullname" placeholder="Full name">
<button onclick="setSession()"> GO </button>
Page 1 Script
<script>
function setSession(){
$.ajax({
type: "POST",
url: "Page2.php",
data: { fullname: $("#fullname").val() },
dataType: "json",
cache: false,
success: function( data ) {
alert(data.fullname);
}
});
}
</script>
Page 2 PHP Script
session_start();
$_SESSION["fullname"] = $_POST["fullname"];
echo json_encode(array('fullname' => $_SESSION['fullname']));
It's generally a bad idea to mix server-side and client-side scripts together so try to separate your PHP and Javascript logic. They both execute at different times/stages of a page request life-cycle.
You are setting the variable in JS using PHP Inline coding. You could however echo the session variable in page2 if no post has been set. If you then request page two without any post you can use the response body in JS to get the current set session variable and put it in a JS variable.
Var name;
$.get(‘page2.php’, function(data){ name = data; } );
I’m using the iOS app so above code is not complete but an indication for what can be done.

Passing jquery variable into php script in a modal with ajax

i'm having problem getting the value of a variable into the modal which is supposed to be openning. i have tried using post but nothing changed. Both codes are in index.php.
This is the jquery script passing the value
$(document).ready(function () {
$(".issue").click(function () {
var x = $(this).attr("id");
$.ajax({
url: "index.php",
type: "GET",
data: {data1: x,},
success: function () {
$("#modal2").modal('show');
}
});
});
});
And i tried echoing the id of class .issue but it doesn't works
<div class="modal fade" role = "dialog" id = "modal2" aria-labelledby = "myModalLabel" aria-hidden = "true">
<div class="dialog">
<div class="modal-content">
<div class="modal-body"><?php echo $_GET["data1"]; ?></div>
</div>
</div>
</div>
You're missing the variable in the success method. It should be success:function(ajaxData){}
So in all:
var x = $(this).attr("id");
$.ajax({
url: "index.php",
type: "GET",
data: {data1: x,},
success: function (ajaxData) { // ajaxData is the return data from php
// add the data to the modal
$("#modal2 .modal-body").html(ajaxData);
$("#modal2").modal('show');
}
});
Are you sending the data server side to save it, or grab information from the database? If all you're trying to do is move the data to the modal, ajax isn't necessary.
Part of me suspects you're not properly calling and passing the data to php, if you really do need ajax. The php you send the ajax data to should be a separate file, that receives it, processes it, and echos it back to the ajax success function. Then the ajax function puts the data in the modal and displays the modal.
Hope one of those thoughts points you in the right direction.

Insert into mysql multiple input data that are created with a jquery add_function

I have the following html:
<h4>Add Steps</h4>
<ul id="pasi">
<li>
<span>Pasul 1: </span><textarea id="pas"></textarea>
<input id="add_pas" type="button" value="Add Step" onclick="add_pas()"/>
</li>
<input id="" type="button" value="Add recipe" />
and this jquery function:
function add_pas() {
var pas = "Pasul " + i;
var list = $('#pasi');
var html = "<li class='pas-"+ pas +"'><span>" + pas + "</span><textarea></textarea><img src='../images/x.png' /></li>";
list.each(function(){
$(this).append(html);
});
i++
}
The function adds a new step when the button is clicked.
SQL:
TABLE recipe_steps (id, recipe_id,sort_oder,description)
My question is how do I insert the custom number of steps into the database, and then how to retrieve it.
A first thaught was to insert all the steps into a vector(steps[]) but I don't really know where to start.
Please take in consideration that I'm a begginer in php, mysql, jquery .
Thank you and I hope I made it as clear as possible.
I don't understand how you're transitioning from js to inserting into SQL (but I may just be missing something!), but IMO you should use a jquery $.post function to call a separate .php file to do the insertion
$("#FORM_SUBMIT_ID").click(function() {
$("#ENTIRE_FORM_NAME").submit( function () {
$.post(
'SQL_INSERTION.PHP', //NOTE <-- assumes .php file is in same dir as curr file
$(this).serialize(), //This takes your form and auto separates it
function(data){
$("#ERRORS").html(data); //This will append error text to a div if you wish
}
);
return false;
});
});
Then, on your .php file you will have an array in $_POST with ALL the form values that were filled out. To test how serialize() formats your form into an array, on your php file just write
<?php print_r($_POST); ?>
I believe that should be enough. Then from there, for custom insertion, depending on how many values you have that can vary in presence, simple if/else if statements may be good enough.
i.e. if ($_POST['name']){ //code}
Alternatively, you can pass in a form "type" along with the serialized data to .php, and that will go into the $_POST array.
I came up with this that worked
function trimite(){
var pasi = {}; //initializing an array
var k=0;
$(".nimic").each(function () { //class of the <textarea>
pasi[k]=$(this).val(); //takes the value for each of the textareas created
k++;
});
$.ajax({ // sends all the textarea created to the php processing script
type:'POST',
url:"functions/add_recipe.php",
dataType:"json",
data:{
'pasi':pasi
},
success: function(data){
},
error: function(){
alert('error');
}
});
return false;
}

Categories

Resources