I am trying to grab text from a text field and then use that to update my db with it. I have tried using session, get, post and cookie to grab the value using php and this doesn't work. I am new to php so I am thinking this comes out blank because it is server side. I did this with javascript and it grabs the value but I am not sure how to use it with php or to update mysql. any help is appreciated. here is some sample code of mine: I have the update on a seperate php page but the input of my text area is not even being grabbed
<?php
function update_db(){
// echo $_POST["comment"];
$nenabled = $_GET['enabled'];
$comments_new = htmlspecialchars($_GET['comment']);
$nemail = $_GET['email'];
echo ("<script>console.log('$comments_new')</script>");
?>
<form method ="get" action ="update_user.php">
<input type="hidden" name = "enabled" value = "nenabled">
<input type="hidden" name = "comments" value = "comments_new">
<input type="hidden" name = "email" value = "nemail">
<input type="submit" >
<script>
function doFunction() {
var com = document.getElementById("comment");
alert(com.value);
// var comment = '<?php update_db(); ?>';
}
</script>
You have something like :-
<input type="hidden" name = "comments" value = "comments_new">
Then how can you expect
document.getElementById("comment");
will work?
You should add the id in your html, like:-
<input type="hidden" id="comment" name = "comments" value = "comments_new">
You won't be able to call a PHP function from inside the javascript function. Once the page is rendered PHP can no longer modify the page since it is a server side language exclusively. There are two common ways to do this however, the first is to wrap your text input in a form and include a submit button that calls a php file with your code to insert the value into your database. There are plenty of good tutorials out there if you google them but http://html.net/tutorials/php/lesson11.php is a pretty good one.
The other way, and the way that sounds like it would work best for you, is to use AJAX to make a call to a php function. You never navigate away from your page and you can handle success and error conditions. AJAX supports GET and POST data to your php file. Again, not reinventing the wheel here is a great AJAX tutorial that spells out using GET and POST, single data, multiple items, return data, etc. http://hayageek.com/jquery-ajax-post/
Hope that helps!
If you want to update your database on submit of the form, then no need to import yout php code within javascript. You just need to send an AJAX request to your php server on submit your form. For the AJAX request you can also use jQuery.
At first you've to modify your html form like:-
<form onsubmit="return false;">
<input type="hidden" id="name" name = "enabled" value = "nenabled"></input>
<input type="hidden" id="comments" name = "comments" value = "comments_new"></input>
<input type="hidden" id="email" name = "email" value = "nemail"></input>
<input type="button" onclick="update()" value="Submit">
</form>
So, on click of the submit button the update function will be called. The update function will take the input values and call another function to send the AJAX request. So I wrote:-
<script type="text/javascript">
function update(){
var data = {
name : document.getElementById("name").value,
comments : document.getElementById("comments").value,
email : document.getElementById('email').value
};
loadXMLDoc(data);
}
//Ajax request function
function loadXMLDoc(data)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","updateDB.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("name="+data.name+"&comments="+data.comments+"&email="+data.email);
}
</script>
The AJAX request will send a POST request to
your base url + 'updateDB.php'
with data:-
name:nenabled,
comments:comments_new,
email:nemail,
So, now you can do the rest of the thing in the server side php code to update the database.
Related
I am trying to submit a form via ajax using the post method and a FormData object.
Here is a simplified version of the JavaScript:
var form=…; // form element
var url=…; // action
form['update'].onclick=function(event) { // button name="update"
var xhr=new XMLHttpRequest();
xhr.open('post',url,true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var formData=new FormData(form);
formData.append('update', true); // makes no difference
xhr.send(formData);
xhr.onload=function() {
alert(this.response);
};
};
The form has:
a button (type="button" name="update") to run the script
no action and method="get"
My PHP script has the following:
if(isset($_POST['update'])) {
print_r($_POST);
exit;
}
// more stuff
print 'other stuff';
When I try it, the PHP falls through to the rest of the code, and I get the other output, rather than what I expect from the print_r statement.
I have tried the following variations:
new FormData() (without the form). This does work if I add the update data manually.
new FormData(form). This does not work, whether I add the update manually or not.
changing the form method to post.
Firefox, Safari & Chrome on MacOS; all current versions.
The from itself looks something like this:
<form id="edit" method="post" action="">
<p><label for="edit-summary">Summary</label><input id="edit-summary" name="summary" type="text"></p>
<p><label for="edit-description">Description</label><input id="edit-description" name="description" type="text"></p>
<p><label for="edit-ref">Reference</label><input id="edit-ref" name="ref" type="text"></p>
<p><label for="edit-location">Location</label><input id="edit-location" name="location" type="text"></p>
<p><button type="button" name="update">OK</button></p>
</form>
What should I do to submit the get this to work?
No jQuery, please.
The content type when sending a FormData object is multipart/form-data not url encoded.
Further more the proper boundary must be set for the request, which the user is unable to do. For this XMLHttpRequest sets the correct content type with the required boundary.
So all you have to do is not set the content type and it'll work.
var xhr=new XMLHttpRequest();
xhr.open('post',url,true);
//xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");<--don't do this
var formData=new FormData(form);
formData.append('update', true); // makes no difference
xhr.send(formData);
xhr.onload=function() {
alert(this.response);
};
Change the name of the button to something other than "update" (and change it in your form['update'].onclick... as well). I think its clashing with the value you are trying to set on the FormData to trigger the PHP code.
I am trying to post data automatically with javascript and retrieve it in a PHP file, but the PHP file does not retrieve the data.
I created an automatic form which receives its input from another form and automatically sends it to another PHP file. But the next file pics.php does not receive the data. I only posted the relevant part of the code. First the HTML/javascript code.
<html>
<script type="text/javascript">
function submit()
{ document.getElementById("auto").click();
document.auto.submit();
}
</script>
<body onload="submit()">
<form name="auto" id="auto" action="pics.php" method="post">
<input type="hidden" name= "prodnm" value="<?php echo
$prodnm; ?>" /><br/>
<input type="hidden" name= "eigid" value="<?php echo $eigid;
?>" /><br/>
</form>
</body>
</html>
And this is part of the PHP code in file pics.php
<?php
require_once 'connect.php';
$prodnm = $_POST['prodnm'];
$eigid = $_POST['eigid'];
echo $prodnm;
echo $eigid;
?>
Help is very much appreciated. I've been at it for two days straight.
Am afraid the approach you are using is not advisable.
The form seems not to be getting the values you said are from another form(who does that anyway?).
Why not use a single form that has a submit button.
Define default values to you input fields(both visible and hidden, as you wish.)
Then use the JavaScript code to auto submit the default values on page load.
Remember, there are always better and less complicated ways to write codes for easy debugging.
Looking at the code above I cannot see why you could not send the data via an ajax request rather than trying to populate a form and then trigger the submit method somehow... Perhaps the following might be of interest in that regard.
/* replace the inline submit handler with a remote listener */
document.addEventListener('DOMContentLoaded', ()=>{
/* a very basic ajax function to send a POST request */
const ajax=function( url, params, callback ){
let xhr=new XMLHttpRequest();
xhr.onload=function(){
if( this.status==200 && this.readyState==4 )callback( this.response )
};
xhr.open( 'POST', url, true );
xhr.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
xhr.send( params );
};
/* for convenience, declare PHP variables as Javascript variables */
<?php
printf("
let prodnm='%s';
let eigid='%s';\n",
$prodnm,
$eigid
);
?>
/* Make the POST request to pics.php */
ajax( 'pics.php', 'prodnm='+prodnm+'&eigid='+eigid, r=>{
alert("Do something with result?\n\nResponse: "+r+"\n\nReload? Modify DOM?")
});
});
As the data exists in PHP at the point you are trying to POST the form and because there is no intended human interaction then you could use curl ( or similar ) and negate the need for this page.
Please forgive the basic question, I'm very new to Javascript and web development in general. I want to use a script on one page of my site to programmaticaly press a button to submit a form on another part of the site, making a POST request. The html I have to access is the following:
html
<form action="thing.jsp" method="post"> // Beginning of form
...
<input type="submit" id="submit" value="Do something"> // Button code
...
</form>
And I think the Javascript should look something like this:
JS
<script>
var xhr = new XMLHttpRequest();
xhr.open('POST', "/stuff.jsp", true);
var params = "???????"; // What do I need to put here?
xhr.send(params);
</script>
From reading around online, my suspicion is that I may just need to get the right value for params? Though if there's another way of achieving the same result (e.g. by just sending a POST request without doing anything to the button), I'd be perfectly happy to go with that.
Thanks in advance for your time and wisdom.
You don't need to use ajax, just use this:
<input type="button" value="GO" id="buttonId" />
<script>
function go() {
document.location.href = 'http://google.com';
}
document.getElementById('buttonId').onclick = go;
</script>
please notice the button type should be 'button', not 'submit'
Using jQuery - a JS library - you can simply send a HTTP GET Request. This can then be picked up in PHP using $_GET['key'] which will hold the value.
$(function() {
$('#unique-id-btn').click(function() {
$.get('file.php', { key: $('unique-id-input').val() }).done(function(response) {
alert(response);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="unique-id-input" placeholder="enter something...">
<button type="button" id="unique-id-btn">Click me</button>
Note, you will need to create the file.php. Inside, it will control what happens with that data being sent across, ie:
$data = $_GET['key'];
echo $data == "foo" ? "bar" : "tell me foo!";
Also note you can only run PHP in a .php file extension, not JSP.
I have a promotion page. I want that page to can be visited only by users that have a code from me sent by email.
So I have this form:
<form accept-charset="UTF-8" action="promotion.php" method="post" onSubmit="return checkcode(this);">
<input name="code" type="text" id="code" maxlength="15" placeholder="Confirmation Code" required="required" />
<input type="submit" value="Submit" />
</form>
And this Javascript:
function checkcode ( form )
{
var pattern = /name="code" value="|2222|1234|8888|"/g
if (!pattern.test(form.code.value)) {
alert( "The code is incorrect." );
form.code.focus();
return false ;
}
return true ;
}
This javascript code not functioning properly: if I write a bigger code with more characters will redirect; also I can't add many, if the numbers from value line come down when I write more codes/numbers will redirect, I need to add more than 100 codes. Is there any other way to get this to functioning properly? Maybe there is a PHP code that can read the codes from a file and redirect only if the code exist in that file?
And on JSFiddle redirect in any case, the javascript code just doesn't working. But if I upload on my server seems to work, but still has the error that I writed below. http://jsfiddle.net/focusoft/e9DHg/
Do like Akhil Sidharth suggests:
Make AJAX call to PHP page passing the promocode. Do validaton within the PHP and return true or false...
You do not need DB for this.
Oke, first thing, NEVER do validating like this in the javascript. This is visible for everyone! so UNSECURE! :)
How you should do this:
create a database table called codes with fields: code, email(if personal code) and code_active(boolean).
send the code (and email) using AJAX or just post it to the backend.
check in the backend if the code is valid and return true/false.
(if you don't want to use a database, then just hardcode the codes in a php array)
NO DATABASE:
<?php
$a_codes = array(1111,2222,3333,4444,5555);
if(isset($_POST['code'])){
if(in_array($_POST['code'], $a_codes)){
echo "VALID CODE";
}else{
echo "INVALID CODE";
}
}
?>
Please dont do this way, try to put all codes in DB & then using AJAX to validate the code will be a better idea. if validation success try making a changing a hidden input value to something for further population. Using JS like this is a very bad idea as its client side validation. please use server side validation.
check this code, if you use Jquery, it will shorten the code & make it better. I just used plain old simple Ajax.
index.php
<script type="text/javascript">
function GetXmlHttpObject(){
var xmlHttp=null;
try{
xmlHttp=new XMLHttpRequest();
}
catch (e){
// Internet Explorer
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function search_code(){
var parameter1= document.getElementById('code').value;
if (xmlHttps1==null){
alert ("Your browser does not support AJAX!");
return;
}
var url="ajax_validate.php?para1="+encodeURIComponent(parameter1)+"&search=search";
xmlHttps1.onreadystatechange=result_search_code;
xmlHttps1.open("GET",url,true);
xmlHttps1.send(null);
}
function result_search_code(){
if (xmlHttps1.readyState==4){
document.getElementById('Promotion_validation_Status').innerHTML="";
document.getElementById('Promotion_validation_Status').innerHTML=xmlHttps1.responseText;
}
}
var xmlHttps1=GetXmlHttpObject();
</script>
<form accept-charset="UTF-8" method="post" onSubmit="return validate()">
<input name="code" type="text" id="code" maxlength="15" placeholder="Confirmation Code" required="required" />
<input type="button" value="Submit" onClick="search_code()" />
</form>
<div id="Promotion_validation_Status" />
ajax_validate.php
<?php
if($_REQUEST['search']=='search'){
$promotion_code=mysql_real_escape_string($_REQUEST['para1']);
$sql="select count(*) from table where feild_name='".$promotion_code;
$res1=mysql_query($sql1);
$res1=mysql_fetch_array($res1);
if($res1['count(*)']>0){
echo "Sucess";
} else {
echo "Validation Failed";
}
}
?>
I think, this should give you an idea. Before you use ajax i will request to validate the format of your code using JS. so it will be easier for you to compare it with DB. This is just a basic outline for you to start this. There are so many things which i havent taken care of.
assuming your code and work, and just want to expand it.
You only need to change your regular expression.
/name="code" value="|2222|1234|8888|"/g
instead of this: |2222|1234|8888|
try this: [0-9]{4}
where: {number} (is the number of characters you admit)
this way you have a rando from 0000-9999 to validate codes.
name="code" value="[0-9]{4}"
in SO you can search for tags without pressing enter.
i want to know:
are the tags retrieved from the database or from a XML file?
is ajax involved?
i am new at front end. if ajax is involved. how should i write the code?
i want it to access a php file which returns the data. but im not familiar with how it works practically.
should the code look something like this:
<html>
<body>
<script type="text/javascript">
function ajaxFunction()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
document.myForm.time.value=xmlhttp.responseText;
}
}
xmlhttp.open("GET","time.php",true);
xmlhttp.send(null);
}
</script>
<form name="myForm">
Name: <input type="text" name="username" onkeyup="ajaxFunction();" />
Time: <input type="text" name="time" />
</form>
</body>
</html>
how do i send the text the user typed after he released the key to php? and how should i return the values after php has fetched the tags with SELECT. echo?
plz guide me a little. im so confused when front end is involved.
You can actually find that out yourself by using Firebug. You'll notice that typing a letter in the tag textbox will trigger a request to the server.
For example, the entry "C" will give you the following response from the server:
c#|48259
javascript|18318
c++|16999
asp.net-mvc|7224
c|6948
css|6563
The results are then interpreted within SO and then displayed with jQuery.
Using Firebug as you write an answer, you'll also notice that the client sends requests every minute or so:
POST answer-activity-heartbeat
This is also why you get notice that the question you are currently working on has been updated with new answers.
In general, using FireBug will really help you out understand how websites work. I recommend you start using it if you want to see a bit better how SO was conceived.
Regards
Looking at the firebug console, you can see that its sending and receiving data with ajax. Most likely to a script that fetches the data from a database.
You can do this with jQuery pretty easily.
<script type="text/javascript">
$("#username").autocomplete("search.php");
</script>
<form name="myForm">
Name: <input type="text" name="username" id="username" />
Time: <input type="text" name="time" />
</form>
<?php
//search.php
$q = $_GET['q']
$result = $db->query("SELECT username, id FROM users WHERE username LIKE '%$q%'");
while($user = $result->fetch_assoc()){
echo $user['username']."|".$user['id']."\n";
}
You can download the plugin here: http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/
and jQuery: http://jquery.com
I recommend that if your really need to know how it works take a look to JS documentation, but if what you need is doing if fast, use jquery and read the documentation (or buy a book like jQuery Reference Guide). It really simplifies the way to do AJAX and you could send back from the server anything you want, from JSON to HTML.
BTW, the way to know when a input box value has change to trigger the JS which does the AJAX request is using the onchange event of the input.