Tried to get value from javascript and get error - javascript

I have tried to get value from file.js and got error:
file.js: this is how i send it:
$.post("site.php",{
whatever: ec
});
site.php: And this is how I tried to get that value:
<button onclick="justdoit();">Click my</button>
<script>
function justdoit() {
var whatever = "<?php echo $_POST['whatever']?>";
alert(whatever);
}
</script>
Got error in console: Uncaught SyntaxError: Invalid or unexpected token on site.php

Edit2: (on comment)
If you have everything in your one page, you never need $.post to go to server
and get back it at from same requesting page. However if you need some server processing and need to fetch the processed data from server then use $.post i.e. ajax request like i answered in edit1
Edit1: (on comment)Changed answer
your site.php (a file just for server side processing) should contain just
$someparam = echo $_POST['whatever'];
Now you should know about $.post
your client side file index.php (a file which you are opening in browser and which shows you your page) should contain following
<button onclick="justdoit();">Click my</button>
<script>
function justdoit()
{
$.post("site.php",{whatever: 'Hi I am a string'; }).done(function(data){
alert(data);
});
}
</script>
Previous answer
site.php
<?php
$someparam = echo $_POST['whatever'];
?>
//off-course above code should not have any error
If it still gives youy problem then there could be somewhere else => In that code which you have not shared. If it works on removing this code. Then you should edit your question and tell the single line which gives error

try this
<button onclick="justdoit();">Click my</button>
<script>
function justdoit() {
var prize = "<?php echo $_POST['prize'];?>";
alert(prize);
}
</script>
u forgot token behind php :P ';'

Related

How to get "$.Post" variable in another site

i search internet for my question and i doesn't found how to get my $_POST on another page. Please help.
game.php:
<?php
session_start();
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
var drzewo = 0;
function save() {
$.post( "save.php", { drzewo: drzewo } );
window.location.href = "save.php"
}
presave.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<?php
session_start();
$_SESSION['drewno'] = $_POST["drzewo"];
echo $_SESSION['drewno']
?>
Undefined array key picture
Your question seems incomplete in my opinion. There are many things missing from your question. From your image I assume you are using it on local server. There are one thing that looks weird is this:
`$.post( "save.php", { drzewo: drzewo } );`
Where is this save.php file stored? Is it stored in your root file? Or along with the operating file. Put a "/" before save.php and see what happens.
There is another thing that seems awkward is your image is showing there is a presave.php file. But I found nothing about that file in your question details.
I can see that you put a redirecting code in your script. JS is not supposed to work like that. What happening here is it is doing an asynchronous operation. That is why PHP can't get the data and showing you a error. If you want to send data send it in a form. Or you can put a redirection in your PHP code after getting the post data. Since it is an AJAX call you can see some reports in your console.log() with the response data.
$.post( "save.php", { drzewo: drzewo } );
window.location.href = "save.php"
Let's analyze these 2 lines of code.
When you send a post request through javascript, it goes through an ajax request and the browser waits till the save.php completes working it's code and returns to the ajax. Here the save.php has received the $_POST data and has processed it.
This processed data by save.php will not output in the browser. It will go to the post (ajax) callback function. If you want to display the data, you need to use a callback function. See this https://www.w3schools.com/jquery/ajax_post.asp for a simple usage of $.post() function.
In the next line of your code you are redirecting your browser to save.php without sending any $_POST data. Since now your save.php does not have any information about $_POST["drzewo"] it throws an error Undefined array key "drzewo" .
Therefore instead of window.location.href page redirect, you need a callback function with your $.post() function. I hope now you understand why you are getting this error.
[Edit]- I have added some code for your better understanding. You can refer to this excellent "JQuery Ajax POST Method" tutorial from freecodecamp.org. https://www.freecodecamp.org/news/jquery-ajax-post-method/
game.php
<?php
session_start();
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<button id="btn" onclick="save();">Click this</button>
<script type="text/javascript">
var drzewo = 0;
function save() {
$.post("save.php", {
drzewo: drzewo
},
function(result) {
alert("This result contains the output from save.php : " + result);
//Write here the code you want to execute after the POST request is successfully completed.
}
);
}
</script>
</body>
</html>
save.php
<?php
session_start();
$_SESSION['drewno'] = $_POST["drzewo"];
echo $_SESSION['drewno'];
If you want to pass data from one URL to another, use query string. $.post() makes a POST request, but it seems like save.php is not an endpoint but actually a page.
In other words, you can do this:
window.location.href = `save.php?drzewo=${drzewo}`;
And then on save.php simply read the value from $_GET:
<?php
session_start();
$_SESSION['drewno'] = $_GET["drzewo"];
echo $_SESSION['drewno']
?>

JQuery to submit PHP not executing

After hours of playing with this, it hit me that my JQuery simply isn't executing.
I have a page that I am trying to submit to a PHP script without refreshing/leaving the page. If I use a typical form action/method/submit, it inserts into my database just fine. But when I use JQuery, the JQuery will not run at all. The alert does not show. (I'm new to JQuery). I have tried to research this, but nothing is working.
Here is my main page:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(e) {
$('submitpicks').on('submit','#submitpicks',function(e){
e.preventDefault(); //this will prevent reloading page
alert('Form submitted Without Reloading');
});
});
</script>
</head>
<body>
<form name="submitpicks" id="submitpicks" action="" method="post">
<script language="javascript">
var v=0;
function acceptpick(thepick,removepick){
var userPick = confirm("You picked " + thepick + ". Accept this pick?");
//var theid = "finalpick" + v;
var removebtn = "btn" + removepick;
//alert(theid);
if(userPick==1){
document.getElementById("finalpick").value=removepick;
document.getElementById(removebtn).disabled = true;
document.getElementById("submitpicks").submit();
v=v+1;
}
}
</script>
<?php
include "Connections/myconn.php";
//$setid = $_SESSION["gbsid"];
$setid = 11;
$setqry = "Select * from grabBagParticipants where gbsid = $setid order by rand()";
$setresult = mysqli_query($conn, $setqry);
$u=0;
if(mysqli_num_rows($setresult)>0){
while($setrow = mysqli_fetch_array($setresult)){
//shuffle($setrow);
echo '<input type="button" name="' . $setrow["gbpid"] . '" id="btn' . $setrow["gbpid"] . '" value="' . $u . '" onClick=\'acceptpick("' . $setrow["gbpname"] . '", ' . $setrow["gbpid"] . ');\' /><br />';
$u=$u+1;
}
}
?>
<input type="text" name="finalpick" id="finalpick" />
<input type="submit" value="Save" />
</form>
<div id="results"> </div>
</body>
</html>
Here is my PHP:
<?php
include "Connections/myconn.php";
$theGiver = 1;
$theReceiver = $_POST['finalpick'];
$insertsql = "insert into grabBagFinalList(gbflgid, gbflrid) values($theGiver, $theReceiver)";
mysqli_query($conn, $insertsql);
?>
you can use e.preventDefault(); or return false;
<script>
$(document).ready(function(e) {
$('#submitpicks').on('submit',function(e){
e.preventDefault();
$.post('submitpick.php', $(this).serialize(), function(data) {
$('#results').html(data);
});
// return false;
});
});
</script>
Note: in your php you not echo out anything to get it back as a data .. so basic knowledge when you trying to use $.post or $.get or $.ajax .. to check the connection between js and php .. so in php
<?php
echo 'File connected';
?>
and then alert(data) in js .. if everything works fine .. go to next step
Explain each Step..
before everything you should check you install jquery if you use
<script type="text/javascript" src="jquery-1.11.3.min.js"></script>
from w3schools website.. its totally wrong .. you should looking for how to install jquery ... then
1st to submit form with js and prevent reloading.. and you used <script> in your main page
<script>
$(document).ready(function(e) {
$('#submitpicks').on('submit',function(e){
e.preventDefault(); //this will prevent reloading page
alert('Form submitted Without Reloading');
});
});
<script>
output : alert with Form submitted Without Reloading ... if this step is good and you get the alert .. go to next step
2nd add $.post to your code
<script>
$(document).ready(function(e) {
$('#submitpicks').on('submit',function(e){
e.preventDefault(); //this will prevent reloading page
$.post('submitpick.php', $(this).serialize(), function(data){
alert(data);
});
});
});
<script>
and in submitpick.php >>> be sure your mainpage.php and submitpick.php in the same directory
<?php
echo 'File connected';
?>
output: alert with File connected
Have you heard of AJAX(asynchronous javascript and XML). While it may not be something that is easy to learn for someone who is new to JQuery and javascript, it does pretty much what you need. Well, its a bit more complicated than that, but basically AJAX submits information by using HTTP requests (much like normal forms) but without refreshing the page.
Here's a link to a tutorial: http://www.w3schools.com/ajax/ with vanilla javascript.
Here's one with Jquery: http://www.w3schools.com/jquery/jquery_ajax_intro.asp
And here's an example of how you can set it up with Jquery:
$(document).ready(function() {
$.ajax({
method: "POST",
url: "/something.php"
dataType: "JSON",
data: {formData:{formfield1: $('formfield1').val(), formfield2: $('formfield2)'.val()}},
success: function(data){
if (data["somevalue"]) == something {
dosomething;
} else {
dosomethingelse
},
error: function() {
alert("Error message");
}
});
});
This is only a basic example, now what does all this stuff mean anyway. Well, there are several methods, some of them are POST and GET, these are HTTP request methods, which you can use to do several things. I'm no expert on this stuff, but here's what they do:
Method
POST
POST basically works, to submit information to a server, which is then usually inserted to a database to which that server is connected to. I believe most forms utilize POST requests, but don't quote me on that.
GET
GET on the other hand requests data from a server, which then fetches it into the database and sends it back to the client so it can perform an action. For instance, whenever you load a page, GET requests are made to load the various elements of a page. What's important to note here, is that this request is made specifically to retrieve data.
There are other types of HTTP requests you can use such as PUT and DELETE, which I'd say are the most common along with GET and POST. Anyway I'd recommend that you look them up, its useful information.
Url
The url represents the path to which you are making a request, I'm not exactly sure how it works with PHP, I think you just need to call the PHP page in question and it will work properly, but I'm not sure, I haven't used PHP since my last semester, been using Rails and it doesn't work quite the same. Anyway, lets say you have some PHP page called, "Something.php" and lets say that somethihng PHP has the following content:
<?php
$form_data = $_POST['data'];
$array = json_decode(form_data, true);
do something with your data;
$jsonToSendBack = "{status: 1}";
$response = json_encode($jsonToSendBack);
echo $response;
?>
So basically what that file received was a JSON, which was our specified datatype and in turn after we finish interpreting data in the server, we send back a response through echo our echo. Now since our datatype is a JSON, the client is expecting a response with JSON, but we'll get to that later. If you're not familiar with JSON, you should look it up, but in simple terms JSON is a data exchange format that different languages can utilize to pass data to each other, like in this example, where I sent data to PHP through Javascript and vice-versa.
DataType
Data type is basically, the type of information that you want to send to the server, you can specify it through ajax. There are many data types you can send and receive, for instance if you wanted to, you could send XML or Text to the server, and in turn it should return XML or text, depending on what you chose.
Success and Error
Finally, there's the success and error parameters, basically if a request was successful, it returns a status code of 200, though that doesn't mean that other status codes do not indicate success too, nonetheless 200 is probably the one you'd like to see when making HTTP requests. Anyway, success basically specifies that if the request succeeded it should execute that function code I wrote, otherwise if there is an error, it will execute the function within error. Finally, even if you do have a success on your request, that doesn't mean everything went right, it just means that the client was successful in contacting the server and that it received a response. A request might be successful but that doesn't generally mean that your server-side code executed everything perfectly.
Anyway, I hope my explanation is sufficient, and that you can take it from here.

Reloading url page with ajax

i'm trying to refresh page every 3 second, the url page change with $_GET variable.
i'm trying to save $_GET var into session and cookie, but get error header has already sent.
how to change url after page reload ?
here my script :
Index.php
<?php
session_start();
$skill =$_SESSION['skill'];
?>
<script type="text/javascript">
var auto_refresh = setInterval(function () {
$('#src2').load('monitor.php?skill=<?php echo $skill;?>').fadeIn("slow");
}, 3000);
</script>
monitor.php
<?php
include "conn.php";
session_start();
$_SESSION['skill'] = $_GET['skill'];
if ($_SESSION['skill']=='')
{
$a ="bro";
$_SESSION['skill']=4;}
elseif ($_SESSION['skill']==4){
$a = "yo";
$_SESSION['skill']='5';
}
elseif ($_SESSION['skill']==5){
$a = "soo";
}
?>
First off, "headers already sent" means that whichever file is triggering that error (read the rest of the error message) has some output. The most common culprit is a space at the start of the file, before the <?php tag, but check for echo and other output keywords. Headers (including setting cookies) must be sent before any output.
From here on, this answer covers how you can implement the "refresh the page" part of the question. The code you provided doesn't really show how you do it right now, so this is all just how I'd recommend going about it.
Secondly, for refreshing the page, you will need to echo something at the end of monitor.php which your JS checks for. The easy way is to just echo a JS refresh:
echo '<script>window.location.reload();</script>';
but it's better to output some JSON which your index.php then checks for:
// monitor.php
echo json_encode(array('reload' => true));
// index.php
$('#src2').load('monitor.php?skill=<?php echo $skill;?>', function(response) {
if (response.reload) window.location.reload();
}).fadeIn('slow');
One last note: you may find that response is just plain text inside the JS callback function - you may need to do this:
// index.php
$('#src2').load('monitor.php?skill=<?php echo $skill;?>', function(response) {
response = $.parseJSON( response ); // convert response to a JS object
if (response.reload) window.location.reload();
}).fadeIn('slow');
try putting
ob_start()
before
session_start()
on each page. This will solve your problem.
Without looking at the code where you are setting the session, I do think your problem is there. You need to start the session before sending any data out to the browser.
Take a look at: http://php.net/session_start
EDIT:
Sorry, a bit quick, could it be that you send some data to the browser in the 'conn.php' file? Like a new line at the end of the file?

Calling PHP script with Cordova

I'm working on an app that's supposed to contain the same information as an already existing website.
What I wanted to do was create a Cordova app that calls an external PHP script which in turn gets information from the database that the website is using.
Right now I'm working on calling the PHP script but it just doesn't seem to work.
Here is the script I'm trying to call:
<?php
$a = 1;
$b = json_encode($a);
return $b;
?>
Ofcourse this is just to test the connection. The URL for this file is http://localhost:8888/get_posts.php
Here is the code for the app:
$('#page1').bind('pageshow', function () {
$.get('localhost:8888/get_posts.php', function (data) {
$(this).find('.homeText').html(data);
});
});
This fetches the file whenever the page is shown (handy) and then puts the new data into the page. The problem is that the page remains empty at all times, when it should be showing a "1". Can anyone see where it goes wrong?
Error message: XMLHttpRequest cannot load localhost:8888/get_posts.php. Cross origin requests are only supported for HTTP.
UPDATE: The error message dissapeared when adding http:// to the url, but the problem persists.
I've changed the code to:
$('#page1').bind('pageshow', function () {
$.get('localhost:8888/get_posts.php', function (data) {
alert(data);
});
});
and it shows me an empty alert box.
Solution: Had to use echo instead of return for the script to show me a result.
http:// was also required so the script is allowed to communicate.
You have to 'echo' your response not returning it like so
<?php
$a = 1;
$b = json_encode($a);
echo $b;
?>

Parsing PHP response: Uncaught SyntaxError: Unexpected token <

I'm using AJAX to make a call to a PHP script. The only thing I need to parse from the response is a random ID generated by the script. The problem is that the PHP script throws a number of errors. The errors are actually fine and don't get in the way of the program functionality. The only issue is that when I run
$.parseJSON(response)
I get:
Uncaught SyntaxError: Unexpected token <
Since the PHP response starts with an error:
<br />
<b>Warning</b>:
I'm wondering how to change the PHP or JS such that it can parse out the ID despite the errors.
PHP:
$returnData = array();
$returnData['id'] = $pdfID;
echo json_encode($returnData);
...
JS:
function returnReport(response) {
var parsedResponse = $.parseJSON(response);
console.log(parsedResponse);
pdfID = parsedResponse['id'];
I know that the warnings should be resolved, but the warnings are not functionality critical for now and more importantly
1) Even if these warnings are resolved new ones may come up down the line and the JSON should still be properly parsed and
2) In addition to the warnings there are 'notices' that cause the same issue.
Why not deal with and eliminate the warning so that the result from the server is actually JSON?
There are several ways this could be solved (any one of which would work):
1. Fix your warnings. : PHP is saying something for a reason.
2. Turn off error reporting & error display:
At the top of your file place the following
error_reporting(false);
ini_set('display_errors', false);<br/>
3. Use the output buffer:
At the top of your file place
ob_start();
When you have your data array and your ready to echo to browser clear the buffer of all notices warnings etc.
ob_clean();
echo json_encode($returnData);
ob_flush();
4. Set a custom error handler:
set_error_handler("myCustomErrorHandler");
function myCustomErrorHandler($errno, $errstr, $errfile, $errline){
//handle error via log-to-file etc.
return true; //Don't execute PHP internal error handler
}
5. Optionally in JavaScript:
Sanitse your response to be a JSON array:
function returnReport(response) {
response = response.substring(response.indexOf("{") - 1); //pull out all data before the start of the json array
response = response.substring(0, response.lastIndexOf("}") + 1); //pull out all data after the end of the json array
var parsedResponse = $.parseJSON(response);
console.log(parsedResponse);
pdfID = parsedResponse['id'];
}
Like everybody else has said, you SHOULD really fix your errors and handle them accordingly.
This is something more to have under circumstances that you will not control and yet want to handle errors accordingly:
<?php
//Change it to 'production' or something like that
//so that you don't send debug data on production
define('ENVIRONMENT', 'testing');
//Set your error handler globally
set_error_handler('handle_error');
function handle_error($errno, $errstr, $errfile, $errline, array $errcontext )
{
//Set your headers to send a different than 200 so you can
//catch it on error on jQuery
header($_SERVER["SERVER_PROTOCOL"].' 500 Internal Server Error');
//Set output as json
header('Content-Type: application/json');
//Create some sort of response object
$response = new stdClass;
$response->message = "Application error details";
//You dont want to give debug details unless you are not on prod
if(ENVIRONMENT == 'testing') {
$severity = get_err_severity($errno);
$response->error_detail = "({$severity}) [{$errfile}#L{$errline}]: {$errstr}";
$response->context_vars = $errcontext;
}
//Return the json encoded error detail and exit script
$json = json_encode($response);
exit($json);
}
function get_err_severity($severity)
{
switch($severity) {
case E_ERROR:
return 'E_ERROR';
case E_WARNING:
return 'E_WARNING';
case E_PARSE:
return 'E_PARSE';
case E_NOTICE:
return 'E_NOTICE';
case E_CORE_ERROR:
return 'E_CORE_ERROR';
case E_CORE_WARNING:
return 'E_CORE_WARNING';
case E_COMPILE_ERROR:
return 'E_COMPILE_ERROR';
case E_COMPILE_WARNING:
return 'E_COMPILE_WARNING';
case E_USER_ERROR:
return 'E_USER_ERROR';
case E_USER_WARNING:
return 'E_USER_WARNING';
case E_USER_NOTICE:
return 'E_USER_NOTICE';
case E_STRICT:
return 'E_STRICT';
case E_RECOVERABLE_ERROR:
return 'E_RECOVERABLE_ERROR';
case E_DEPRECATED:
return 'E_DEPRECATED';
case E_USER_DEPRECATED:
return 'E_USER_DEPRECATED';
}
}
function test_error()
{
$test = array('foo'=>'bar');
$baz = $test['baz'];
echo $baz;
}
test_error();
While this doesn't solve the broader issue of warnings, I used this hack to parse the response:
function returnReport(response) {
var pdfID = parseID(response);
...
}
function parseID(response) {
var responseIndex = response.indexOf('{"id');
var start = responseIndex + 7;
var pdfID = response.slice(start, start + 6);
return pdfID;
}
I know everybody has recommended you fix the errors, I would agree, but if you do not want to then there is another a solution.
If you are getting a number of warnings and expect new warnings could appear, simply disable reporting of warnings and notices:
error_reporting(E_ALL ^ (E_NOTICE | E_WARNING));
If ob is enabled
ob_end_clean();
ob_start();
echo json_encode($returnData);
Or, in top of your file
error_reporting(0);
I am sure that there would be some mistakes in your PHP code due to that error is coming please check few things:
Make sure that there should not be more than one echo or print in your php code for printing response.
jQuery must be included properly.
And check the other php code in your function/page that should not produce any run time errors/warnings because it will also create same problem.
I am saying this because I have tried your code and it working fine for me you can check that also:
PHP File: myContentPage.php
<?php
$returnData = array();
$returnData['id'] = 123;
echo json_encode($returnData);
?>
HTML File:
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='js/jquery.js'></script>
</head>
<body>
<h1>Demo Example</h1>
<script>
function loadResponse() {
var dataString={};
$.ajax({
url:"myContentPage.php",
type: 'POST',
cache:false,
data: dataString,
beforeSend: function() {},
timeout:10000000,
error: function() { },
success: function(response) {
var parsedResponse = $.parseJSON(response);
pdfID = parsedResponse['id'];
console.log(pdfID);
alert(pdfID);
}
});
}
loadResponse();
</script>
</body>
</html>
And for handling the warnings you can do these this:
To skip warning messages, you could use something like:
error_reporting(E_ERROR | E_PARSE);
or simply add the # sign before the each line of php code on that you think warning can come
Happy Coding!!
Script used in Ajax call just must have perfect constrution, shall not thrown any warnings just by convenience, for production you should have erros disabled, so fix it into development, edit the question with the warning that's phps givin to we help you with directly on the point.
1st alternative:
Solve the problem causing the warning. A good PHP system should never show a PHP Notice, Warning or Error. This may expose some critical information.
2nd alternative:
Just disable error reporting by setting
error_reporting(0);
This will work, but will hide even to you any errors.
3rd alternative:
Set a error handler function that treat the error and show a JSON friendly error message that does not cause any trouble.
Also I recommend you to log this exceptions. It will allow you to debug any system trouble.
My recomendation?
Use 1st and 3rd alternatives together, and be HAPPY!
You can use Try..Catch construct in the javascript function code as shown below.
function returnReport(response) {
try
{
var parsedResponse = $.parseJSON(response);
console.log(parsedResponse);
pdfID = parsedResponse['id'];
}
catch(err)
{
//Do something with the err
}
}
This will work even if your php code generates debug info in response.
If you want to see the error in JavaScript, you should handle the error on PHP with a "try catch" and the "catch" to do something like "echo json_enconde ($ error);" on this way you can parse from JavaScript.
Example:
try{
$returnData = array();
$returnData['id'] = $pdfID;
echo json_encode($returnData);
}catch (Exception $e) {
echo json_encode($e);
}
I hope this helps :)!

Categories