I'm trying to pass a javascript variable to php on the same page. I tried some code but nothing worked.
The current code looks like this:
function init(e){
$('#DeleteDaily').click(function() {
d = document.getElementById("DailyRequestsList");
selected = d.selectedIndex;
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "index.php?i=" + selected, true);
xhttp.send();
});
}
$(document).ready(init);
$(document).ready(function() {
$('#myForm').ajaxForm(function() {
<?php
if(isset($_POST['DeleteDaily'])) {
$Index = $_GET['i'];
}
?>
});
});
If I try to use Index as an argument for a python script it should delete an entry in a textfile and an element from a select object should be deleted on the website which doesn't happen. The python script itself works fine.
But I don't know why the variable isn't passed to php.
You can't just "mix" javascript and PHP like you're doing.
If that is inside a web page, the PHP code will be rendered (in your case, it will return nothing), and the page will just interpret an empty javascript function.
You need that PHP to be on the server, or turn it into javascript...
you can done it by
PHP Code
<?php
if(isset($_POST['DeleteDaily'])) {
$Index = $_GET['i'];
}else{
$Index='';
}
?>
Javascript code
$(document).ready(function() {
$('#myForm').ajaxForm(function() {
var index = '<?php echo $Index;?>';
if(index == ''){
//put your code
}else{
//put your code
}
});
});
Related
For my own reasons I am using JS in a seperate script, linked into my PHP file to perform several of nearly the same function (only the images change in each function) like this:
function Clicky1(element) {
var XTag= element.parentElement.previousElementSibling.firstChild;
if (element.src == "../image1.jpg")
{
element.src = "../image2.jpg";
XTag.innerHTML = XText;
localStorage.setItem(XTag.id, XText);
}
else
{
element.src = "../image1.jpg";
XTag.innerHTML = " ";
localStorage.removeItem(XTag.id);
}
}
function Clicky2(element) {
var VTag= element.parentElement.previousElementSibling.firstChild;
if (element.src == "../image3.jpg")
{
element.src = "../image4.jpg";
VTag.innerHTML = VText;
localStorage.setItem(VTag.id, VText);
}
else
{
element.src = "../image3.jpg";
VTag.innerHTML = " ";
localStorage.removeItem(VTag.id);
}
} //this repeats 3 more times
But what I want is to just use something like "{$myDB['images']}" as all the images that I am manually inserting links to within each function are already stored in my database. - How do I go about doing this in the simplest way?
You can't just inject PHP code into your Javascript like that. If the Javascript is in a block within a .php file then you can inject the result of running some PHP code as hard-coded values into your script, but not if it's in a separate .js file, because it doesn't pass through the PHP script engine before being sent to the browser.
But this code is overly repetitive anyway - why not have the image paths as parameters to the function? Then you could only have one single re-usable function. Apart from those names, the code is identical in its functionality. And also if these functions are called from JavaScript within a .php file, then you could inject the image paths into it using PHP at that point.
You'd change the function to more like this:
function Clicky(element, img1, img2) {
var XTag= element.parentElement.previousElementSibling.firstChild;
if (element.src == img1) {
element.src = img2; XTag.innerHTML = XText;
localStorage.setItem(XTag.id, XText);
}
else {
element.src = img1;
XTag.innerHTML = " ";
localStorage.removeItem(XTag.id);
}
}
And then you could call it from a <script block embedded in a PHP file, something like this:
Clicky(someElement, "<?php echo $myDB['images']; ?>", "<?php echo $myDB['images1']; ?>");
(or whatever PHP you have to use to get to each separate image string). Then you can use the values from your PHP easily, and you also wouldn't need Clicky1, Clicky2, Clicky3 etc etc all with virtually-identical code in them.
I'm making a project with the slides of text.
I have in the page a main div that contain the text of each slide.
I saved the content in a database.
I want do this operation:
When I click the arrow for view the next slide, PHP catch from database the content and save it in a variable.
Then with JQuery, I replace the maindiv's content with variable.
It is possible? If not, How can I do it?
Use a ajax request to simulate a post request, and parse the information with php. You will end up with someting like this:
<?php
if( isset( $_POST["slide"] ) {
// Database stuff
// Echo back
echo "Information that you need to get in jQuery";
}
?>
<script>
$("button.next_slide").click(function(){
var ajax;
if (window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
} else {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
ajax.onreadystatechange = function() {
if (ajax.readyState==4 && ajax.status==200) {
document.getElementById("some_element").innerHTML = ajax.responseText;
}
}
ajax.open("POST","this_page.php?slide=1&foo=bar&bar=foo",true);
ajax.send();
});
</script>
<button class="next_slide">Next slide</button>
<div id="some_element"></div>
Note: This could be done without jQuery, or with jQuery's $.ajax method. Read more here: http://api.jquery.com/jquery.ajax/
In my understanding, you want to load some data when user click on a particular button and then load it into a div we can achieve it via jQuery ajax and PHP.
HTML
<div class="main_div">
<ul id="list"><!-- Our content will load here --></ul>
Next
</div>
jQuery
jQuery(document).ready(function($){
$('.call_ajax').on('click', function(e){
e.preventDefault();
$.post('ajax.php', { get_slide: true }, function(response){
// We are telling jQuery to parse response as json because in ajax.php we have used json_encode function.
var data = jQuery.parseJSON(response);
$("#list").append('<li>' + data['slide'] + '</li>');
});
})
})
PHP ajax.php
if(isset($_POST['get_slide'])){
//Get slide from db and output it as json, but currently for example purpose we assume that we have a array.
$data['slide'] = 'Your slide text';
echo json_encode($data); die(); // We have used die because we don't won't our script to run any more.
}
I've not tested it, but it will work.
I have a simple if statement where when i send this certain data to the database, i want the php code to send bake a code that tells javascript its ok to continue, but if the php script sends back a bad code, javascript is to now move forward and display a certain text or something.
The php code works fine but for some reason my javascript files would not work at all.
My javascript is suppose to ajax request to parse.php and receive the data that parse.php sends back to it, if parse.php says 200 its suppose to load in specific items.
Here is the code for one of my systems:
$(document).ready(function(){
$("#chatForm").submit(function(){
var chatHash = $("#chatHash").val();
var body = $("#chatPoster").val();
var by = $("#userBy").val();
if(chatHash != "" && body != ""){
$.post('parse.php',{chatHash: chatHash, body: body, userBy: by},function(data){
if(data == "200"){ // Right here is where its messing up
$("#chatPoster").val("");
$.get('getChatMessages.php?hash=' + chatHash,function(data2){
$(".allMsgs").html(data2);
});
} else {
alert('Critical error');
}
});
} else {
alert('Error');
}
});
});
Here is the code for the parse.php page:
$chat = new ChatSystem;
if(isset($_POST['chatHash']) && isset($_POST['body']) && isset($_POST['userBy'])){
$chat->sendMessage($_POST['userBy'],$_POST['chatHash'],$_POST['body']);
}
Here is the code from the class ChatSystem that the parse.php page is referring to:
public function sendMessage($user,$hash,$body){
global $db;
$date = date("Y-m-d");
$time = date("H:i:s");
$timestamp = "$date $time";
if(empty($user) == false && empty($hash) == false){
$db->query("INSERT INTO chat_messages VALUES('','$user','$body','$timestamp','','0','$hash')") or die("error");
echo '200';
}
}
Even though my php code works perfectly the javascript still messes up. My php code sends back 200 like i ask it to but yet the jquery messes it up
Have a look here, http://api.jquery.com/jquery.post/.
You need a second parameter to the success callback function to be able to catch the response status code.
I.E. function(data,statusCode){ // check the status code here}
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I hope to run a php code inside a javascript code too and I do like that :
<?php function categoryChecking(){
return false;
}?>
....
function openPlayer(songname, folder)
{
if(<?php echo categoryChecking() ?> == true)
{
if (folder != '')
{
folderURL = "/"+folder;
}else
{
folderURL = '';
}
var url = "/users/player/"+songname+folderURL;
window.open(url,'mywin','left=20,top=20,width=800,height=440');
}else{
alerte('you should click on a subcategory first');
}
}
....
<a href='javascript:void();' onClick="openPlayer('<?php echo $pendingSong['id']; ?>','')">
finally I get this error instead the alert message "you should click on a subcategory first"
ReferenceError: openPlayer is not defined
openPlayer('265','')
You're reduced your test case too far to see for sure what the problem is, but given the error message you are receiving, your immediate problem has nothing to do with PHP.
You haven't defined openPlayer in scope for the onclick attribute where you call it. Presumably, the earlier JS code is either not inside a script element at all or is wrapped inside a function which will scope it and prevent it from being a global.
Update: #h2ooooooo points out, in a comment, that your PHP is generating the JS:
if( == true)
Check your browser's error console. You need to deal with the first error messages first since they can have knock on effects. In this case the parse error in the script will cause the function to not be defined.
Once you resolve that, however, it looks like you will encounter problems with trying to write bi-directional code where some is client side and some is server side.
You cannot run PHP code from JavaScript, because PHP is a server-side language (which runs on the server) and JavaScript is a client-side language (which runs in your browser).
You need to use AJAX to send a HTTP request to the PHP page, and then your PHP page should give a response. The easiest way to send a HTTP request using AJAX, is using the jQuery ajax() method.
Create a PHP file ajax.php, and put this code in it:
<?php
$value = false; // perform category check
echo $value ? 'true' : 'false';
?>
Then, at your JavaScript code, you should first add a reference to jQuery:
<script type="text/javascript" src="jquery.js"></script>
Then, use this AJAX code to get the value of the bool:
<script type="text/javascript">
$.ajax('ajax.php')
.done(function(data) {
var boolValue = data == 'true'; // converts the string to a bool
})
.fail(function() {
// failed
});
</script>
So, your code should look like this:
function openPlayer(songname, folder) {
$.ajax('ajax.php')
.done(function (data) {
var boolValue = data == 'true'; // converts the string to a bool
if (boolValue) {
if (folder != '') {
folderURL = "/" + folder;
} else {
folderURL = '';
}
var url = "/users/player/" + songname + folderURL;
window.open(url, 'mywin', 'left=20,top=20,width=800,height=440');
} else {
alert('you should click on a subcategory first');
}
})
.fail(function () {
// failed
});
}
I have a little problem with the syntax in Javascript. I want to work with a defined variable for a path in Javascript.
function checkusername(){
var u = _("username").value;
if(u != ""){
_("unamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "http://localhost:8888/.../file.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("unamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+u);
}
}
Now I want to set for
http://localhost:8888/.../file.php
a defined variable from php
define('Name','http://localhost:8888/.../file.php');
You'd either have to retrieve that constant via an AJAX call, or embed it into the Javascript at the time PHP is building the page.
e.g.
<?php
define('your_url', 'http://.....');
?>
<script type="text/javascript">
var url = <?php echo json_encode(your_url) ?>;
...
var ajax = ajaxOBJ('POST', url);
Note that if the sole purpose of this constant is to hold a url that's passed to javascript and is otherwise never used in PHP, you might as well just use a variable - Javascript could not alter the PHP/server-side value anyways, so it's effectively a constant.