$_GET randomly gets unset in if statement - php

I'm sure there is a simple answer to this stupid problem but I have searched high and low and can not figure out why this wont work.
$tutorid = $_GET['userid'];
var_dump($tutorid);
//populate user tutoring subjects
if( isset($_POST['a'])) {
$currentsubjects = get_current_user_subjects( $tutorid );
unset($_POST['a']);
echo json_encode($currentsubjects); return;
}
I have a simple AJAX function that sets $_POST['a'] equal to something. The var_dump($tutorid) properly displays the id from the url. However the $tutorid in the get_current_user_subjects is sending NULL.
If I try a var_dump like this to check $tutorid
$tutorid = $_GET['userid'];
//populate user tutoring subjects
if( isset($_POST['a'])) {
echo json_encode($tutorid); return;
// $currentsubjects = get_current_user_subjects( $tutorid );
// unset($_POST['a']);
// echo json_encode($currentsubjects); return;
}
Then I get NULL. If I hard code in a tutorid in the get_current_user_subjects( $tutorid ) (like add in 15 or something) the function returns data to console.log like expected but using the variable $tutorid stops it completely. I can't figure out why this is happening! Someone please enlighten me.
Here is the AJAX just incase. It works find on other pages so I am assuming the issue is with $_GET
$.ajax({
url: 'profile.php',
method: 'post',
data: "a=true",
dataType: 'json',
success: function (x) {
console.log(x);
},
error: function(a, b, c) {
console.log(a);
console.log(b);
console.log(c);
}

Maybe you can use this method. So you can POST the userid
$.ajax({
url: 'profile.php',
method: 'post',
data: {a: a, userid:userid},
dataType: 'json',
success: function (x) {
console.log(x);
},
error: function(a, b, c) {
console.log(a);
console.log(b);
console.log(c);
}
So in your form before the action. you can set userid in hidden form
<input type="hidden" name="userid" value="<?php echo $userid;?>" />

Save the userId to the session and take it from there. Or pass the userId with the ajax request. I dont think the logic is right in your code, as bsed on the info you have provided. Trying to take the id from $_GET in the requested page while your ajax method is post and no userId is passed with the request, is not right. From my knowledge, you wont have data in the $_GET array if the request to that page is not 'get'. Session provides InterPageCommunication. use session.

Related

Posting data from ajax to php

Trying to send a post request from ajax to php.
I did many trial and errors based from the answers including making sure that the "type" is set to post, specifying "dataType", correct "url". I think I miss something important but I can't figure out what it is.
main.php
<script>
$(document).ready(function(){
$(".editContact").on("click", function(){
let dataID = $(this).attr("data-id");
console.log(dataID);
$.ajax({
type: 'POST',
url: 'functions/phonebook.php',
dataType: "text",
data:{data:dataID}
});
});
});
</script>
functions/phonebook.php
if(isset($_POST["data"])){
$res = array($data=>var_dump($_POST["data"]));
}
else{
$res ='null';
}
Then print the $res variable containing the dataID from ajax to my html element in main.php
<label class="m-label-floating">Contact name <?php echo $res; ?> </label>
The console.log in my main.php prints the data what I want to send in ajax but when I try to send the dataID to my phonebook.php, I get a null value.
Your problem is here:
$res = array($data=>var_dump($_POST["data"]));
You are using var_dump the wrong way.
From the docs:
This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.
This function does not return any value, so, in your case, $data=>var_dump($_POST["data"]) will always be null.
What you need to is:
$res = array($data => $_POST["data"]);
If you are sending data to a different page altogether and need to use jquery / JS to do it, it might be simpler to send via window replace:
window.location.replace(...)
If you need to stay on the same page, you might want to include a success function in your ajax query, as this will return to the page you are calling from:
$.ajax({
type: 'POST',
url: 'functions/phonebook.php',
data:{data:dataID},
success: function (html) {
// do your HTML replace / add stuff here
},
});

Increment MySQL value on click with +1

What I have
An url like this: http://localhost:8888/website/?key=ABC
A MySQL table with many rows, one with a key called ABC. I have a button that I want users to click (upvote) the MySQL row corresponding to key=ABC.
In my scripts.js I have this (incomplete?) Ajax code:
function increment() {
$.ajax({
type: 'POST',
url: '../js/ajax.php',
success: function(data) {
alert("function saved: " + data);
}
});
}
And my ajax.php looks like this:
<?php
if (isset($_GET['key']) {
$rowKEYtest = $_GET['key'];
$sql2 = "UPDATE database SET Score = Score + 1 WHERE UniqueKey = '$rowKEYtest'";
$conn->query($sql2);
} else {
echo "lol";
}
?>
It's not updating. I have no idea what to do.
Please have a look in your code, There is 2 mistakes.
1. In your ajax call you are using type: 'POST', you should use GET.
2. You are nor parsing your 'key' param in ajax call.
Actually you are using POST method in ajax but in ajax.php trying to get the value with GET method. second thing you are not passing any param in ajax call.
Hope this will help.

ajax POST not working, can't figure why

I have a simple AJAX function to send an id of an object to a php page
My function looks like this:
$(function(){
$("a.vote").click(function(){
//get the id
the_id = $(this).attr('id');
alert(the_id);
//ajax post
$.ajax({
type: "POST",
data: "?id="+the_id,
url: "vote.php",
success: function(msg)
{
$("span#message"+the_id).html(msg);
}
});
});
});
My vote.php looks like this:
session_start();
if(isset($_SESSION['user'])) {
// db setup removed
// insert vote into db
$q = "UPDATE votes SET vote = vote + 1 WHERE id = " . $_POST['id'];
mysql_query($q);
echo "You sent " . $_POST['id'];
}
When I execute my AJAX function, it appears that the vote.php is never run
I know that my AJAX function is being called correctly, because alert(the_id); is popping up with the correct ID.
I know my vote.php is functioning correctly because I can run an HTML method="post" with a textbox named "id", and it will update the database correctly.
Can anyone see what's wrong?
Thank you
You're trying to send your variables in the URL, not as POST variables. Should be something like:
$(function(){
$("a.vote").click(function(){
//get the id
var the_id = $(this).attr('id');
alert(the_id);
//ajax post
$.ajax({
type: "POST",
data: {id:the_id},
url: "vote.php",
success: function(msg)
{
$("span#message"+the_id).html(msg);
}
});
});
});
Your data should be as included as an object, not as a string URL. Check out the examples on the jquery API page for more info on this!
The principal thing I see in your code that doesn't look right is data: "?id="+the_id,. The ? is unnecessary, and illogical for a post request. Do the following instead:
data: {
id: the_id
}
This lets jQuery do the URL-encoding for you.
As an additional point, you do $(this).attr(id). This is very inefficient. Do this.id instead, for exactly the same effect hundreds of times quicker at least 20 times quicker.
Your data value shouldn't need a question mark at the beginning.

Ajax post return value

Im using Ajax to send values to a PHP script which writes some value to a database:
$.ajax({
type: "POST",
data: "action=vote_down&id="+$(this).attr("id"),
url: "vote.php",
success: function(msg) {
$("span#votes_count"+the_id).fadeOut();
$("span#votes_count"+the_id).html(msg);
$("span#votes_count"+the_id).fadeIn();
}
});
As you can probably tell from the action=vote_down the script is for a voting script.
Im already preventing the user from voting more than once by logging there vote against there username and ID in vote.php and if there username and ID is already in the DB against the same post then I dont add the vote to the DB.
I personally think that querying the database on each page load to check if the user has already voted could be quite intensive, there are many places to vote on a single page.
So instead i'll show the user the voting option, but when they vote I want to some how return a value from vote.php to say they have already voted.
Any ideas for the best approach to this?
Use JSON
If this is your file to show the voting form:
<div id='voteform-div'>
<form id='voteform'>
Your form elements and a submit button here.
</form>
</div>
Your JS code look like this:
jQuery('#voteform').live('submit',function(event) {
$.ajax({
url: 'vote.php',
type: 'POST',
data: "action=vote_down&id="+$(this).attr("id"),
dataType: 'json',
success: function( messages) {
for(var id in messages) {
jQuery('#' + id).html(messages[id]);
}
}
});
return false;
});
your vote.php should be something like this:
// Get data from $_POST array.
if( Already voted ) {
// It will replace the id='voteform-div' DIV with error message
$arr = array ( "voteform-div" => "you have already voted." );
} else {
// Store vote in database
// It will replace the id='voteform-div' DIV with confirmation message
$arr = array ( "voteform-div" => "Yor vote is submitted. Thanks" );
}
echo json_encode( $arr ); // encode array to json format
For more detail on this look at this question.
This should put you in the right direction...
http://forum.jquery.com/topic/jquery-ajax-and-php-variables
I would parse back a boolean false if they have posted already, or the id of the vote if they were successful (for styling / adding the html message).

JQuery to PHP function and back Ajaxed

i have a set of php function that i want to call on different events mostly onclick with jquery async (ajax).
The first function is called on load
$(document).ready(function()
{
$("#div2").hide('slow');
$("#div1").empty().html('<img src="ajax-loader.gif" />');
$.ajax(
{
type: "POST",
url: "WebFunctions.php",
data: {'func':'1'},
success: function(html)
{
$("#div1").show('slow').html(html)
}
});
The Data: {'func':'1'} --> is a switch statement on the php side
switch($_POST['func'])
{
case '1':
getParents();
break;
case '2':
getChilds(params);
break;
case '3':
getChildObjects(params);
break;
default:
}
"This functions are calls to a soap server" <-- irrelevant.
So when that function finishes i get an array which contains IDs and Names. I echo the names but i want the ID for reference so when i click on the echoed name i can call an other php function with parameter the ID of the name...
How do i get rid of the switch statement?? How do i call properly php functions and pass params to it??? How can i save this IDs so when i click on an item with that id an other php function is called??
Plz feel free to ask any question, any answer is welcome :)
``````````````````````````````EDIT``````````````````````````````````````````
$(document).ready(function()
{
$("#div2").hide('slow');
$("#div1").empty().html('<img src="ajax-loader.gif" />');
$.ajax(
{
type: 'post',
async: true,
url: "Parents.php",
data: {'id' : 12200},
dataType: "json",
cache: false,
success: function(json_data)
{
$("#div1").empty();
$.each(json_data, function(key, value)
{
$("#div1").append('<p class="node"><b>['+key+']</b> => '+value+'</p>');
$(this).data('id', key);
});
}
});
$("p.node").click(function()
{
var id = $(this).data('id');
alert('The ID is: ' + id);
});
});
I got json communication working but my problem is the data stuff,
when i click on a node the id is undefined... it gets printed but when i click on it oupsss.. so the problem is how can i properly attach the ID to each corresponding .. .
You can avoid the switch statement by using an MVC framework that routes your request to the proper function. For example, using CodeIgniter REST Server, you might have the following URL's to your functions:
http://myserver/my_api/parents
http://myserver/my_api/children
http://myserver/my_api/childObjects
You can then POST the parameters along with each AJAX request.
You would probably also want to return the ID you pass as part of the response, so it will be available when you make a request for the next function.
One solution for managing your ID's would be to encode your data as JSON. This will allow you to pass the whole PHP array to Javascript, and have it natively understand and read the ID's and Names.
To encode your PHP array as JSON, try this:
echo json_encode($my_array);
(You'll need PHP 5.2+ for this to work)
This will print out JSON data when the page is requested. Next, in your JavaScript add a "dataType" argument to your Ajax function call. Something like this:
// Get JSON Data and Save
$.ajax({
type: "POST",
url: "WebFunctions.php",
data: {'func':'1'},
dataType: "json",
success: function(json_data) {
$("#div1").data(json_data);
}
});
// Display the ID when clicked
$("#div1").click(function(){
var id = $(this).data('id');
alert('The ID is: ' + id);
});
This tells the Ajax function to expect JSON back.
When the success function is called you can access the "json_data" variable and find all the ID's and Names just as you had them in PHP. You'd then need to write some code to appropriately save those ID's and Names. They can then be used later on (ie. when you click on the button etc).
EDIT: I've updated the code above. The JSON data is now associated with the HTML element "#div1", so you can refer back to it in the future. I've also added a simple click event. Whenever the element is clicked, it's ID will be displayed.

Categories