This form is working perfectly fine, e.g. it stops the form submitting, there's no javascript errors in the console log. However, when I press submit, I get an alert with nothing in it. I have searched the internet for multiple solutions and they all give the same for me.
Here's my Javascript/Html
<script>
$(function(){
$("#submit").click(function(event){
event.preventDefault();
$.ajax({
type:"post",
url:"templates/process-token.php",
data:$("#form").serialize(),
success:function(response){
alert(response);
}
});
});
});
</script>
<form id="form" method = "post" action = "security_check">
<input type = "text" name = "fld1" id = "fld1" />
<input type = "text" name = "result1" id = "result1" value = "value_from_php_page" disabled />
<input type="submit" value="Submit" id="submit">
</form>
And here's the PHP, it's so simple but doesn't work:
<?php
echo $_POST["fld1"];
?>
Any help here would be appreciated. Thank you.
Change data from $('#form').serialize() to a one test variable so you can see if it is JS or PHP that is causing the issue.
On your PHP page:
<?php
isset($_POST["fld1"]) ? $myvar1 = $_POST["fld1"] : $myvar1 = 'No data passed...';
echo $myvar1;
?>
This confirms that there is infact an fld1 in the $_POST, and if not, says so, taking away the guess work...
You could do this with JSON both ways. Here's how I would implement this kind of thing in JavaScript and PHP.
There's a great function in jQuery that is a shortcut for getting JSON data. It's a shortcut for $.ajax specifically for simple calls.
$.getJSON( "templates/process-token.php?"+$("#form").serialize(), function( data ) { alert( data.reponse ) } );
PHP could return a json encoded string so it can be accessed from the JavaScript code more easily.
<?php echo json_encode( array('response'=>$_POST['fld1']) ); ?>
That can happen only if the text box #fld1 is empty. Type something in the text box and it will work.
Related
I have the following JS code:
<script>
$('#mpxModalEdit').on('show.bs.modal', function(e) {
var editId = $(e.relatedTarget).data('edit-id');
$(e.currentTarget).find('input[name="editId"]').val(editId);
});
</script>
This places the CORRECT edit-id value into a form text box name=editIdas I wish.
I would like to add another line of JS so that it ALSO places the value into a PHP variable since I need to make a subsequent
$query = "select * from playlists where id='editId'
I don't know any PHP syntax, but what I can tell you is that PHP is executed on the server and JavaScript is executed on the client (on the browser).
if on your page you had:
<form method="get" action="blah.php">
<input name="test"></input>
</form>
Your $_GET call would retrieve the value in that input field.
So how to retrieve a value from JavaScript?
Well, you could stick the javascript value in a hidden form field...
That could be the best solution only.
<script type="text/javascript" charset="utf-8">
var test = "tester";
// find the 'test' input element and set its value to the above variable
document.getElementByID("test").value = test;
</script>
... elsewhere on your page ...
<form method="get" action="blah.php">
<input id="test" name="test" visibility="hidden"></input>
<input type="submit" value="Click me!"></input>
</form>
Then, when the user clicks your submit button, he/she will be issuing a "GET" request to blah.php, sending along the value in 'test'.
Or the another way is to use AJAX.
PHP-Scripts are only run, when you load your page before any js is run or make an AJAX. In addition, PHP runs on the server, while JS is client-side.
My first suggestion would be, to really think, whether you need to do this (or even tell us, why you think it is).
If you really need it, you can perfom an AJAX and send your variable as data to the Server.
Using AJAX call you can pass js values to PHP script. Suppose you are passing editId js value to logtime.php file.
$(document).ready(function() {
$(".clickable").click(function() {
var userID = $(this).attr('id');
//alert($(this).attr('id'));
$.ajax({
type: "POST",
url: 'logtime.php',
data: { editId : editId },
success: function(data)
{
alert("success!");
}
});
});
});
<?php //logtime.php
$editId = isset($_POST['editId']);
//rest of code that uses $editId
?>
Place the AJAX call after
$(e.currentTarget).find('input[name="editId"]').val(editId);
line in your js script.
then you can assign to your desired PHP variable in logtime.php file
I'm new to PHP and am trying to figure something out that I'm sure is very basic. What I am wanting to do is generate variables in javascript and pass these to a PHP page which then loads and displays. The problem is, I seem to be able to both POST variables to the PHP page and load the PHP page but am unable to load the PHP page with the variables that I POSTed.
Here is an example of my code:
index.php
...
<script language="javascript">
function passToPHP(){
$.ajax({
type: "POST",
url: "/TraceExperiment/TraceExperiment.php",
data: {
varToPass: "foo"
},
success: function(){
window.location.href="/TraceExperiment/TraceExperiment.php";
}
})
}
</script>
<input type="button", value="displayPHP", onclick="passToPHP()"></input>
TraceExperiment.php
<?php
$tempVar = $_POST["varToPass"];
echo("hello" . $tempVar);
print_r($_POST);
?>
What is happening when I click displayPHP is that the ajax POST succeeds and
TraceExperiment.php loads fine (it actually has a whole heap of other html, php etc. code that loads and displays fine but for simplicity I've excluded that) but the $_POST array seems to be empty.
i.e. what ends up being displayed when I try to echo and print the POST array and variables is:
Notice: Undefined index: varToPass in C:\xampp\htdocs\TraceExperiment\TraceExperiment.php on line 3
helloArray ( )
Any help resolving this would be much appreciated. Ultimately, I'm simply after a way to display a PHP page that uses variables passed from a javascript file.
You can dynamically create a form in JavaScript and submit it rather than calling ajax and refreshing the page:
<script language="javascript">
function passToPHP(){
$('<form action="/TraceExperiment/TraceExperiment.php" method="POST"><input type="hidden" name="varToPass" value="foo" /></form>').appendTo('body').submit();
}
</script>
<input type="button" value="displayPHP" onclick="passToPHP()"></input>
You can do a get request like this
<script language="javascript">
function passToPHP(){
var varToPass= "foo"
window.location = "/TraceExperiment/TraceExperiment.php?varToPass="+varToPass;
</script>
<input type="button", value="displayPHP", onclick="passToPHP()"></input>
<?php
$tempVar = $_GET["varToPass"];
echo("hello" . $tempVar);
?>
or a post request by creating a simple form
$('#frm').submit(function(e){
var varToPass= "foo"
e.preventDefault();
$(this).find('#varToPass').val(varToPass);
$(this).submit();
});
<form id ="frm" method="POST" action="/TraceExperiment/TraceExperiment.php">
<input type="hidden" id="varToPass"/>
<input type="submit"/>
</form>
dont redirect to the same page on success. you are getting the undefined var on second go to that page
function passToPHP() {
$.ajax({
type: "POST",
url: "/TraceExperiment/TraceExperiment.php",
dataType:text,
data: {
varToPass: "foo"
},
success: function(data) {
console.log(data);
}
})
}
try doing like this
if you want to show the message in the html
try
success: function(data) {
$('body').append(data);
}
There is 2 solution for This
by the different approach
Generate your variable value by JavaScript and than use
Write in TraceExperiment.php
function genratenumber(){
return "number"
}
window.location.href= "/TraceExperiment
/TraceExperiment.php?yourvar="+genratenumber()
</script>
<?php }else{
// get the value of $_GET['yourvar']
} ?>
Than get it by using $_GET['yourvar'] on same page
By using your approch
you need to put that variable in session (in ajax file) than only you can get that variable
I have a form with action="" and many AJAX codes to validate or chain-select the form elements as below.
** My current code (Simplified) **
<?php
if( isset( $_POST['create_transaction'] ) ) {
// do something
}
?>
<div>
<!-- period information will be filled up by ajax -->
<input type="text" name="period" class="form-control" id="period" readonly />
</div>
<form id="form" method="post" action="">
<input name="r_date" type="date" value="<?php echo isset( $_POST['r_date'] ) ? $_POST['r_date'] : date( "Y-m-d" ); ?>" class="transaction_date" />
<input type="submit" name="create_transaction" value="Create" />
</form>
<script>
jQuery(document).ready(function($) {
// Do this and that...
/* Get period information if date is already filled up on page load */
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
var $transaction_date = $(".transaction_date").val();
if( $transaction_date ) {
// call ajax for period <-- THIS IS THE PROBLEM CHILD.
jQuery.ajax({
url: ajaxurl,
data: 'action=get_period_by_date&transaction_date='+$transaction_date,
type: 'GET',
success:function(results) {
jQuery("#period").val(results);
}
});
}
});
</script>
Here I am retrieving a period name using the input date. For example, if the date is 2014-01-01, then the #period div will be filled up with PERIOD-01. If the date is 2014-08-25, then the #period div will be filled up with PERIOD-08. This date field is auto-filled up with today's date when the page loads.
The problem is that if I insert the AJAX code to retrieve period information using the date input, submitting the form (clicking the 'create' button) leads to 404 error. If I remove the code, the form works well.
There doesn't seem to be a problem in the get_period_by_date function since it correctly retrieves and shows period name.
What would be the cause of my problem?
404 error means that your AJAX request leads to an unexisting path. Thats the first issue you should solve :).
Use your console to debug this one:
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
You are using this var in a jQuery method. I think it will be literally interpreted. I don't think it's possible to use php syntax here.
I'm not sure if it's a good practice, but for a quick fix you could make a hidden field in your html page with that tag. And then you could easily get the value from it with the use of jQuery or javascript
Ok I am confused with php, javascript and html and dont know what to do. On researching on the internet, i found js is client side and php is server side. when a php file is run on the browser, it converts everything into html and the page is loaded. Now let me tell you guys what i am doing.
I have a php file that give me some stats from a particular url (in the sample i am just showing url)
<?
$url="www.example.com";
echo "URL = " .$url;
?>
Result URL = www.example.com
The above code echoes the url which is www.example.com. I added a textbox to this code which i believe is javascript+html
<script>
function myFunction() {
$url=myurl.value;
}
</script>
<input type="text" name="myurl" id="myurl">
<input onclick="myFunction()" type="submit" name="btnurl" id="btnurl" value="Submit">
<br><br>
<?
$url="www.example.com";
echo "URL = " .$url;
?>
Here the result is same. only difference is that it has a textbox and button above the result.
When I enter another url in the textbox and press submit, it does nothing probably because the page is already loaded. I want to replace the result of www.example.com to the one which is entered in the textbox without changing the .php file. There will always be a default url in the .php file. whenever the file is opened in the browser, the default statistics will be shown... only when the user enters new url and clicks submit, the stats should change.
How can I achieve this? I am behind this since more than a couple of hours now and not sure how to get this done. Please help me.... Thank you.
EDIT
Can I have two .php files? one for the user to enter url and submit and another one to get the entered url and echo it? If yes, how? If I understand this logic, i can get a start for what I am doing.
I think you are trying to do more with your js function, but syntactically it is combining js and php. It should look like this
function myFunction() {
var url = document.getElementById('myurl').value;
}
Although this doesn't really do anything other then assign the content of the text box to a variable.
EDIT
<script>
function myFunction() {
document.getElementById('url').innerHTML = document.getElementById('myurl').value;
}
</script>
<input type="text" name="myurl" id="myurl">
<input onclick="myFunction()" type="submit" name="btnurl" id="btnurl" value="Submit">
<br><br>
<? $url = "www.example.com"; ?>
URL = <span id="url"><?= $url; ?></span>
natzim is correct if you are wanting to write the url back to the php file. If you use javascript to change the action of the form, it will submit to a different page.
//javascript
function myFunction() {
//this should change the page that loads after submit.
//If you want to go to a new page that the user enters, leave this code in...
//If not, remove it
document.getElementsByTagName("form")[0].action = document.getElementById("myUrl").value;
}
That is assuming you have a form tag somewhere (which you will need to submit the page). Also I am not sure this code will run if you use a submit and not a button. If you used a button instead you could append this to the code above to submit the form:
//This would be part of your myFunction if you used a button instead of a submit input
document.getElementsByTagName("form")[0].submit();
as per my comment -
this code is your old php:
<?
$url="www.example.com";
echo "URL = " .$url;
?>
and this is the php I suggested:
<?php
$url=isset($_POST['myurl']) ? $_POST['myurl'] : 'www.example.com';
echo "URL = " .$url;
?>
this would check the myurl input from that was submitted to the server and set the value of $url to its value if it existed then the $url variable would be echoed to the page under the inputs.
This code is assuming you are using the POST method rather than the GET method when your form was submitted.
**EDIT: **
To clarify - here is your page with the modifications I am suggesting. (Please ignore the javascript above as it seems you will not need it):
<form action='www.example.com' method='post'>
<input type="text" name="myurl" id="myurl">
<input type="submit" name="btnurl" id="btnurl" value="Submit">
<br><br>
<?php
$url=isset($_POST['myurl']) ? $_POST['myurl'] : 'www.example.com';
echo "URL = " .$url;
?>
</form>
Imagine the page always refreshes after submitting a comment form. That is annoying since the comments are at not at the top of the page and you always have to scroll to the bottom to see your comment and the other ones.
I thought it would be a lot better to use ajax to submit the form.
HTML
<form id="com-form" method="post">
<textarea type="text" name="text" required=""></textarea>
<input type="submit" value="Post"/>
</form>
<div id="com-refresh"></div>
jQuery
$("#com-form").on('submit', function(e) {
e.preventDefault();
var form = $(this),
form_data = form.serialize();
$.post('/php/comments/add.php', form_data, function(data) {
$("#com-refresh").append(data);
});
});
PHP
<?php
session_start();
require_once 'comment.class.php'; //require a class with methods
$text = $_POST['text'];
if($_SESSION['status'] == 'loggedin') {
if(isset($text)) {
$comment = new Comment(); //initialize the Comment object
echo $comment->add_comment($text); //safe the comment in the database and output it
} else echo "Your comment is empty.";
} else echo "Please log in to post comments.";
I hope the code is understandable.
Do you think it is smart or a bad practice to use ajax to not refresh the page after submitting a form?
How should it be done? Do you have a better idea, a cleaner solution?
You could simply do:
$(document).ajaxSuccess(function(e, xhr, settings) {
$(".mydiv").html(xhr.responseText);
});
having your php file print what ever html you want to replace.
further reading: ajaxSuccess
example of what might be your solution
form file:
<form method="post">
<textarea type="text" name="comment" id="com-area"></textarea>
<input type="submit" id="com-submit"/>
</form>
<div id="com-refresh">
<?php require_once "comments/build.php"; ?>
</div>
$(function() {
$(".cmtx_form").submit(function(e) {
e.preventDefault();
var form = $(this);
var text = $(".cmtx_textarea_field").val();
$.ajax({
type: 'POST',
url: 'comments/add.php?ajaxCall=true',
cache: false,
data: { comment: text }
});
});
});
$(document).ajaxSuccess(function(e, xhr, settings) {
$("#com-refresh").html(xhr.responseText);
});
your add.php file should look somewhat like so:
// ... code code code...
if (isset($_GET['ajaxCall']) && $_GET['ajaxCall']) {
include_once('/path/to/build.php');
}
simply you can redirect the file from add.php to build.php after complete the process using header('location:comments/build.php'); or some other else, so second ajax call was unnecessary.
The problem was the php code. I have rewritten the functions that generate the comments in OOP style which helped a lot. I edited the post know so it can be useful in the future.
To make it short:
Use ajax! Your website's user experience will be a lot better, because you are able to provide live updates, etc.
It is recommendable to use the built-in jQuery function .serialize() to safe data into a "text string in standard URL-encoded notation", that can make your work more simple.
I know there is a lot of discussions about OOP, but it really helps understanding, organizing and maintaining your code more easily