Using ajax to get javascript value in another page - javascript

I have a button that counts clicks and i want that final value to get stored in my database but I'm having a hard time getting that value.
I have one page where i have the counter and i tried using ajax to get it to the other page, here's the code.
var clicks = 0;
function hello(){
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
}
$.ajax({
url: 'conta.php',
data: {'score' : clicks},
type: 'POST'
});
And in conta.php:
echo $_POST['score'];
The problem is when the timer runs out and it goes to conta.php there is an Undefined index: score error.
Would really welcome suggestions if possible.

$_POST['score'] is the value you posted to the URL in the response to that POST request.
If you want to get the data in a different request then you'll need to store it somewhere (such as a database) and then read it from wherever you stored it when you get the request that you want to use to display it.

Related

How to refresh a specific part of the HTML Document with Vanilla JavaScript

I am working on an AJAX cart system where the sub total will automatically update when the quantity changes. My solution is every time the input changes, post it to the current page (cart page) then reload the div that displays the sub total. However, I don't know how to do this with pure JavaScript, and I haven't found any reference yet.
This is my function for the above algorithm:
var _rangeInput = document.querySelectorAll('.ranum'), _upAload = document.getElementsByClassName('upAload');
var _frmData = {};
for (var i = 0; i < _rangeInput.length; i ++) {
_rangeInput[i].addEventListener('change', function(){
_frmData[this.name] = this.value;
ajaxFormValidate({
type: 'POST',
url: location.href,
method: true,
sendItem: _frmData,
success: function(response) {
//reload here
}
});
}, false);
}
Code explaination:
First, get the inputs and divs that need to be processed.
Loop through all of the inputs and get their values and names.
I have written an AJAX function for my self, you can look above.
Is there anyway to do this with pure JavaScript?
I can't use JavaScript methods or functions to change the content since I am sending the request to the same page, as a result, response here will have the value of the whole document.
Also, this is how the system works:
First, the user changes the quantity they want
AJAX sends request to the same page
The page changes the information based on the request
AJAX receives the request, and refreshes/reloads the specific div
Simply set the innerHTML of your sub total div with the response data.
document.getElementById("sub-total").innerHTML = response.value; //Whatever value you get in response
It sounds like you're actually asking how to get a single element out of an AJAX response.
You can do that by parsing the response into a temporary element, then finding the element you need within it:
const holder = document.createElement('div');
holder.innerHTML = response;
const myElement = holder.querySelector('some selector');

How do I sync an AJAX call to a php file with posting data through a form to the same file?

My problem is update.php only gets the posted form data (post_edit). The variables posted earlier through AJAX don't go through
Notice: Undefined index: id_to_edit in ...\update.php on line 5
Notice: Undefined index: column_to_edit in ...\update.php on line 6
What I'm trying to do:
I have a callback function that traces the mouse's position on the table's body. This is done to detect the column and the id of the cell that the user wants to edit - id integer and column string are posted to a php file through AJAX and used in an SQL query using both values (for coordinates) on top of the data the user wants to update (posted through a form, more on this later).
Editing is done this way: when a user mouses over a cell a form is created inside, and filling in that form should post the data to update the corresponding entry in the SQL table (which is found by using the coordinates from the callback function). Mousing out removes the form.
To paraphrase a bit
How do I post the coordinates and the form data to a php file so that all these values can be used in an SQL query? If what I've been doing is fundamentally broken, is there another way?
$(function(){
$("td")
.hoverIntent(
function(e){
var id_of_edit = $(e.target).siblings('th').text();
var $clicked_column_i = $(e.target).index() + 1;
var column_of_edit = $("#tableheader").children("th:nth-child(" + $clicked_column_i + ")").text();
$.ajax({
type: 'POST',
dataType: 'text',
url: 'update.php',
data: {
'id_of_edit': id_of_edit,
'column_of_edit': column_of_edit
},
});
var $edit_button = $('<form action="update.php" method="post"><input type="text" name="post_edit"/></form>');
$(e.target).append($edit_button);
console.log(e.target.innerText + " was clicked");
console.log(id_of_edit + " is the ID");
console.log(column_of_edit + " is the column name");
//just to check the tracer function is working correctly
},
function(e){
$id_of_edit = $(e.target).siblings('th').text();
$clicked_column_i = $(e.target).index() + 1;
$column_of_edit = $("#tableheader").children("th:nth-child(" + $clicked_column_i + ")").text();
$(e.target).children('form').remove();
});
});
update.php:
<?php
include 'config.php';
echo $_POST['id_to_edit'];
echo $_POST['column_to_edit'];
echo $_POST['post_edit'];
$stmt = $pdo->prepare('UPDATE food SET :column = :edit WHERE id = :id');
$stmt->execute([
'id' => $_POST['id_to_edit'],
'column' => $_POST['column_to_edit'],
'edit' => $_POST['post_edit']
]);
?>
An ajax request and a form submission via standard postback are two separate HTTP requests. Your "update.php" script will execute twice - once for each separate request, and each request will have separate sets of POST variables, according to what you sent on that request. The variables do not persist between requests - just because you sent them to the same endpoint script does not matter.
To summarise: HTTP requests are stateless - they exist in isolation and any given request knows nothing about previous or future requests. Each one causes the named PHP script to run from start to finish, as if it had never run before, and might never run again. It remembers nothing about the past, and knows nothing about the future, unless you do something about it explicitly.
If you want values to persist between requests you have to store them yourself - in a DB, Session, cookies, whatever (it's up to you) - and then retrieve them later when you need them.
Having said that, looking at your server code it's not clear why you would want two separate requests anyway - you are doing a single UPDATE statement in the SQL, so it would make more sense to use one HTTP request to transmit all the data to the server, and then execute the script which runs the UPDATE. Unless there's some reason in the UI why this can't be done, in which case then you need to persist the values somewhere in between requests. From your description, you could potentially capture the cell/column ID into a hidden field inside the form you generate, rather than sending them immediately to the server via ajax. The hidden field values would then be posted to the server together with the user-generated values when the main form is submitted.
Also, if you really are using the mouse's position to determine the cell, this sounds very unreliable - browser windows can be resized to anything. Surely putting an ID inside the HTML markup of the cell (e.g. as a data- attribute) which you can then read when the cell is clicked / moused-over would be much more reliable?

Updating total number on website with jQuery / Javascript?

This below is displaying Total racers on my website but its not updating live. I need to referesh the page to grab the new number from the database, so what's the simple way of updating it live with jquery/javascript without refreshing the page? Thanks a lot for taking the time to check my question and possibly answer.
<div id="stats">
<div id="racers">
<span><?=number_format($racers, 0, ' ', ' ')?></span>
RACERS
</div>
</div>
Jquery Ajax:
$.post('page.php', {
postVariable : value
}, function(data) {
//do something with data retrieved from php script
});
You set 'page.php' to a script that gets the data you want and echoes it.
You then retrieve what was echoed in the callback function(data);
So data will be the variable containing the value you need. You put this script in a
javascript function and call it when you need to make a request for information on the back-end.
If you have questions let me know. If you need more information on the ajax request you can find it here as well: api.jquery.com/jquery.post/
What you need to do this is the following:
1. Have an action in a controller that outputs the total number of racers
For example:
class Data extends CI_Controller {
public function GetTotalRacers() {
// This is dummy data. You need to replace this code with the correct
// number of racers retrieved from the database
echo 14;
}
}
Take note of where this action is. I'm assuming codeigniter will make the path something like /Data/GetTotalRacers in this case (that depends on how your route rules are configured).
2. Use JavaScript to ask the server for the data and display the result on the page
I recommend you have a method that runs every X number of seconds to refresh the total number of racers. To achieve this, you can use setInterval. Within the setInterval's function have an ajax call to your action. Finally, display the value that's returned from the server:
setInterval(function() {
$.ajax({
// Replace the url value with the correct url to access your action
url: '/Data/GetTotalRacers',
cache: false
})
.done(function( totalRacers ) {
$("#racers span").text(totalRacers);
});
}, 60000); // ex. Update every 60000ms
Note: I've never used codeigniter, but hopefully this description will help set you on the right path.

Return result to a PHP variable from AJAX in a jQuery function

So this is the hardest thing I've ever tried to do, I cannot find any answers after 1 day of searching. Note that I am using some custom jQuery API and will explain what it does.
The setup is a php page that contains a jQuery function. That jQuery function calls the API to return a result based on a row I clicked (it is jQgrid, basically looks like an online excel sheet). That works fine, but the objective is to get that result OUT of the jQuery function and store it in a PHP variable. I am just clueless......
Main PHP Page:
$getUnitID = <<<getUnitID //This is the jQuery function. It is stored in a php variable for use in other functions of the API
function(rowid, selected)
{
var selr= null;
if(rowid != null){
selr = jQuery('#grid').jqGrid('getGridParam','selrow'); //This will give ma a number result based on the row I selected. Works fine.
$.ajax({ // I believe I need to use AJAX so here is my attempt
type: "POST",
url: "getId.php", //This is another PHP page for the reuslt. See below
dataType: "json",
data: {selr:selr},
success: function(data) {
alert (data); // This will successfully show me the row number I chose as an alert. But I don't want an alert, I want it stored as a php variable in my main document to use elsewhere.
}
});
}
}
getUnitID; //End of the function
$grid->setGridEvent('onSelectRow',$getUnitID); //Just an event that calls the function upon clicking the row
$rowResult = ??????? //I need this variable to store the result of that AJAX call or that function call
getId.php
<?php
$rId = $_POST["selr"];
echo $rId;
?>
Essentially, I have no idea why I am using AJAX, because my result is still stuck inside the main jQuery function. How in God's name do I get it OUTSIDE that function?!?!?!?!?!?!?! Do I need to $_GET the 'selr' that I POSTed to getId.php ? If so, how?
Thank you, I love you all.
By the time you get that AJAX request sent out and response received, PHP has already gone to sleep. You cant give the data back to your same page's PHP code. Your jQuery starts executing on client computer long after PHP has already finished its work on your server.
It doesn't matter whether your JavaScript function is stored in a PHP variable. PHP will not get its output back. Only way you can do so is to launch another new request to that code and send value to it. but on the same very request on the same very page, its a no no.
Example of how you can send that data to another PHP page
//Your existing jQuery
success: function(data) {
// alert (data);
var result=data;
$.ajax({
type: "POST",
url: "anotherpage.php",
data: { data: result }
});
}

AJAX and a global variable not working, have I got this wrong?

what I am trying to achieve is to AJAX a load of client's data into a page (this works), I then have a company ID in one of the fields brought in. I need to cross check this with a different company table (same database) to replace the company ID on the page with the name instead.
To get this I have set a global javascript variable to blank then fired off the main AJAX request getting all the initial client data then within that parsing loop (client side) I need to fire off a function which will check against the companies table to get the name. My current problem is that the global variable is not being set to the 2nd AJAX result. Here is my code:
var nameresult = "";
function namecheck(id){
var request = new Ajax().sendRequest
('../company_check.php',
{ method: 'GET',
parameters: 'id=' + id,
callback: namecheckReceived }
);
}
function namecheckReceived(xmlHTTP){
var n_data = JSON.parse(xmlHTTP.responseText);
nameresult = n_data[0].name;
}
function client_call(){
var request = new Ajax().sendRequest
('../client_data.php',
{ method: 'GET',
callback: searchReceived }
);
}
function searchReceived(xmlHTTP){
var data = JSON.parse(xmlHTTP.responseText);
for(var i=0; i<data.length; i++)
{
namecheck(data[i].company_id);
/////spit out all the data in a readable format //////
}
}
Notes:
Only one result will be received from the company_check.php hence no
loop in the namecheckRecieved() function.
No errors in the JS console.
The nameresult variable stays as blank and is never
changed, if I alert(nameresult) within the namecheckRecieved()
function it spits out what I want so why is it not changing the
global variable with each loop of the searchRecieved() function?
I'm going to delete all my previous comment and say that you only need one ajax call. And everything should be done on server side. That means get the company Id, and use that to get the name of the company then pass everything back to the client side. From the look of it you are doing A LOT of call backs to the server to get every company name when you could have just done that on your first visit to the server. This way you do not need to worry about doing two ajax call Although from the look of it your doing more than 2 calls, depending on the length of data
Try this
function namecheckReceived(xmlHTTP){
var n_data = JSON.parse(xmlHTTP.responseText);
nameresult = n_data[0].name;
client_call();
}

Categories