I have a php code that loops to create multiple separate forms with a submit button for each. I am trying to use JS to update the MYSQL with the form data without leaving the page
The Form (simplified)
<form name='myform'>
<SELECT class='index' NAME='album' id='album'>
<option value='1'>"PUBLIC"</option>
<option value='2'>"PRIVATE"</option>
<option value='3'>"FRIENDS"</option>
</select>
<input type="text" name="title" size="40" maxlength="256" value="">
<textarea name="caption" cols="37" rows="3"></textarea>
Photo Rating:
<input type="radio" name="rate" value="1">ON
<input type="radio" name="rate" value="0" checked>OFF
<input type="checkbox" name="del" value="1"> Delete Photo
<?php
<input type='submit' name='submit' value='Save changes to this photo' onClick=\"picupdate('include/picupdate.php', '1', 'picpg');\">";
?>
</tr></table></form>
The JS
function picupdate(php_file, pid, where) {
var request = get_XmlHttp(); // call the function for the XMLHttpRequest instance
var a = document.myform.album.value;
var b = document.myform.title.value;
var c = document.myform.caption.value;
var d = document.myform.rate.value;
var e = document.myform.del.value;
var the_data = 'pid='+pid+'&album='+a+'&title='+b+'&caption='+c+'&rate='+d+'&del='+e;
request.open("POST", php_file, true); // set the request
// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(the_data); // calls the send() method with datas as parameter
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
request.onreadystatechange = function() {
if (request.readyState == 4) {
document.getElementById(where).innerHTML = request.responseText;
}
}
}
The PHP for updating MYSQL
$pid=$_POST['pid'];
$album=$_POST['album'];
$title=$_POST['title'];
$caption=$_POST['caption'];
$rate=$_POST['rate'];
$del=$_POST['del'];
$db->query("UPDATE photos SET album = '".$album."', title = '".$title."', caption = '".$caption."', rate = '".$rate."' WHERE pid = '".$pid."'");
The reaction on submitting should be the MYSQL updating in the background with no changes to what the user sees. However it is not updating the MYSQL at all.
The problem is that you're not doing anything to prevent the browser from submitting the form when you press the submit button. There are two ways to do this. Without using jQuery, you can use the onclick property (sort of like what your'e doing), but you have to return a value of false, otherwise the form will be submitted in addition to whatever the onclick handler is doing. So:
<input type='submit' name='submit'
onclick=\"picupdate('include/picupdate.php', '1', 'picpg');\">
Is not doing the trick. What you need is:
<input type='submit' name='submit'
onclick=\"picupdate('include/picupdate.php', '1', 'picpg'); return false;\">
You can also modify your function, picupdate to return false, and then just do this:
<input type='submit'
onclick=\"return picupdate('include/picupdate.php', '1', 'picpg');\">
Lastly, if you want to use jQuery instead, you call preventDefault() against the event object when you handle the click event:
$(document).ready(function(){
$('input[name="submit"]').on('click', function(evt){
e.preventDefault(); // prevent form submission
picupdate('include/picupdate.php', '1', 'picpg');
});
I hope this helps!
Got it to work by changing the JS to
function picupdate(php_file, pid, where) {
var request = get_XmlHttp(); // call the function for the XMLHttpRequest instance
var a = document.getElementById('album').value;
var b = document.getElementById('title').value;
var c = document.getElementById('caption').value;
var d = document.getElementById('rate').value;
var e = document.getElementById('del').checked;
var the_data = 'pid='+pid+'&album='+a+'&title='+b+'&caption='+c+'&rate='+d+'&del='+e;
request.open("POST", php_file, true); // set the request
// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(the_data); // calls the send() method with datas as parameter
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
request.onreadystatechange = function() {
if (request.readyState == 4) {
document.getElementById(where).innerHTML = request.responseText;
}
}
}
Thanks all
Related
I have a array student. I need to pass this array in another php page via POST, not from GET, because it can contains thousands of characters.
I am trying to open new page sheet.php and echo the array student, I do simply checking echo $_POST['mnu'], but it is showing undefined index error.
var http = null;
if(window.XMLHttpRequest){
http = new XMLHttpRequest();
}
else{
http = new ActiveXObject('Microsoft.XMLHTTP');
}
http.open('POST','sheet.php',true);
http.setRequestHeader('Content-type','application/x-www-form-urlencoded');
http.onreadystatechange = function(){
if(http.readyState==4 && http.status==200){
window.open('sheet.php','_blank')
}
}
http.send('mnu='+JSON.stringify(student));
Like #RamRaider commented.. you're making two requests to sheet.php. The first being a "silent" POST request and the second being a GET request after the first POST request has successfully completed.
The second request won't share the payload of the first.
If I under stand correctly the below code should do what you are wanting...
// Create a form element
// <form action="sheet.php" method="post"></form>
var tempForm = document.createElement('form');
tempForm.setAttribute('action', 'sheet.php');
tempForm.setAttribute('method', 'POST');
tempForm.setAttribute('target', '_blank'); // Open in new tab
// Create an input field
// <input name="mnu" value="...">
var tempInput = document.createElement('input');
tempInput.setAttribute('name', 'mnu');
tempInput.setAttribute('value', JSON.stringify(student)); // Set field value
// Add the input to the form
tempForm.appendChild(tempInput);
// Add the form to the body in order to post
document.body.appendChild(tempForm);
// Submit the form
tempForm.submit();
// Remove the form
document.body.removeChild(tempForm);
And if you're using jQuery you can simplify the above code..
$('<form>', {
action: 'sheet.php',
method: 'POST',
target: '_blank',
html: $('<input>', {
name: 'mnu',
value: JSON.stringify(student)
}).prop('outerHTML')
}).appendTo($('body')).submit().remove();
Change http.send('mnu='+JSON.stringify(student)); to http.send(JSON.stringify(student));
And then in your sheet.php use json_decode($_POST) to fetch your POST data
want to create a fully dynamic chat UI for my website, But it reloads the whole page if a person submits the button page should not reload like many chat website.
<form action="action.php" method="post" id="formpost">
<input type="text" id="input" value="php echo">
<input type="submit" value="send">
</form>
I want to submit this form through ajax and show the last xml <message> containing <message>talk 123<message>
<messages category="short">
<person1>
<time>
r
<message>Djssjs</message>
</time>
</person1>
<person2>
<time>
r
<message>1234fdg</message>
</time>
</person2>
<person1>
<time>
r
<message> talk 123</message>
</time>
</person1>
</messages>
i want to show that talk 123 in the html document bit confused how to do that
//for form submit
$("#formpost").submit(function(e) {
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: action.php,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
//for xml
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "name.xml", true);
xhttp.send();
}
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var msg = "";
//how to select the last person's of the <messages> child
msg = getElementsByTagName("messages").lastChild.childNodes[1].nodeValue ;
document.getElementById("demo").innerHTML = msg;
}
$("#formpost").on('submit', function(event){
event.preventDefault();
// rest of your ajax code here...
});
Points to note
1. Make sure you have also added JQuery script source on the head tag of your chat page.
2. Make sure to put preventDefault() immediately before any other code is executed.
You can use reverse ajax method pulling data from the server.
In reverse ajax a request is auto-generated at a certain time interval or hold the request for fetching new message.
There are three technologies for reverse ajax:-
Piggyback
Polling
Comet
I'm trying to create a form on my website where a user has a text field that they can use to enter a registration number. I want the registration number to be added to the end of the action URL so when that page loads I can use PHP to explode the URL and grab the number. Here's an example of what I'm looking for...
<form action="http://mywebsite.com/registrations/123456789">
<input type="text" name="registrationnumber">
<input type="Submit" value="Submit">
</form>
Is it possible to take whatever is entered into the text field called registrationnumber and have it passed to the URL the form directs to? Maybe an easier way is to create a text field that has a button, when the button is clicked the URL is links to is dynamically created by adding the registrationnumber to the end.
Anyone know of a way to do this?
Indeed you don't need a form to make an AJAX call. A simple input and button will suffice.
I have made a function that will make AJAX call, it will convert the object params containing all key/value pairs of the parameters you want to send to PHP, and concatenates it into a URL string:
function ajax(file, params, callback) {
var url = file + '?';
// loop through object and assemble the url
var notFirst = false;
for (var key in params) {
if (params.hasOwnProperty(key)) {
url += (notFirst ? '&' : '') + key + "=" + params[key];
}
notFirst = true;
}
// create a AJAX call with url as parameter
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callback(xmlhttp.responseText);
}
};
xmlhttp.open('GET', url, true);
xmlhttp.send();
}
Assuming you have an input field:
<input id="code" type="text">
<button id="sendData">Send</button>
Here's how we can use the function ajax:
function sendData() {
parameters = {
inputValue: document.querySelector('#code').value
};
ajax('target.php', parameters, function(response) {
// add here the code to be executed when data comes back to client side
// e.g. console.log(response) will show the AJAX response in the console
});
}
You can then attach the button to sendData using an event listener:
document.querySelector('#sendData').addEventListener('click', sendData)
I have a server which I am storing standard text inputs once a submit button has been clicked, I have done this successfully and now need to recall all the inputs on a different button click. My lack of understanding of PHP starts to kick me as I have little to no idea how to retrieve this, I know that data within PHP files once ran is deleted so I need to create some sort of "storage" ( I found the use of $_SESSION to be the go to thing for this).
I then need to use my JS file to somehow recall the data that is temporarily stored but again have no idea how I can get an array that is stored on a PHP file across to a JS file.
Any brief explanation oh how this is done would be greatly appreciated as I am extremely new to PHP!
For reference I currently have:
JS:
function writeDoc() {
var xhttp = new XMLHttpRequest();
var url = "gethint.php";
var input = document.getElementById("text").value;
var clicker = document.getElementById("submit");
xhttp.open("POST", "gethint.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-
urlencoded");
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
alert("Form Was Submitted");
// var returnData = xhttp.responseText;
}
}
xhttp.send("input= " + input);
}
function readDoc() {
var xxhttp = new XMLHttpRequest();
xxhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
alert("Data retrieved")
// var returnData = xhttp.responseText;
}
}
xxhttp.open("GET", "gethint.php", true);
xxhttp.send();
}
HTML:
<body>
<label>Text Input To Save: </label>
<br></br>
<textarea rows="6" cols="20" id="text" name="textInput"></textarea>
<input type="submit" id="submit" onclick="writeDoc()">
<br></br>
<label>Retrieve Text :</label> <input type="button" id="getText"
onclick="readDoc()">
</body>
PHP:
<?
session_start();
echo $_SESSION["input_data"] = $_POST;
print_r($_POST);
echo "Text Submitted". $_POST["input"];
print_r($_REQUEST);
echo "Text Retrieved" . $_REQUEST["input"];
?>
In your php you can encode the post data as json like so:
$_SESSION['input_data'] = json_encode($_POST);
And in your js you can the get the data by decoding it like so:
var data = JSON.parse('<?php echo $_SESSION["input_data"]; ?>');
This will give you a js object that you can access using the name you gave your input tags in your html.
ex: data.textInput would get that value of the textarea.
To easily access the php data in js , you can store the data in session.also use json format to throw data to js and access it in js via jeson array key value format if you have multiple form field to store and access.
Use json_encode() to throw from php to js.
Also you can save this data in cookie. Session and cookie are temporary way to store data. For permanent storage use a database like mysql and call this from js with json.
I'm making a simple login page (backed by PHP and MySQL) to learn more about JavaScript and AJAX. I had it working with a form without a submit button, just a button with an onclick method call. However, I want it to be a submit button so hitting enter will call the function, and that seems the proper way to do things anyway. After endless research and trying to translate jQuery solutions, I still can't stop the form from submitting by default.
If I fill out the form with test data and submit, it submits the form with "?username=test&password=test&submit=Log+In" in the url and reloads the page, without displaying the message from the server. Why isn't the event preventDefault working? I've also tried this with adding the eventlistener to the form element with a submit event.
<?php
session_start();
if (isset($_SESSION['user']))
header("Location: home.php");
?>
<html>
<head>
<script>
document.getElementById('login_btn').addEventListener('click', login(event));
var request = new XMLHttpRequest();
function login(evt) {
evt.preventDefault();
var username = encodeURIComponent(document.getElementById('username').value);
var password = encodeURIComponent(document.getElementById('password').value);
request.open('POST', 'login.php', true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = process_login;
request.send('username=' + username + '&password=' + password);
}
function process_login() {
if (request.readyState == 4) {
if (request.status == 200) {
var response = request.responseXML;
var message = response.getElementsByTagName('message').item(0).firstChild.nodeValue;
if (message == '')
window.location = 'home.php';
else
document.getElementById('message').innerHTML = '<b>' + message + '</b>';
}
}
}
</script>
<title>Log In</title>
</head>
<body>
<h2>Please Log In</h2>
<form>
<table>
<tr><td>Username:</td><td><input type="text" name="username" id="username"></td></tr>
<tr><td>Password:</td><td><input type="password" name="password" id="password"></td></tr>
<tr><td><input id="login_btn" type="submit" name="submit" value="Log In"></td></tr></form>
<tr><td colspan="2"><div id="message" /></td></tr>
</table>
document.getElementById('login_btn').addEventListener('click', login(event));
You are calling login immediately and trying to use its return value (undefined since it has no return statement) as the event handler.
Remove (event) from there.
… at least that is what would happen if you weren't trying to call null.addEventListener. See this question and learn how to use the developer tools for your browser so you can see error messages from JavaScript.