How can I use a variable from javascript in php? - javascript

I'm having a brain freeze at the moment..
I have a variable here in this bit of JavaScript code...
<script type="text/javascript">
$('#menuNameEdit').val(reservationId);
</script>
I have managed to use #menuNameEdit in form input as below but I don't know how to use it as a normal variable in PHP. For example if I want to compare it's value against another variable. Mind Block!
<input id="menuNameEdit" name="reservationId" type="text"
class="form-control" disabled>

You can't. It's just not possible. If JS starts with its work, PHP is already done.
The only way to do that - though its extremely vulnerable - is via AJAX:
$.ajax({
type: "POST",
url: "your_php_script.php",
data: {var: your_variable},
success: function() {
console.log("ajax successful!");
}
});
Without jQuery:
var request = new XMLHttpRequest();
request.open('POST', 'your_php_script.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(your_variable);
This needs to be in your_php_script.php:
$jsVariable = $_POST['var'];
This is extremely vulnerable though - always sanitize input via filter_var() or htmlspecialchars() which could be modified by the user!

<?php
if (isset($_POST['submit'])) {
$reservationId = $_POST['reservationId'];
$reservationId2= $_POST['reservationId2'];
//comparison
}
?>
<form class='addcategory' method="post" enctype="application/x-www-form-urlencoded">
<input id="menuNameEdit" name="reservationId" type="text"
class="form-control" disabled>
<input id="another" name="reservationId2" type="text"
class="form-control" >
<input name="submit" type="submit" value="submit">
</form>

If your form gets submitted you can access the below code:
PHP
if(isset($_POST['reservationId'])){
echo $_POST['reservationId'];
}
HTML
<form method="" action="" id="form-id">
<input id="menuNameEdit" name="reservationId" type="text" class="form-control" disabled>
<input name="submit" type="submit" class="form-control">
</form>
Jquery
var menuNameEdit = $('#menuNameEdit').val();
$.ajax({
type: "POST",
url: "index.php",
data: {menuNameEdit : menuNameEdit },
success: function() {
console.log("Success!");
}
});
index.php
echo $_POST['menuNameEdit'];

Related

How to get php page to receive ajax post from html page

I have a very simple form that has an input field for first name. I captured the form data and transmitted it via ajax to a PHP page using the standard jQuery posting method. However, I am not able at all get any responses from the PHP page that any data was captured on the server-side. I am not sure what I have done wrong or what is missing.
Here is my code.
Form:
<form action="process.php" method="POST">
<div class="form-group">
<div class="form-row">
<div class="col-md-6 mb-3">
<label for="firstName">First name</label>
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="First name">
<div class="d-none" id="firstName_feedback">
<p>Please enter a first name.</p>
</div>
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form</button>
</form>
Here is my Jquery Ajax call:
<script>
$(document).ready(function() {
$('form').submit(function(event) {
var formData = $("form").serialize();
console.log(formData);
$.ajax({
type: 'POST',
url: 'form.php',
data: formData,
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
</script>
And here is my PHP page:
if(isset($_POST['formData']))
$ajaxData = ($_POST['formData']);
echo $ajaxData;
{
}
In your Ajax function, you're passing the contents of formData to the server, though not as formData but as their original input name.
In this case, you have:
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="First name">
The input's name is firstName, so you need to call $_POST['firstName'] instead of $_POST['formData'].
if (isset($_POST['firstName'])) {
$ajaxData = $_POST['firstName'];
echo $ajaxData;
}
The same applies for any other field you would have in your form, so for example, having another input with the name lastName means you'd have to call $_POST['lastName'] to access it.
There were also some misplaced brackets and parentheses in the PHP code which I accommodated above.

Form submit only one value with AJAX passing form data to PHP in the same page

I need to pass a single value from my form to my php in the same page. It´s probably not an option to create another .php file and take the code there since there´s a lot going on.
This is the part of the code I need to fix, currently it only works when the code is on another file, since the $_POST is not messing around with other parts of the code. Specifically I need to manage to pass the 'client' or the 'empre' from the form alone to the php.
HTML
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
if($(".cliente").click(function() {
var name = $("#client").val();
var dataString = 'client='+ name;
}))else if($(".empresa").click(function() {
var name = $("#empre").val();
var dataString = 'empre='+ name;
}));
$.ajax({
type: "POST",
data: dataString});
});
</script>
</head>
<body>
<form>
<input name="client" type="text"><br>
<input class="cliente" type="submit" value="Buscar cliente"/><br>
<input name="empre" type="text"><br>
<input class="empresa" type="submit" value="Buscar empresa"/><br>
</form>
//PHP HERE
//HTML AGAIN
</body>
</html>
PHP (same page, just separating for readability)
if(isset($_POST['empre'])){
//DB QUERY
}
elseif(isset($_POST['client'])){
//DB QUERY
}
You can combine and send it in same AJAX call as below, and in PHP you can do:
$parameters = json_decode($_POST['params']);
$parameters would have all the variables sent in that AJAX call.
I would recommend, not to use same page for your AJAX. You should keep it in separate file. That would make code much cleaner, lighter, readable and easy-to-tweak.
$(function() {
$(".cliente, .empresa").click(function(e) {
e.preventDefault();
var paramsToSend = {};
if ($(this).hasClass('client'))
paramsToSend['client'] = $('form[name="client"]').serialize();
else
paramsToSend['empre'] = $('form[name="client"]').serialize()
$.ajax({
url: 'index.php' //assuming this is index.php (same page)
type: "POST",
data: {
params: JSON.stringify(paramsToSend)
},
success: function(data) {},
failure: function(error) {}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="client">
<input name="client" type="text" value="some value"><br>
<input class="cliente" type="submit" value="Buscar cliente" />
</form>
<form name="empre">
<input name="empre" type="text" value="some value"><br>
<input class="empresa" type="submit" value="Buscar empresa" />
</form>
//PHP HERE //HTML AGAIN
Why not use separate forms to process the data? (Your PHP logic mentioned will work with this proposed solution)
$(function() {
$(".cliente").click(function(e) {
e.preventDefault();
alert('Going to post data for client, check the console log now');
$.ajax({
url: $('form[name="client"]').attr('action'),
type: "POST",
data: $('form[name="client"]').serialize(),
success: function(data){
console.log(data);
},
failure: function(error){}
});
});
$(".empresa").click(function(e) {
e.preventDefault();
alert('Going to post data for empre, check the console log now');
$.ajax({
url: $('form[name="empre"]').attr('action'),
type: "POST",
data: $('form[name="empre"]').serialize(),
success: function(data){
console.log(data);
},
failure: function(error){}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form name="client" action="https://someurl.com/fileto.php">
<input name="client" type="text" value="some value"><br>
<input class="cliente" type="submit" value="Buscar cliente"/>
</form>
<form name="empre" action="https://someurl.com/fileto.php">
<input name="empre" type="text" value="some value"><br>
<input class="empresa" type="submit" value="Buscar empresa"/>
</form>

ajax isnt sending post request to php

Javascript doesn't send any post data to php file
$(document).ready(function(){
function showComment(){
$.ajax({
type:"post",
url:"process.php",
data:"action=showcomment",
success:function(data){
$("#comment").html(data);
}
});
}
showComment();
$("#button").click(function(){
var name = $("#name").val();
var message = $("#message").val();
var dataString = "name="+name+"&message="+message+"&action=addcomment";
$.ajax({
type:"post",
url:"process.php",
data:dataString,
success:function(data){
showComment();
}
});
});
});
form:
<form action="" method="POST" enctype="multipart/form-data">
name : <input type="text" name="name" id="name"/>
</br>
message : <input type="text" name="message" id="message" />
</br>
<input type="submit" value="Post" name="submit" id="button">
<div id="info" />
<ul id="comment"></ul>
</form>
php
$action=$_POST["action"];
if($action=="addcomment"){
echo "Add comment WORKS!";
}
if($action=="showcomment"){
echo "default";
}
Tried to add such lines as if post addcomment than show some words, just for a test since sql request didn't but php doesn't show any response at all, like there was no post action at all.
ps. I'm really new ajax so if possible show me a solution to solve it.
You're using a submit button so it will be making the form submit and reload which will bypass your ajax, you can change your jQuery to listen for the form submit event instead like this:
$("form").on('submit', function(e){
// Stop form from submitting
e.preventDefault();
var name = $("#name").val();
var message = $("#message").val();
var dataString = "name="+name+"&message="+message+"&action=addcomment";
$.ajax({
type:"post",
url:"process.php",
data:dataString,
success:function(data){
showComment();
}
});
});
Or simply change the button from type="submit" to type="button" or replace it with a element.
You are using submit button as Dontfeedthecode mentioned. Your form does not have any action so it is self posting. I have added action and id to the html form and a hidden field to pass the action. Now javascript serialize the form and send it to the process.php.
$(function () {
$("#my-form").on("submit", function (e) {
$("#action").val("addcomment");
$.ajax(
{
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (data) {
showComment();
}
});
return false;
});
});
<form action="process.php" method="POST" id="my-form" enctype="multipart/form-data">
<input type="hidden" id="action" name="action" value="" />
name : <input type="text" name="name" id="name" />
</br>
message : <input type="text" name="message" id="message" />
</br>
<input type="submit" value="Post" name="submit" id="button">
<div id="info" />
<ul id="comment"></ul>
</form>

how to get parameters in php page with ajax and $.post

actually i'm new to web and php,
i'm building a website,
i would like to introduce chat session there but, when the user click the insert button that's not working (failing to pass the paramerts to another page)
Help me out...!!!
here is the code
chat_page.php
<input type="text" id="txtmsg" name="txtmsg" size="25"> <input type="button" value="send" onclick="sndmsg()">
jscript.js
function sndmsg() {
msg=document.getElementById('txtmsg').value;
$.post("insert.php",{u:un,m:msg},function(){ });
document.getElementById('txtmsg').value="";
}
insert.php
include("connec.php");
$chatmsg=mysql_real_escape_string($_REQUEST['m']);
$uname=mysql_real_escape_string($_REQUEST['u']);
echo $chatmsg;
echo $uname;
mysql_query("INSERT INTO `mdi_chat_msg`(`uname`, `chatmsg` ) VALUES ( '$uname','$chatmsg')") or die(mysql_error());
What is un in jscript.js. Maybe, that parameter is unknown.
$.post("insert.php",{u:un,m:msg},function(){ });
You should declare un and msg variables;
var un, msg;
Check you have declare and change the type="submit" instead type="button" you cant use the word msg as variable and cant pass the js value in ajax and check un variable.
<form>
<input type="text" id="txtmsg" name="txtmsg" size="25"> <input type="submit" value="send" onclick="sndmsg()">
</form>
<script>
function sndmsg() {
msg1=$("#txtmsg").val();
$.post("insert.php",{u:un,m:msg},function(){ });
document.getElementById('txtmsg').value="";
}
$.ajax({
type: "POST",
url: "insert.php",
data: { u: un,m:msg1},
});
</script>

Add php variable to ajax call

I have a form on page 1 and I want to parse its variables to ajax call on page 2. The ajax call is triggered by on onload event.
Scenario:
Page1
<form id="form1"method="GET" action="page2">//send the variables to page 2
<input type="text" name="Place" value="city">
<input type="text" name="Type" value="room">
<input type="submit"></form>
page 2
<form name="myform2" id="myform2" method="GET">
<input type="text" name="Place" value="<?php echo $_GET[Place] ?>">//
<input type="text" name="type" value="<?php echo $_GET[Type] ?>">
<button id="submit2"type="submit" value="submit2" name="submit2" onclick="return ss()">
js1
$(document).ready(function(){ // load file.php on document ready
function sssssss2(page){
var form2 = document.myform2;
var dataString1 = $(form2).serialize() + '&page=' + page;
({
type: "GET",
url: "file.php",//
data: dataString1,
success: function(ccc){
$("#search_results").html(ccc);
}});}
sssssss2(1) ;
$('#search_results .pagination li.active').live('click',function(){
var page = $(this).attr('p');
sssssss2(page);
});
});
js2
function sss() {//serialize the form each time submitted.
var form2 = document.myform2;
var dataString1 = $(form2).serialize();
$.ajax({
type:'GET',
url: "file.php",
cache: false,
data: dataString1,
success: function(data){
$('#search_results').html(data);
}
});
return false;
}
The problem is the file.php doens't take the variable "city" and "room".I would like to parse the 2 variable to file.php when page2 load first time.
Hw to parse those variable on document load page2?
Shouldn't Place and Type be in quotes like
<input type="text" name="Place" value="<?php echo $_GET['Place'] ?>">//
<input type="text" name="type" value="<?php echo $_GET['Type'] ?>">
Here you miss a blankspace before 'method' and before 'type' attribute:
<form id="form1"method="GET" action="page2">
<button id="submit2"type="submit" value="submit2" name="submit2" onclick="return ss()">
Here you miss an action attribute:
<form name="myform2" id="myform2" method="GET">
This is wrong² because you miss a ; and you put a constant instead of a string in the index:
<?php echo $_GET[Type] ?>
correct:
<?php echo $_GET['Type']; ?>
In js1 you miss $.ajax({ + on line 4 ({ is not correct either.
Learn about valid HTML, proper PHP and some more basics I suggest, it can't work this way, especially not cross-platform compatible.
You can't copy scripts together from 100 tutorials and hope they will work, you have to know each command and line of code and what it does.

Categories

Resources