I need help to send the token with ajax request. He always say: "invalid".
What Mistake do I make?
world.php:
<form name="theform" id="suchform" method="POST">
<p><input type="text" class="find_person search_btn" placeholder="Person Suchen" tabindex="1"></p>
<p><input type="hidden" class="csrf_token" value="<?= echo $_SESSION['csrf_token']; ?>"></p>
</form>
<div id="output">
</div>
<script>
$('#suchform').on('input', function(event) {
event.preventDefault();
var name = $('#suchform').find('.find_person').val();
var token = $('#suchform').find('.csrf_token').val();
$.ajax({
type: 'POST',
url: 'show_user.php',
data: {find_person:name, csrf_token:token},
success: function(data) {
$('#output').html(data);
}
})
})
</script>
show_user.php
if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
echo $_POST['csrf_token'] . '<br>' . $_SESSION['csrf_token']. '<BR>';
exit("invalid");
}
connect.php
$_SESSION['csrf_token'] = bin2hex(random_bytes(16));
Related
I'm trying to send a form via jquery ajax. I have this:
JS:
$('#form-pm').on('submit',function(e) {
e.preventDefault();
var formData = $('#form-pm').serialize();
var ajaxRequest =
$.ajax({
url: //my valid url,
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
type: 'post',
data: formData
});
ajaxRequest.done(function(data) { console.log(data); });
ajaxRequest.fail(function(jqXHR) { alert('You are fail. ' + jqXHR); });
});
UPDATE:
JS looks like this now:
var formData = $('#form-pm').serialize();
var ajaxRequest =
$.ajax({
url: admin_ajax.ajax_url,
type: 'post',
data: formData
});
ajaxRequest.done(function(data) { console.log(data); });
ajaxRequest.fail(function(jqXHR) { alert('You are fail. ' + jqXHR); });
e.preventDefault();
400 Bad Request is gone, but my function send_message is receiving blank parameters. According to error.log, it's send_message('',NULL,NULL)
PHP:
function send_message($projectid, $userid, $message) {
//do stuff
}
<form id="form-pm" method="post" enctype="multipart/form-data" action="">
<textarea name="message" rows=3 id="project-message"></textarea>
<input type="submit" name="send" value="send message">
<input id="userid" type="hidden" name="userid" value="<?php echo $userid; ?>">
<input id="projectid" type="hidden" name="projectid" value="<?php echo $projectid; ?>">
<input id="userid" type="hidden" name="action" value="send_message">
</form>
I keep getting POST 400 Bad Request. I know it's data that is causing trouble. How does post expect data to look like?
I have a php function:
<?php
function send_message($userid, $projectid, $message) {
//some code
}
$userid = '1';
$projectid = '2';
$message = 'hello';
?>
<form id="myform" method="post" action="">
<textarea name="message" id="project-message"></textarea>
<input type="submit" name="send" value="send message">
</form>
I want the submit button to do jQuery Ajax so my page won't refresh:
js:
$('#myform').on('submit',function(e) {
e.preventDefault();
$.ajax({
url: //my valid url,
type: 'post',
dataType : 'json',
data: {
action: 'send_message', //this is the PHP function
projectid: projectid //how do I write this?,
userid: userid //how do I write this?,
message: message//how do I write this?'
},
})
.done(function(data) { console.dir(data);; })
.fail(function(jqXHR) { alert('You are fail. ' + jqXHR); });
});
On my error.log, I get NULL for the 3 parameters because I'm not sure how to access them from my PHP. How do you access the PHP variables from jQuery?
Put your PHP variables into hidden inputs so they'll be automatically sent when it is submitted.
For example : <input type="hidden" name="userid" value="1">
Serialize the form data : var formData = $(form).serialize();
On submit attach your form data :
$.ajax({
url: admin_ajax.ajax_url,
type: 'POST',
data: formData
})
Access it from PHP with a classic way : $_POST['userid']
<form id="insert_form">
<textarea name="message" id="project-message"></textarea>
<input type="submit" name="send" id="send" value="send message">
<input type="hidden" name="userid" id="userid" value="<?php echo $userid= '1'; ?>">
<input type="hidden" name="projectid" id="projectid" value="<?php echo $projectid='2'; ?>">
<input type="hidden" name="message" id="message" value="<?php echo $message=
'hello'; ?>">
</form>
var project-message=document.getElementById('project-message').value;
var send=document.getElementById('send').value;
var userid=document.getElementById('userid').value;
var projectid=document.getElementById('projectid').value;
var message=document.getElementById('message').value;
$.ajax({
url:"your_url.php",
type:"POST",
data:$('#insert_form').serialize(),
success:function(data)
{
}
})
You can get all the values of the form, and submit it.
Also you can set other the values in the form as hidden.
<form id="myform" method="post" action="" id='form1'>
<textarea name="projectMessage" id="project-message"></textarea>
<input type="submit" name="send" value="send message">
<?php print "<input type='hidden' value='$userid' > "; name='userid' ?>
<?php print "<input type='hidden' value='$projectid' > "; name='projectid' ?>
<?php print "<input type='hidden' value='$message' > "; name='message' ?>
</form>
$('#myform').on('submit',function(e) {
e.preventDefault();
$.ajax({
url: admin_ajax.ajax_url,
type: 'post',
dataType:'json',
data: $("#form1").serialize(),
})
.done(function(data) { console.dir(data);; })
.fail(function(jqXHR) { alert('You are fail. ' + jqXHR); });
});
I like this approach because I can reuse the ajax multiple times or even create a generic function to submit the form on the background with ajax. Also I can fill the form using a for each loop in php, having all the values in an array (like a database result)
ex.
<?php
foreach($values as $k=>$v}{
print "<input name='$key' value='$v'>\n";
}
?>
I have a page with two forms and each form uses a different PHP page for its post. I can only find examples / documentation on using multiple forms with the same PHP post script. I am struggling to get this to work, can any help ?
This is the JQUERY, that works if i use one form, I've tried to add an ID tag but it didn't seem to work:
$(function () {
$('form').on('submit', function (e) {
var form = $(this);
e.preventDefault();
$.ajax({
type: 'post',
url: form.attr('action'),
data: form.serialize(),
success: function () {
alert('Suppiler Amended!');
}
});
});
});
</script>
</head>
<body>
<?php
echo "<div class='table1'>";
echo "<div class='datagrid'>";
echo "<table id='tblData2'><thead><tr><th>Notes</th><th>Updated By</th><th></th></thead></tr>";
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {
?>
<tbody><tr>
<td><FONT COLOR='#000'><b><?php echo "".$row["notes"].""?></td>
<td><FONT COLOR='#000'><b><?php echo "".$row["enteredby"].""?></td>
<td><FONT COLOR='#000'><b><a href="edit.php">
<form name="edit" action="script1.php" method="post">
<input type="hidden" name="notes" value="<?php echo"".$row["notes"]."";?>">
<input type="hidden" name="noteid" value="<?php echo"".$row["noteid"]."";?>">
<input type="submit" value="EDIT">
</form>
</a></td>
</tr></tbody>
<?php
$companyid = "".$row['id']."";
}
?>
</table>
</div>
<br>
<form name="notes" action="add-note.php" method="post">
ADD NEW NOTE:<br>
<input type="text" name="newnote" style="height:120px;width:200px;"><br>
<input type="hidden" name="companyid" value="<?php echo"".$companyid."";?>">
<input type="hidden" name="user" value="<?php echo"".$user."";?>">
<br>
<input type="submit" value="ADD NOTE">
</form>
You have to loop over your forms:
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$('form').each(function(i, form) {
$.ajax({
type: 'post',
url: form.attr('action'),
data: form.serialize(),
success: function () {
alert('Note has been edited!');
}
});
})
});
});
What you need to do is to simply get the action attribute dynamically. You can do that easily with form.attr('action'); inside the function. See bellow -
$(function () {
$('form').on('submit', function (e) {
var form = $(this);
e.preventDefault();
$.ajax({
type: 'post',
url: form.attr('action'),
data: form.serialize(),
success: function () {
alert('Note has been edited!');
}
});
});
});
Update:
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
</head>
<body>
<form name="edit" action="script1.php" method="post">
<input type="hidden" name="notes" value="1">
<input type="hidden" name="noteid" value="2">
<input type="submit" value="s1">
</form>
<form name="edit" action="script2.php" method="post">
<input type="hidden" name="notes" value="1">
<input type="hidden" name="noteid" value="2">
<input type="submit" value="s2">
</form>
<script type="text/javascript">
$(function () {
$('form').on('submit', function (e) {
var form = $(this);
e.preventDefault();
$.ajax({
type: 'post',
url: form.attr('action'),
data: form.serialize(),
success: function () {
alert('Note has been edited!');
}
});
});
});
</script>
</body>
</html>
I have a form in a modal window. When I submit the form through ajax I don't get the success message. My aim is to see the message created in the php file in the modal after submitting the form. Here is the code:
<p><a class='activate_modal' name='modal_window' href='#'>Sign Up</a></p>
<div id='mask' class='close_modal'></div>
<div id='modal_window' class='modal_window'>
<form name="field" method="post" id="form">
<label for="username">Username:</label><br>
<input name="username" id="username" type="text"/><span id="gif"><span>
<span id="user_error"></span><br><br>
<label for="email">Email:</label><br>
<input name="email" id="email" type="text"/><span id="gif3"></span>
<span id="email_error"></span><br><br>
<input name="submit" type="submit" value="Register" id="submit"/>
</form>
</div>
The modal.js
$('.activate_modal').click(function(){
var modal_id = $(this).attr('name');
show_modal(modal_id);
});
$('.close_modal').click(function(){
close_modal();
});
$(document).keydown(function(e){
if (e.keyCode == 27){
close_modal();
}
});
function close_modal(){
$('#mask').fadeOut(500);
$('.modal_window').fadeOut(500);
}
function show_modal(modal_id){
$('#mask').css({ 'display' : 'block', opacity : 0});
$('#mask').fadeTo(500,0.7);
$('#'+modal_id).fadeIn(500);
}
The test.js for the registration of the user
$(function() {
$('#form').submit(function() {
$.ajax({
type: "POST",
url: "test.php",
data: $("#form").serialize(),
success: function(data) {
$('#form').replaceWith(data);
}
});
});
});
And the PHP FILE
<?php
$mysqli = new mysqli('127.0.0.1', 'root', '', 'project');
$username = $_POST['username'];
$email = $_POST['email'];
$mysqli->query("INSERT INTO `project`.`registration` (`username`,`email`) VALUES ('$username','$email')");
$result = $mysqli->affected_rows;
if($result > 0) {
echo 'Welcome';
} else {
echo 'ERROR!';
}
?>
Try putting the returncode from your AJAX call into
$('#modal_window')
instead of in the form
$('#form')
BTW: Why not use the POST or GET method of jQuery? They're incredibly easy to use...
Try something like this.
First write ajax code using jquery.
<script type="text/javascript">
function submitForm()
{
var str = jQuery( "form" ).serialize();
jQuery.ajax({
type: "POST",
url: '<?php echo BaseUrl()."myurl/"; ?>',
data: str,
format: "json",
success: function(data) {
var obj = JSON.parse(data);
if( obj[0] === 'error')
{
jQuery("#error").html(obj[1]);
}else{
jQuery("#success").html(obj[1]);
setTimeout(function () {
jQuery.fancybox.close();
}, 2500);
}
}
});
}
</script>
while in php write code for error and success messages like this :
if(//condition true){
echo json_encode(array("success"," successfully Done.."));
}else{
echo json_encode(array("error","Some error.."));
}
Hopes this help you.
I want a code for get textbox value when submit button is clicked. It must be Ajax.Here is the code I tried so far.But I culdent get to work....
<form action="" method="post">
<p>Route No :
<input type="text" name="route_no" required="required" />
<input type="submit" value="Search" name="search" />
</form>
Ajax Code
<script type="text/javascript">
$(document).ready(function() {
$("#sub").click(function() {
var textboxvalue = $('name or id of textfield').val();
$.ajax({
type: "POST",
url: 'ajaxPage.php',
data: {txt1: textboxvalue},
success: function(result) {
$("div").html(result);
}
});
});
});
</script>
PHP code
$txt = null;
if((isset($_POST)) && (isset($_POST['txt1'])))
{
echo $txt = $_POST['txt1'];
}
HTML:
<label for="route_no">Route No:</label><input type="text" id="route_no" name="route_no" required="required" />
<input type="button" value="Search" id="search" />
<div id="result"></div>
JavaScript:
$(document).ready(function()
{
$("#search").click(function()
{
var textboxvalue = $('input[name="route_no"]').val();
$.ajax(
{
type: "POST",
url: 'ajaxPage.php',
data: {txt1: textboxvalue},
success: function(result)
{
$("#result").html(result);
}
});
});
});
ajaxPage.php:
if(isset($_POST) && isset($_POST['txt1']))
{
echo $_POST['txt1'];
}
You have problem here
$("#sub").click(function() {
you are using id ="sub" for submit button but you are not assigning id to that button so give id to submit button as id="sub".
To get the value of the textbox you can use:
$('#elementid').val()