Trouble posting variable from JS to PHP - javascript

I am trying to send a JS a variable to a php file. It is not happening. And there are many questions answered out there on similar situation. I probably am making some similar mistake. Though, I am not able make out what it is.
The Codes are as follows;
main.php
<script type="text/javascript"> var socialurl= "<?php echo $url;?>";</script>
JS
jQuery(function(){
alert('socialurl');
$("#smshare").click(function(){
$("#smp").slideToggle("fast");
$.post("social-media-share.php", {socialurl: socialurl });
$("#smp").load("social-media-share.php");
});
});
social-media-share.php;
<?php
$socialurl=$_POST['socialurl']
echo $socialurl."<br>";
include('conn.php');
$socialurl = $conn->real_escape_string(trim($_POST['socialurl']));
?>
<img src='images/share.png' width="30" height="30" alt='WhatsApp Share'>
The file social-media-share.php is called into the main.php with JS. Prior to which the JS variable socialurl is defined in the main.php
The variable value pops up in alert in the JS but it is not getting posted to social-media-share.php
I am sure I must be making some silly mistake. But for the life of me am not able to find out what.
Any help will be greatly appreciated.

I think the problem is you're posting to the page, but then loading it again via a GET request and so you're not loading the results of the post request itself.So unless the GET on social-media-share.php is displaying a database result I'm not sure you're actually loading what you want.
jQuery(function(){
alert('socialurl');
$("#smshare").click(function(){
$("#smp").slideToggle("fast");
$.post("social-media-share.php", {socialurl: socialurl });
$("#smp").load("social-media-share.php");
});
});
This bottom line is doing the wrong thing. $("#smp").load("social-media-share.php");
you actually want a callback function in you .post that loads the response from that
http://api.jquery.com/jQuery.post/
$.post( "social-media-share.php", {socialurl: socialurl })
.done(function( data ) {
//you might need to do some other stuff to data here
$("#smp").html(data);
});
Alternatively you might have an error in your social-media-share.php script so you could try doing a var_dump($_POST); to see what variables are actually being posted

Related

Google reCaptcha v3 returns success as false

I am testing my user login/registration system. I finally finished the form and I have been testing the form for a while now. It was working before I got the form finished and it works perfectly fine on another page however, it won't work on my page for registration. It keeps sending the success as false. My other page is a contact form and it's not that different from my registration page. It has all the same files inside.
My error code keeps showing me that I'm a bot when I'm clearly not a bot and I'm just testing out my own code.
I thought before there was a problem with where the code was stored in the directory at first, so I tried that.
Then, I thought that if I changed the keys, then maybe I would manage to get the system to work again. That didn't work.
Finally, I tried rearranging my html code to get it to work and that didn't work either.
Now, the crazy part, I'm still getting a score of 0.9 (checked on recaptcha site), which is enough for me to pass as a human but, it's still giving me that error within the JSON.
It worked fine before but, as soon as I started to test my input validation for my registration form, it began to call my response a false.
This is the error I keep getting. I wasn't too sure about formatting a JSON. This was returned with the php function var_dump. It was technically just one line.
object(stdClass)#13 (2)
{
["success"]=> bool(false)
["error-codes"]=> array(1)
{
[0]=> string(22) "missing-input-response"
}
}
This is the script I have in a file called recaptcha.php
<script src='https://www.google.com/recaptcha/api.js?render=<?php echo SITE_KEY; ?>'></script>
<script>
grecaptcha.ready(function() {
grecaptcha.execute('<?php echo SITE_KEY; ?>', {action: 'homepage'}).then(function(token) {
document.getElementById('g-recaptcha-response').value=token;
});
});
</script>
EDIT/
Added some additional code.
A php function. The constant SECRET_KEY is defined as a global variable in another file.
function getCaptcha($secretKey) {
$response =
file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=" . SECRET_KEY . "&response={$secretKey}");
$reCaptcha = json_decode($response);
return $reCaptcha;
}
This is included where I verify the recaptcha.
$reCaptcha = getCaptcha($_REQUEST['g-recaptcha-response']);
var_dump($reCaptcha);
If that helps.
I'm expecting it to turn into ["success"]=> bool(true) but, I don't even have the slightest clue what's wrong. I'm ready to get Google on the phone just to solve this issue. Can anyone help?
This error means that you're not passing in the site 'secret' param to the POST request to:
https://www.google.com/recaptcha/api/siteverify
Check that the 'secret' param (called SECRET KEY in the settings screen of the admin area), is correct and is being sent in the POST request.
Okay, so after looking at a few things, I found out why it kept returning as a "missing-input" error.
I had a page with two forms and only one recaptcha.
<form>
<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response" />
</form>
<form>
<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response" />
</form>
Because there were two of them, the API didn't know which to distinguish and instead of assigning the same value to both, it assigned no value to either. So, in-order to fix this I changed my javascript to this:
<script src='https://www.google.com/recaptcha/api.js?render=<?php echo SITE_KEY; ?>'></script>
<script>
grecaptcha.ready(function() {
grecaptcha.execute('<?php echo SITE_KEY; ?>', {action: 'homepage'}).then(function(token) {
document.getElementById('g-recaptcha-response').value=token;
document.getElementById('g-recaptcha-response2').value=token;
});
});
</script>
And my input form looked something like this:
<form>
<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response" />
</form>
<form>
<input type="hidden" id="g-recaptcha-response2" name="g-recaptcha-response2" />
</form>
The same value but, put into two separate fields. Even if you are using the second field for just one page, it's okay to leave it in there because it won't affect a page with just one recaptcha. As long as the first field is used to store the token and is reference in your html. I also changed this in the php.
$reCaptcha = getCaptcha($_REQUEST['g-recaptcha-response2']);
var_dump($reCaptcha);
I guess for anyone building a page with multiple forms, if you want to use recaptcha, you will need to distinguish two different input fields to receive the token. After spending nearly a day on this, I can't believe it took me that long to figure out something so simple. This will solve the missing-input error as well as the invalid-input error.

How to include PHP file with JavaScript and pass parameters

I need to run a PHP function in a page, after the user clicks on something, in this case, a link.
First I was using onclick to run a javascript AJAX to request a PHP file with the function in it. The thing is, I need to pass a parameter to the function, and I can't seem to be able to do it with AJAX.
If it was a PHP include, it would behave like it 'appended' the other file to the current file, so this way, the included file could reference variables in the current file. Apparently, AJAX is just taking the file I need, running it's code, and displaying the results. So yeah, doesn't work for me.
So basically. I need an exact replica of PHP's 'include', on JavaScript.
OR any other workaround.
My current code:
<br> <div id="seeMore"> </div> <br>
<ul> <li style="float: left"> Ver Mais </li> </ul>
<script type="text/javascript">
function loadMore()
{ $("#seeMore").load("feedP.php"); }
</script>
This is the part of the code in the main page that im needing help with, you can see it's loading a page called feedP.php, here's it's code:
<?php
echo 'test';
require_once('functions.php'); loadFeeds($urls, 5);
?>
As you can see, I have to run a function called loadFeeds, and it requires a parameter, $urls. Witch is created back on the main page.
EDIT:
I CAN'T reload the page, or redirect the user, that's why i'm trying to 'append' the file here.
You can use the second parameter of the load function which takes parameters that can be posted to the file in question:
$("#seeMore").load("feedP.php", {
url: 'url'
});
Then, in your PHP you can make use of $_POST to access the posted data.
data
Type: PlainObject or String
A plain object or string that is sent to the server with the request.
Reading Material
.load
You can pass the parameters through load function. I have altered your script code as below.
<script type="text/javascript">
function loadMore() {
$("#seeMore").load("feedP.php", {urls: "<?php echo $url; ?>"});
}
</script>
In the above code $url is the php variable which you assign the url you need to pass to feedp.php

Call javascript function within a PHP form

The architecture I use to load contents onto a common area on the web page is as below
I have a java script function within the form as shown below called javaScriptFunc which never gets invoked.
Is it possible to invoke a java script function within a form?
Please do let me know if more clarity is needed. I'll try to clarify. I'm stuck with this for a while now. I'd appreciate any help please
I think you are missing some PHP tags if I understand what you are trying to do correctly. Try this:
<form method="post" action="" id='somdId'>
<?php
require_once 'some_php_file.php';
if (isLoggedIn()) {
// Some PHP code here
?>
<script>
javaScriptFunc(<?php echo formatJson(someArgs); ?>);
</script>
<?php
}
?>
Not very clear what you want. You need to echo the script like this
echo ("<script type='text/javascript'>javaScriptFunc(" . formatJson(someArgs) . ");</script>");
provided you have already defined the function javaScriptFunc somewhere else in script.
For some reason, I the JS function doesn't seem to fire from within a form. I've worked around by re-writing the load logic to load the whole PHP page instead of a form. just a different way of doing things.

Insert code with JS just like echo in php

I want to get some code snippets from a PHP server to be "injected" in HTML. Basically when I open page.php I get some text like "_off".
The injection works with this code, however I can't use php in this html since it is local.
<img src="images/test
<?php
{ echo "_off"; }
?>
.jpg">
JavaScript seems to be the logical step. But if I just enter this at the position where I want the text of course it doesn't work:
<script type="text/javascript"> $.get( "page.php", function( data ) { document.write(data); } ); </script>
Any ideas?
You need to use $('#someElement').html(data) or $('#someElement').text(data) if you want to write the data to a specific place on the page. You should avoid using document.write
Here is a fiddle to demonstrate: https://jsfiddle.net/yd9mx4d3/

Unearthing a js php load/execution issue

Running a base web framework from https://github.com/panique/huge/
The overarching problem I have is: html table needing live updates to account for database (mysql) changes.
Where I'm stuck: I have added to the index/index.php page, the following javascript code to the end of the file (note: header and footers loaded around this index/index.php page) in attempt to refresh the need for updating the table every few seconds in order reload the html table based off of the mysql database state. The index/tableChange module simply gathers the mysql data and returns the query.
<?php echo "
<script language='javascript' type='text/javascript'>
function loadlnk() {
document.getElementById('tableHolder').innerHTML =
\"<object type=\"text/html\" data=\"<?php echo config::get('URL'); ?>index/tableChange\"></object>\";
setTimeout(loadlnk, 3000);
}
loadlnk();
</script>";
?>
When I test the index/tableChange snippet out, I am able to load the php by itself in its own individual webpage (but for the purpose of this question, I'm needing to load that content of tableChange into the index/index page).
I also tried adding the $(document).ready(function() { around inside of the script, but this didn't seem to help accomplish anything visible to changing the table.
I looked at what I understood and could find, but I don't think it's a quote issue.
You might like to remove the inner PHP tags and the echo statement and try like this:
<?php
echo "
<script language='javascript' type='text/javascript'>
function loadlnk() {
document.getElementById('tableHolder').innerHTML =
\"<object type=\"text/html\" data=\"" . config::get('URL') ."index/tableChange\"></object>\";
setTimeout(loadlnk, 3000);
}
loadlnk();
</script>";
?>
I found that I was getting an error in the console, similar to the following:
Load denied by X-Frame-Options: https://localhost/test/target.php does
not permit framing.
The solution, at least a quick one in this instance was to add a header before sending the output from /test/target.php ~ name header('X-Frame-Options: sameorigin'); then it worked just fine.

Categories

Resources