I've been been through numerous articles on here and tried dozens of variations including ajax. What I want to do is click a button and store the id of that button in a php variable without having to refresh the page.
I've tried using isset and POST and I get some variation of Undefined key array.
Ajax was suggested but when I use ajax I can get the variable stored, but I'm unable to get it into a php variable.
Current setup...
I have an HTML button from which I need the id stored in a php variable so I can use it in another SQL statement. This button is part of an HTML table of MySQL records returned from the db.
<input type='button' value='Edit' name='editbtn' onclick='edit(this.id)' id = '" . $row['id'] . "'/>
JavaScript...
function edit(clicked_id){
var selid = clicked_id;
var seleid = selid.toString();
$.ajax({
type: 'post',
data: {name: seleid},
datatype: 'text',
success: function(data){
console.log(name);
alert("Success, data is: " + data); // This correctly returns the id of the button clicked
},
});
}
The PHP at the top of the page is...
if(isset($_POST['name']) && !empty($_POST['name'])){
ob_clean();
$varid = $_POST['name'];
echo $varid;
exit;
}
PHP is not receiving anything. Is there a way to do this? I guess it's a backend/frontend issue?
Note: I have been able to store a JavaScript variable in an HTML tag but I've been unable to use it as part of a SQL statement, even after trimming the tags off of it.
Please help and thank you!
Try something like this in your php code :
$data = json_decode(file_get_contents('php://input'), true);
if(isset($data['name']) && !empty($data['name'])){
ob_clean();
$varid = $_POST['name'];
echo $varid;
exit;
}
Related
So basically I want to design my page in such a way that when a user leaves a comment, the page doesn't get refreshed, but the comment is sent and inserted into a database.
As such, I need to send the comment itself to the server, and I've read that the best way to do this is by using JavaScript FormData.The problem is that I can't get it to actually send something, and I want it to send to the server the data written in the type="input" element.
I previously did this by using the default way provided by the HTML form element itself: action=link method="post".
So I wanna append the id of the campaign to the url and send the comment itself to the server by using $_POST and JavaScript DataForm if possible, so it knows the campaign that should have that comment.
I can have multiple campaigns and they're all gonna be generated 'dynamically' so to say, with PHP alongside JavaScript scripts to handle their behavior, so that's why I echo'ed all of that.
<form id="commentForm' . $row['id'] . '" name="commentForm" method="post" class="greyContainerAllCampaigns">
<input id="comment' . $row['id'] . '" name="CommentContent" max="250" title="max 250 alphanumeric and ,.?: etc chars" required pattern='.' \'[A-Za-z0-9 .,!?:\[\]()"-+]+\' ' .'class="inputBox" type="text" placeholder="write here">
<button id="commentB' . $row['id'] . '" class="submitButton" type="submit" name="Comment">Comment</button></form>';
That's the JavaScript script I tried to write in order to do that:
document.getElementById("commentB' . $row['id'] . '").addEventListener("click", commentFunction);
function commentFunction() {
fetch(\'http://localhost:80/proiect/GaSM/public/Campaign/comment/'. $row['id'] . '\', {
method: \'POST\',
body : new FormData(document.getElementById("commentForm' . $row['id'] . '")),
headers: {\'Content-Type\':\'multipart/form-data\'}
});
alert ("You left a comment!");
}
</script>';
I tried to get the result on the server with $_POST['CommentContent'] but I get nothing, nothing ever gets sent.
I'm obviously doing something wrong with the way I try to send it via POST to the server in the JavaScript script but I don't know what.
Thanks in advance!
how about you give the form a class and in javascript add an event to this form whenever it is submitted to make an Ajax request to the form action with the data of thr e form serialized.
$(“.form”).on(“submit”, function(e) {
$form = $(this);
$.ajax({
url: $form.attr(“action”),
type: “post”,
data: $form.serialize(),
success: function(res) {
alert(“success”);
},
error: function(error) {
alert(“error”);
}
});
e.preventDefault();
return false;
});
First, give your form element a normal id. Not sure what youre trying to do now, but if you want to use PHP to render it, use echo between PHP opening and closing tags: id="<?php echo 'commentForm' . $row['id']?>". As it is now, I suspect your Javascript is always looking for a form with the literal string 'commentForm' . $row['id']'. row['id'] is not considered a variable.
Next, the syntax of this fetch function looks completely invalid. FormData works nicely with XMLHttpRequest, which I believe is what you're looking for.
For example:
<?php
<script>
let xhr = new XMLHttpRequest();
// Your logic for handling the response of the server
xhr.onreadystatechange = function() {
if (4 !== this.readyState) {
// not yet ready
return;
}
if (200 !== this.status) {
//handle error response
return;
}
// Handle something good...
}
xhr.open('POST', 'https://my.page/comment/' + <?php echo $row['id'] ?>);
xhr.send(new FormData(document.getElementById('myForm')));
</script>
?>
I've got a piece of javascript as follows:
$.ajax({
type:"get",
url:"http://www.orc23.com/get.php",
data: { solution: src },
datatype: "json",
success: function(returndata){
alert(returndata);
}
});
And this is the corresponding php file that interacts with mysql:
<?php
$con = mysqli_connect("orc23com.fwdsfawmsdfaysql.com","ssft","dsfss123","cookies");
if (!$con)
{
die('Could not connect: ' . mysqli_connect_error());
}
mysqli_select_db($con, "cookies");
$sql="SELECT SOLUTION FROM requests WHERE theurl = '$_GET[solution]')";
$result=mysqli_query($con,$sql);
$num_rows=mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
$returndata=json_encode($row);
echo $returndata;
mysqli_close($con)
?>
The variable "src" I am passing in is a URL (string) , so I believe I should be treating it in a different way b/c of the nature of an URL with all its' special characters ,,,, I am running my code and it errors out as a "null" , but when I run the appropriate sql statement query in mysql DB then the DB returns what I am expecting ..... please advise what I may be doing wrong please ?
the sql I am running is this:
SELECT solution
FROM requests
WHERE theurl = 'https://www.google.com/fskdfalkadsl?=sksdkalsk&soccer=uwiw'
;
I know it will return back to me single row with just one column , and know what to expect as the value , but I can't seem to get the "get.php" page to return anything but "null" it seems ....
You get NULL because PHP does not automatically populate the $_GET when it receives JSON formatted data, so there is nothing in $_GET['solution']. You need to capture and decode the input yourself.
Instead of:
$solution = $_GET['solution'];
You need
$data = json_decode(file_get_contents('php://input'), true);
$solution = $data['solution'];
Or something close to it.
I wanted to use HTML links to change a session variable in PHP. To do this, I set up an HTML "a" tag that would call a javascript function that looks like this:
function changeValue(name){
data = "key='person'&value=" + _name;
$.ajax({
url: www_root + "/funcs.php?func=set_session_var",
type: "post",
data: data,
success: function(data){
console.log(data);
}
});
}
Then, I had the funcs.php script which had the set_session_var function like this:
function set_session_var(){
session_start();
$key= trim($_GET["key"]);
$value= trim($_GET["value"]);
$_SESSION[$key] = $value;
session_write_close();
echo $key;
}
Then, the original php/html page would reload, but it would first load an external page (call it item.php) that settled all of the php session stuff. Looks like this:
session_start()
$session_id = session_id();
$sc = $_SESSION['person'];
However, the $sc variable always shows up as empty, despite the AJAX success function returning the right value. I've checked the session_id's for both scripts, and they are the same. I have also tried to set a session variable in item.php, and it persists. It's just that when I set a session variable using the funcs.php script it doesn't save.
Any and all ideas are appreciated!
You're sending quotes:
data = "key='person'&value=" + _name;
^------^
which means you're effectively doing:
$_SESSION["'person'"] = $value;
^------^-
Note that those single quotes have become PART of the session key name.
Try
data = "key=person&value=" + _name;
^----^--- no quotes
instead.
Ok I know this can't be done using PHP and I think it's done by using Ajax/Javascript...
Unfortunately I'm very low on these and I need your help..
So I have made a <select> based on what players there are playing for the team the user has selected. It works fine, no problems.
What I need for it is a button that will add 1 XP to the player that the user has selected.
<?php
$query = mysql_query("SELECT `team` FROM `users` WHERE `username`='". $_SESSION['username'] ."'");
$row2 = mysql_fetch_assoc($query);
$result = mysql_query("SELECT `name` FROM `players` WHERE `team`='". $row2['team'] ."'");
$dropdown = "<select name='players'>";
while($row = mysql_fetch_assoc($result)) {
$dropdown .= "\r\n<option value='{$row['name']}'>{$row['name']}</option>";
}
$dropdown .= "\r\n</select>";
echo $dropdown;
?>
<button onclick="">Support</button>
In my case, the update would look something like this:
$oldxp = mysql_query("SELECT `xp` FROM `players` WHERE `name`="the option the user selected,got stuck here");
mysql_query("UPDATE `players`SET `xp`=''". $oldxp ."' + 1' WHERE `name` = "the option the user selected, got stuck here");
So what I need is how do I get what the user has selected and replace it with that "the option user selected, got stuck here" and how do I do this in Java since I can't put that PHP code in the onclick event because it won't work?
Thanks a lot.
Change your button html
-- add a onclick function
html:
<button onclick="saveData()">Support</button>
onclick in the button send an ajax request to the server and run your query.
jquery:
function saveData(){
$.ajax({
type: "POST",
url: "your_php_page.php",
data: { name: $("select[name='players']").val()},
success:function( msg ) {
alert( "Data Saved: " + msg );
}
});
}
php:
your_php_page.php:
$sql = "UPDATE `players`SET `xp`= `xp`+ 1 WHERE `name` = '".$_REQUEST['name']."'";
if(mysql_query($sql)){
return "success!";
}
else {
return "failed!";
}
you should not use mysql_* since it is deprecated. you should use pdo or mysqli_*
jquery ajax api doc
First off, Java and Javascript are totally different languages. They share very little except a name and their both a programming language.
You'd need to use Ajax to do this, so you'd need a PHP file on your server that the AJAX can request to run the query you're wanting. You would then use AJAX to request this file to add the XP, I suggest you use jQuery (http://jquery.com/) for AJAX calls as its much easier to use than pure javascript.
Once you have included jQuery into your site you can use the following to make an ajax call:
$.ajax({
type: 'post',
url: 'http://domain.com/myscript.php',
success: function(data){
// callback function
}
});
Documentation: https://api.jquery.com/jQuery.ajax/
You could wrap the ajax call in a function and then call that function using onclick on the button you're wanting to use.
eg:
<button onclick='javascript:ajaxCall()'>Call AJAX</button>
function ajaxCall(){
// include code above
return false; // not always essential, but I usually return false.
}
I have a little contact form, where I would like to ask the user to calculate and enter the correct value in order to prevent spam. Now, when the send button is clicked, I fire a php script, where I change the calculation values. I would like to echo these values and show them as the new placeholder in case of both, success, as well as failure.
$("#send_button").click(function() {
var url = "contact.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#contact_form").serialize(), // serializes the form's elements.
success: function(data)
{
var txt = "<?php echo 'Spam protection: Calculate ($first_num + $second_num) x $multiplier';?>";
$("#form_info_label").css('color','#0ed68d');
$("#form_info_label").text(data);
$("#user_answer").attr("placeholder",txt);
},
error: function(data) {
var txt = "<?php echo 'Spam protection: Calculate ($first_num + $second_num) x $multiplier';?>";
alert(txt);
$("#form_info_label").css('color','#f2275e');
$("#form_info_label").text("Error. Please try again.");
$("#user_answer").removeAttr('value');
$("#user_answer").attr("placeholder",txt);
}
});
return false; // avoid to execute the actual submit of the form.
});
However my placeholder ends up not interpreting it as php code, but just simply copies the text. So my placeholder then ends up displaying:
<?php echo 'Spam protection: Calculate ($first_num + $second_num) x $multiplier';?>
I ended up returning a json-encoded array with my desired values from php back to javascript and parsed the response there.
You'll need PHP tags
var txt = "<?php echo 'Spam protection: Calculate ($first_num + $second_num) x $multiplier'; ?>";
You actually have it right in the error handler, so you probably just forgot, and now you've edited the question to include them ?
If you have PHP tags, and it's still not being parsed, the file the javascript is in is not being parsed by PHP.
Remember on comuputers to use the * for multiply things, not the x.
And it´s also not clear, what your function "Calculate($param)" does, but usally you don´t need a function for adding one variable to another. But the brackets still needed...
In my case the PHP tag was not interpreted by js either. A solution I found was:
In my php file I defined the variable in a non-visible div:
?>
<div id="first_num" style="display: none">
<?php echo $first_num; ?>
</div>
<?php
In the jquery file I read the div value like this:
var first_num= $("#first_num").text().trim();
First of all what adeneo already said: .js files are not parsed by PHP.
Secondly PHP variables will not be expanded when they occur in single quoted strings. http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.single
You should use either double quotes or
echo 'Spam protection: Calculate ('.$first_num.' + '.$second_num.') x '.$multiplier;