Send JS variable to PHP on another page without form - javascript

I have an html page with a search field that can have a name typed in which returns a table of Names and IDs (from Steam, specifically). The leftmost column, the names, are hyperlinks that I want to, when clicked, take the user to said player's profile (profile.php) and I want to send the "name" and "steamid" to that profile.php when the name link is clicked, so essentially sending two JS variables from one page to the PHP backend of another page.
I'm new to ajax and it seems that that is the only way to use it, so after researching for a while this is what I've come to:
$(document).ready(function() {
$('#playerList td').click(function(e) {
if ($(this).text() == $(this).closest('tr').children('td:first').text()) {
console.log($(this).text());
var name = $(this).text();
var steamid = $(this).closest('tr').children('td:nth-child(2)').text();
$.ajax({
url: 'profile.php',
method: 'POST',
data: {
playersSteamID : steamid,
playersName : name
},
success: function() {
console.log('success');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
})
}
});
});
Everything up to the ajax definition works as I want, and I want to send the "name" and "steamid" vars to profile.php, but I don't think I'm understanding how ajax works. My understanding is that ajax can "post" information (usually a json object from what I've seen) to a url, but can also return information from a page? That's where I'm a bit confused and am wondering if I'm just using it wrong.
As a quick note: playerList is my table's id.
When I click the hyperlink, it takes me to profile.php, which is what I want, but php's $_POST[] array seems to be empty/null as I get the "undefined array key" error when trying to access both 'playersSteamID' and 'playersName'. var_dump() returns NULL as well, so I'm wondering if there's a problem with the way the data{} field is being sent in the ajax. I'm still very new to this so any help would be much appreciated.
Update: How I'm accessing the variables in profile.php
<?php
echo var_dump($_POST['playersName']);
echo var_dump($_POST['playersSteamID']);
if (isset($_POST['playersName'])) {
console_log("PLAYER_NAME => ".$_POST['playersName']);
}
if (isset($_POST['playersSteamID'])) {
console_log("PLAYER_STEAMID => ".$_POST['playersSteamID']);
}
?>
The rest of profile.php is taking those variables and running several sql queries and building a table which work given proper variables, but since the $_POST[] is empty I can't continue past the above point as the first two lines return null and the conditionals are never true since isset() is false.

The ajax is used to, post or get parameters/info from/to URL without redirecting/refreshing/navigating to a particular page.
Please note down without redirecting/refreshing/navigating
In your case you want to send 2 parameters to profile.php and you also want to navigate to it, yes..? but for that you are using Ajax, which is not a right choice.
Solutions:-
-> Use normal form submission kinda thing, and post the parameters to profile.php, in this case you will get redirect to profile.php and can expect proper functionality.
You can use a normal form with a submit button {pretty normal}, or use a custom function to submit form with some further work if need to be done {form validation}.
you function would look like this...
$(document).ready(function() {
$('#playerList td').click(function(e) {
e.preventDefault();
if ($(this).text() == $(this).closest('tr').children('td:first').text()) {
console.log($(this).text());
var name = $(this).text();
var steamid = $(this).closest('tr').children('td:nth-child(2)').text();
//Do some other stuffs
document.forms['someform'].submit();//submitting the form here
}
});
});
The rest in profile.php remains same.
-> If you really wanna use ajax do following.
Ajax are meant for dynamic web designing, pretty useful to grab data from server without refreshing the page.
You should change the way your response is in profile.php file.
for eg:-
<?php
if(isset($_POST['playersSteamID'])){
$name = $_POST['playersName'];
$id = $_POST['playersSteamID'];
//Do your stuff here db query whatever
//Here echo out the needed html/json response.
echo "<h3>".$name."</h3>";
echo "<h4>".$playersSteamID."</h4>";
}
?>
The response {from: echo} will be available in data of function(data) in ajax success, you can use this data in whatever you want and however you want.
for eg:-
success: function(data){
console.log(data);//for debugging
$('#mydiv').html(data);//appending the response.
}
-> Use php sessions and store steamID in sesssion variable, very useful if you have some login functionality in your website.
$_SESSION['steamID'] = //the steamID here;
This variable can be used anywhere in site use by calling session_start() in the page, you want to use sessions.
for eg:-
click here to view your profile
profile.php
<?php
session_start();
$id = $_SESSION['steamID'];
//echo var_dump($_POST['playersName']);
//echo var_dump($_POST['playersSteamID']);
/*if (isset($_POST['playersName'])) {
console_log("PLAYER_NAME => ".$_POST['playersName']);
}
if (isset($_POST['playersSteamID'])) {
console_log("PLAYER_STEAMID => ".$_POST['playersSteamID']);
}*/
echo $id;
//Do your work here......
?>
For any queries comment down.

A hyperlink may be causing the page navigation, which you dont want.
Page navigation will make a get request but your endpoint is expecting a post request.
You can stop the navigation by setting the href to # or by removing the <a> altogether.
You could also try calling the preventDefault on the event object.
$(document).ready(function() {
$('#playerList td').click(function(e) {
e.preventDefault();
if ($(this).text() == $(this).closest('tr').children('td:first').text()) {
console.log($(this).text());
var name = $(this).text();
var steamid = $(this).closest('tr').children('td:nth-child(2)').text();
$.ajax({
url: 'profile.php',
method: 'POST',
data: {
playersSteamID : steamid,
playersName : name
},
success: function(data) {
console.log('success', data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
})
}
});
});

Related

How to use PHP variable in Jquery Ajax success request

I have page which shows number of routes. User click one and it sends an ajax request and save the selected route in database.
On the same page in different tab, I am running query which gets related information of the selected route. So i have Where clause in my query.
The problem is how I can feed in the ID of selected route to Where clause in my query in different tab
Here is code.
JQuery - When user click/select the route
$(document).ready(function () {
// capture the ID of clicked route
$(".collection-routeselection").click( function(){
route_id = $(this).attr("value");
jQuery.ajax({
url: '../data/collecting.php?action=route-selection?routeid='+route_id,
type: 'POST',
dataType: 'text',
data: {'routeid':route_id},
success: function(data, textStatus, jqXHR) {
$("#tab1").removeClass("active");
$("#tab2").addClass("active");
},
error: function(jqXHR, textStatus, errorThrown){
//Display error message to user
alert("An error occured when saving the data");
}
});
});
So i send the selected route using ajax to update database table.
$insert_web1 = $mysqli_scs->prepare("INSERT INTO collectiontracking_ctr (idrou_ctr,tab_ctr,created_ctr,modified_ctr) VALUES (?,'tab1',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)");
//bind paramaters
$rouid = "";
if (isset($_POST['routeid'])) {
$rouid = $_POST['routeid'];
}
$insert_web1->bind_param("i",$rouid);
$insert_web1->execute();
All working perfect so far..now I have another query on the same page (in different tab) which should have a where clause of selected route.
My question is how can i bind the selected route id to the where clause on second query.
$select_stmt = mysqli_prepare($mysqli_scs, "SELECT id_rou,idjtp_job
FROM routes_rou
WHere id_rou =?");
I want to populate ? with selected route ID.
Thanks
Assuming the value you are interested in is route_id, you should be able to store that in a variable that is accessible to tab #2 if it isn't already. Since it's on the same page this should be trivial especially since you're using jquery.
I apologize if I'm misunderstanding the question. If so please elaborate.

jQuery.ajax() just receives an error, however jQuery.post() works

Debated whether to put this on WordPress.SE or here; decided that since it's primarily a jQuery question I'd post it here with the note that it occurred during WordPress development for context.
Long story short, following a guide on how to use AJAX in WordPress to the letter—including pasting in the same code excerpts to see if they run—doesn't work on my dev server. The designated PHP function is never executed, and the call just returns a 0 when I dump the response to a an output div.
I added an error: field to the AJAX call and that triggered, but other than revealing that there was an error, I couldn't figure out what was actually at issue.
Here's a look at the AJAX call, as shown in the guide.
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "my_user_vote", post_id : post_id, nonce: nonce},
success: function(response) {
if(response.type == "success") {
jQuery("#vote_counter").html(response.vote_count)
}
else {
alert("Your vote could not be added")
}
}
})
Remembering having had this problem before, I decided to review an old project from a year ago, and found the following workaround, which seems to do the same thing, but actually returns the proper response from the script.
Functional workaround, does what is expected
var ajaxurl = '<?php bloginfo('url'); ?>/wp-admin/admin-ajax.php';
var data = {action: "my_user_vote", post_id : post_id, nonce: nonce};
// Handle any returned values
jQuery.post(ajaxurl, data, function(response) {
if(response.type == "success") {
jQuery("#vote_counter").html(response.vote_count)
}
else {
alert("Your vote could not be added")
}
});
Ostensibly, it seems that the latter is just a longwinded way of executing the former, but for some reason only the latter works. What could be causing the error on the first block?
EDIT: It seems this may be a WordPress problem after all. I've already sent the code I was working on the other night to production, so to reproduce it I put it into a plugin and tried to run it on the default theme. It's working on the front end, but it's not working when I take it to a back-end page (which is what I was working on at the time). According to the console, it appears to be an issue with enqueueing the scripts on the back end.
To mitigate that issue, I dumped the following on an otherwise blank back-end page:
This post has <div id='vote_counter'>0</div> votes<br>
<div id="output">Test</div>
<script>
jQuery(document).ready( function() {
jQuery(".user_vote").click( function() {
post_id = jQuery(this).attr("data-post_id")
nonce = jQuery(this).attr("data-nonce")
jQuery.ajax({
type : "post",
dataType : "json",
url : "<?php bloginfo('url'); ?>/wp-admin/admin-ajax.php",
data : {action: "my_user_vote", post_id : post_id, nonce: nonce},
success: function(response) {
jQuery("#output").html(response)
jQuery("#vote_counter").html(5)
},
error: function(response) {
jQuery("#output").html(response)
jQuery("#vote_counter").html(10)}
})
})
})
</script>
<?php
$link = admin_url('admin-ajax.php?action=my_user_vote');
echo '<a class="user_vote" href="' . $link . '">vote for this article</a>';
Long story short: There is no longer any external script to enqueue, the link is coded directly into it, and the count should update to 5 on success or 10 on failure (since this is a back-end page and therefore there's no page_id to check for). All extraneous data fields have been dropped, since they won't be used in this form.
To simplify generating the response, I trimmed the code back to just the following:
function my_user_vote() {
$result = array(
'status' => 'success',
'count' => 5
);
$result = json_encode($result);
echo $result;
die();
}
What now happens is we get redirected to a blank page with the JSON response dumped on it. Tried dropping in the .post() method from above and that's doing the same thing for some reason.
TL;DR: This probably needs a move to wp.se.

Use Javascript array in PHP

I know this question has been asked before several times on this forum, but I think I am missing something. Or maybe it is because I don't know JSON/AJAX that well.
Here is the thing.
I got some javascript/JQuery code on a page, say on index.php, (not yet in a seperate JS file) which let you put any number in an array from 1 to 10. If it's already in it, it will be removed if clicked again.
Now I want to pass that JS array to PHP, so I can create tables with it.
Here's what I have done.
$(".Go").click(function() {
var enc = JSON.stringify(tableChoice);
$.ajax({
method: 'POST',
url: 'calc.php',
data: {
elements: enc
},
success: function(data) {
console.log(enc);
}
});
});
And in my calc.php I got this to get the values to PHP.
<?php
$data = json_decode($_POST['elements'],true);
echo $data;
?>
Now here comes the noob question:
If I click my (.Go) button, what really happens?
Because the console.log let's me see the correct values, but how do I access it? The page (index.php) doesn't automatically go to the calc.php.
When I use a <form> tag it will take me there, but it shows this error:
Undefined index: elements
I am sure I am looking at this the wrong way, interpreting it wrong.
Can someone please help me understand what it is I should be doing to continue with the JS array in PHP.
With a XHR request you don't do a page reload. With your $.ajax method you post data to the server and receive information back. Since you can see information in your console, the success method is triggered.
You might want to take a look at your DevTools in for example Chrome. When you open your Network tab and filter on XHR you see what happens. You can inspect your XHR further by looking into the data you've send and received.
So my question to you is: what do you want to happen onSuccess()? What should happen with the data you receive from your backend?
In JavaScript:
$(".Go").click(function() {
var enc = JSON.stringify(tableChoice);
$.ajax({
method: 'POST',
url: 'calc.php',
data: {
"elements="+enc;
},
success: function(data) {
console.log(data);// You can use the value of data to anywhere.
}
});
});
In PHP:
<?php
if(isSet($_POST[elements]))
{
$data = json_decode($_POST['elements'],true);
echo $data;
}
else
{
echo "Elements not set";
}
?>

How to add checkbox info to MySQL database using Ajax?

I have a simple list populated via MySql via Ajax / Json. The list is just a title and description and every entry has a checkbox. I need the checkbox, once clicked, to push to database that it is clicked. How would you go about doing that?
[btw...
right now since I have a setTimeInterval on my SQL data to deliver the list on the fly it automatically resets my checkbox. I'm assuming that if I record that my checkbox has been set via boolean in the SQL that there could be a way to keep it checked...]
I'm new at this and I'm just playing around and trying to learn so this information is entirely theoretical.
You can use the on() function to listen to checkbox clicks.
$(function() {
$(document.body).on('click', 'input.mycheckbox', function() {
var checkbox = $(this);
var checked = checkbox.attr('checked');
$.ajax('service.url', {
type: 'post',
data: {action: 'checkbox-select', id: checkbox.attr('id'), checked: checked},
success: function(data) {
alert(data);
},
error: function(data) {
alert(data);
// Revert
checkbox.attr('checked', !checked);
}
});
}
});
Feel free to ask if you need any clarification or if this doesn't fit your situation.
EDIT:
The data parameter of the AJAX function is an object that will be posted to your PHP page. When your PHP code is running, $_POST will be an array containing the values we passed. So, $_POST['action'] will be 'checkbox-select', $_POST['id'] will get the ID, and $_POST['checked'] will be true or false depending on whether the checkbox was selected or deselected. Your method of getting the ID in the Javascript will probably change; I just put checkbox.attr('id') to give you an idea.
When learning PHP it can be helpful to dump the responses from the server on the client-side. Example PHP code:
if($_POST['action'] == 'checkbox-select']) {
$checkbox = $_POST['id'];
$checked = $_POST['checked'];
// Your MySQL code here
echo 'Updated';
}
echo 'Code ran';
I edited the JS to show the result from the server.

Auto refresh with ajax/jQuery after initial form submit then change page title

I have a form set up that, when submitted, uses an ajax call to retrieve data via a PHP file that in turn scrapes data from a given URL based on the input field value.
Everything is working perfectly, but what I'd like to do now is implement a couple of additional features.
1) After the initial form submission, I'd like it to auto-update the query at set intervals (Chosen by the end user). I'd like to append the new results above the old results if possible.
2) When new results are returned, I'd like a notification in the title of the page to inform the user (Think Facebook and their notification alert).
Current jQuery/Ajax code:
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
$.ajax({
url: 'jobSearch.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alert.fadeOut();
submit.val('Searching....'); // change submit button text
},
success: function(data) {
$('#container').css('height','auto');
alert.html(data).fadeIn(); // fade in response data
submit.val('Search!'); // reset submit button text
},
error: function(e) {
console.log(e)
}
});
});
I'm not too sure how I'd go about this, could anyone give me an insight? I'm not after somebody to complete it for me, just give me a bit of guidance on what methodology I should use.
EDIT - jobSearch.php
<?php
error_reporting(E_ALL);
include_once("simple_html_dom.php");
$sq = $_POST['sq'];
$sq = str_replace(' ','-',$sq);
if(!empty($sq)){
//use curl to get html content
$url = 'http://www.peopleperhour.com/freelance-'.$sq.'-jobs?remote=GB&onsite=GB&filter=all&sort=latest';
}else{
$url = 'http://www.peopleperhour.com/freelance-jobs?remote=GB&onsite=GB&filter=all&sort=latest';
}
$html = file_get_html($url);
$jobs = $html->find('div.job-list header aside',0);
echo $jobs . "<br/>";
foreach ($html->find('div.item-list div.item') as $div) {
echo $div . '<br />';
};
?>
Question 1:
You can wrap your current ajax code in a setInterval() which will allow you to continue to poll the jobSearch.php results. Something like:
function refreshPosts(interval) {
return setInterval(pollData, interval);
}
function pollData() {
/* Place current AJAX code here */
}
var timer = refreshPosts(3000);
This has the added benefit of being able to call timer.clearInterval() to stop auto-updating.
Appending the data instead of replacing the data is trickier. The best way, honestly, requires rewriting your screen scraper to return JSON objects rather than pure HTML. If you were to return an object like:
{
"posts": [
// Filled with strings of HTML
]
}
You now have an array that can be sorted, filtered, and indexed. This gives you the power to compare one post to another to see if it is old or fresh.
Question 2:
If you rewrote like I suggested above, than this is as easy as keeping count of the number of fresh posts and rewriting the title HTML
$('title').html(postCount + ' new job postings!');
Hope that helps!
If i understand correctly. . .
For updating, u can try to do something like this:
var refresh_rate = 2500
function refresh_data() {
// - - - do some things here - - -
setTimeout (refresh_data(),refresh_rate); // mb not really correct
}
You can read more about it here
Hope, i helped you

Categories

Resources