So I am trying to submit a variable and the name of the variable via a form. I switched a button from submit to button because I need additional validation.
Anyway, here's the button now:
<button type="button" onclick="subForm()" name="del" id="deletebutton" value="'.$org.'">Delete</button>
Here's my current validation:
<script type="text/javascript">
function subForm()
{
if(confirm("Are you sure you want to delete this?"))
document.forms["addorg"].submit();
else
return false;
}
</script>
And here's my script on the other side:
if (isset($_POST["del"]) && ($_POST['del'] !== '')) {
$del = mysql_real_escape_string(html2txt($_POST['del']));
$resfile = mysql_query('SELECT file_loc from organization WHERE org_id = '.$del);
$org_name = mysql_real_escape_string(html2txt($_POST['orgname']));
if (!$resfile)
header('Location: '.$admin.'?error=query');
while ($filerow = mysql_fetch_array($resfile)) {
$fileplace = $filerow['file_loc'];
unlink(".".$fileplace);
rmdir($org_name);
}
mysql_query("DELETE from organization where org_id='".$del."'");
header('Location: '.$admin);
}
It is not currently deleting the records that I want. How do I pass along the "del" name to the other page?
You can use <input type="hidden">:
echo '<input type="hidden" name="org_id" value="'.$org_id.'" />'
This should render something like:
<input type="hidden" name="org_id" value="1" />
Using this code you can access the hidden field data using:
$org_id = $_POST['org_id'];
instead use onsubmit
<form method='POST' onsubmit='return subForm();'>
and
<script type="text/javascript">
function subForm()
{
if(confirm("Are you sure you want to delete this?"))
return true;
else
return false;
}
</script>
edit:
you can also change
if (isset($_POST["del"]) && ($_POST['del'] !== '')) {
to
if ( !empty($_POST['del']) ) {
but i think this line is your problem
$resfile = mysql_query('SELECT file_loc from organization WHERE org_id = '.$del);
try
$resfile = mysql_query("SELECT file_loc from organization WHERE org_id = '".$del."' ");
Looking at http://www.w3schools.com/tags/tag_button.asp suggests that the 'name' of a button isn't submitted as opposed to its 'value' or 'text'. Why not use an input of type hidden as just suggested?
I suggest you rethink using a form at all and consider AJAX. This would solve the problem of knowing which button was clicked and the page doesn't need to reload.
Here is a sample of what you're trying to do:
<html>
<head>
<script type="text/JavaScript">
var xmlhttp;
if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();
else
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
function deleteOrganization(orgID)
{
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
// in your PHP file, have it echo something like "SUCCESS" or "FAIL", and the response will be alerted here
alert(xmlhttp.responseText);
refreshList(); // either call another function to update the list or return the new list after the success/fail response.
}
};
xmlhttp.open("GET", "delete.php?orgID="+ orgID, true);
// OR - xmlhttp.open("GET", "page.php?action=DELETE&orgID="+ orgID, true);
xmlhttp.send();
}
function refreshList()
{
// either delete the row with JavaScript or make another AJAX call to get the new list after the entry was deleted.
}
</script>
</head>
<body>
<button onclick="deleteOrganization('<?php echo $org; ?>')">Delete</button>
</body>
</html>
Related
I've successfully wrote a working Ajax code, but the problem is that i can add an input field only once. I have a submit input, that calls Ajax script, everything works, the input text field appears, but after this if i want to add another text field by clicking on the submit input, it does not work. You only load once (YOLO). How do i write more awesome code that lets me add as many text fields as needed? Thanks for every reply. Here is my code:
index.php:
<head>
<script>
function ajaxobj(){
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('asd').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'ajaxAddInput.php',true);
xmlhttp.send();
}
</script></script>
</head>
<body>
<input type="submit" onclick="ajaxobj();">
<div id="asd"></div>
</body>
the php file:
<?php
echo '<input type=\"text\">';
?>
Simply use a standardized library, just like jQuery. With this in mind, you might use the following code:
$("#asd").on('change', function() {
var val = $(this).val();
$.ajax("ajaxAddInput.php", {input: val});
});
Alternatively, you can use the library with classes as well:
$('input[type=text]').on('change', function() {
var val = $(this).val();
$.ajax("ajaxAddInput.php", {input: val});
});
I am writing a program that gets information from forms using AJAX, and I was wondering if there was a way to make a button that clears the form and sort of resets the form. Right now if you press a button, the text won't disappear, but Im hoping to make a home button that would make the text disappear. I am just going to post my .html file because I think thats all we need. Let me know if there is more code you need. I tried making a reset button but it didn't seem to work.
<!DOCTYPE html>
<html>
<head>
<title>Assignment8</title>
<script src="ajax.js"></script>
<script>
function getXML() {
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get XML Document
var xmlDoc = xmlHttp.responseXML;
// Variable for our output
var output = '';
// Build output by parsing XML
dinos = xmlDoc.getElementsByTagName('title');
for (i = 0; i < dinos.length; i++) {
output += dinos[i].childNodes[0].nodeValue + "<br>";
}
// Get div object
var divObj = document.getElementById('dinoXML');
// Set the div's innerHTML
divObj.innerHTML = output;
}
}
xmlHttp.open("GET", "dino.xml", true);
xmlHttp.overrideMimeType("text/xml")
xmlHttp.send();
}
function getJSON() {
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get Response Text
var response = xmlHttp.responseText;
// Prints the JSON string
console.dir(response);
// Get div object
var divObj = document.getElementById('dinoJSON');
// We used JSON.parse to turn the JSON string into an object
var responseObject = JSON.parse(response);
// This is our object
console.dir(responseObject)
// We can use that object like so:
for (i in responseObject) {
divObj.innerHTML += "<p>"+responseObject[i].name + " lived during the " + responseObject[i].pet + "period.</p>";
}
}
}
xmlHttp.open("GET", "json.php", true);
xmlHttp.send();
}
</script>
</head>
<body>
<form>
<h3> Dinosaur Web Services </h3>
<div id="home"></div>
<button type="reset" value="Reset"> Home</button>
<div id="dinoJSON"></div>
<button type="button" onclick="getJSON();"> JSON Dinos</button>
<div id="dinoXML"></div>
<button type="button" onclick="getXML();"> XML Dinos</button>
</form>
</body>
</html>
Your reset-button should already do this, if its within the <form></form> or has the "form"-attribute, see here
You can either use the default reset button, if it is in between the form tag or you can use jquery to do this for you.
You just have to add an event on the click event of the home button and u can achieve what you want.
this is a reference which u can take
$(".reset").click(function() {
$(this).closest('form').find("input[type=text], input[type="password"], textarea").val("");
});
Add all other fields which u want to clear on click of the home button
I am thinking on how to implement this scenario:
I have a table orders where there is a serialNumber field. Then I also a have a PHP page with a form. What I am thinking of doing is that, onBlur or on keypress enter/return of a <input type=text> field, I would like an ajax/jquery script to check the serial number from the text box input if it has an existing record in my mySQL database. Then the script will warn the user that the serial number exists already in the database and will not allow submission.
I know how to implement it with standard form submission but I was thinking is it can be done without the literal pressing of the submit button.
Is there a way to implement this?
for this you can use javascript. create on javascript that called on textbox on blur event.
here i created on function that called on textbox on blur event.
function CheckUserName(){
var UserName = document.getElementById('UserName');
if(UserName.value != "")
{
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)
{
var value = xmlhttp.responseText;
if(value.length > 1)
{
document.getElementById('ErrorSpan').innerHTML="User Name Already exist please choose Other User Name";
UserName.focus();
}
else
{
document.getElementById('ErrorSpan').innerHTML="";
}
}
}
xmlhttp.open("GET","checkUserName.php?q="+UserName.value,true);
xmlhttp.send();
}
}
and create one php file with the name checkusername.php and pass your value through query string.
php code as follow.
<?php
$q=$_GET["q"];
include("db_connect.php");
$sql="select * from usermaster where UserName='".$q."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo $row['UserName'];
}
mysql_close($con);
?>
here from php if username find it will return value and you can get value in your javascript function. i hope it will help you.
you can also use this method I checked it on keyup you can use it via onblur option.
<input type="text" value="" id="jform_domain_name" name="jform[domain_name]" onkeyup="checkAvailability();"/>
<div id="errormsg" class="no-display">Sorry, this name is not available!</div>
<div id="successmsg" class="no-display">Congratulations, this domain is available!</div>
<script>
function checkAvailability(){
jQuery('#ajaxloader').html('<img src="images/ajax-loader.gif" />');
var string = jQuery('#jform_domain_name').val();
if(string == ''){
jQuery('#ajaxloader').html('');
return false;
}
jQuery.ajax({
type : "POST"
,url : "YOUR_ACTION_URL"
,data :"string="+jQuery('#jform_domain_name').val()
,success : function(data){
if(data==0){
var errormsg = jQuery("#errormsg").html();
jQuery("#ajaxloader").show();
jQuery('#ajaxloader').html(errormsg);
}else{
var successmsg = jQuery("#successmsg").html();
jQuery("#ajaxloader").show();
jQuery('#ajaxloader').html(successmsg);
}
}
,complete : function(){
if( jQuery('#jform_domain_name').val() == "" ) {
jQuery("#ajaxloader").hide();
}
}
,beforeSend: function(html){
jQuery("#ajaxloader").show();
jQuery('#ajaxloader').html('<img style="padding-top:6px;" src="images/ajax-loader.gif" />');
return;
}
});
}
</script>
for reference I am providing my controller action and the model which I have used
//sample controller action
function checkdomain(){
$requestData = JRequest::get();
$return = $model->checkAvailabiLity($requestData['string']);
if($return === false){
echo 0;
}else{
echo 1;
}
die;
}
//sample model on which I created Query logic.
public function checkAvailabiLity($data){
$select = "SELECT id FROM #__jshopping_vendors WHERE domain_name = '".strtolower($data)."' AND user_id != ".$user->id."";
$db->setQuery($select);
$type = $db->loadObject();
if(isset($type->id) && $type->id >0){
return false;
}else{
return true;
}
}
hope this helps....
I am a beginner and I am trying to learn how to add, delete, retrieve and update a database using PHP and Ajax.
At this time I have accomplished how to retrieve and delete so I am trying to update some values. For retrieving data, I just pass the selected ID I want, so I can retrieve the data. Same goes for delete, I just assign which ID I want to delete. Now to update there are more things going on, its where I cant find the solution.
This is my Form:
<form onsubmit="updateuser()">
ID Number: <input name="ud_id"><br>
First Name: <input type="text" name="ud_first"><br>
Last Name: <input type="text" name="ud_last"><br>
<input type="Submit" value="Update">
</form>
and this is my javascript:
function updateuser() {
var str = $('.ud_id').attr('value');
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtuser").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ajaxupdate.php?q=" + str, true);
xmlhttp.send();
}
I think the problem comes because my form ajaxupdate.php file doesn't retrieve the First and Last name values from the form. It's like I am not passing them (?).
Here is my ajaxupdate.php file:
<?php include("connection.php");
$id=$_GET['ud_id'];
$first=$_GET['ud_first'];
$last=$_GET['ud_last'];
$query="UPDATE contacts SET first='$first', last='$last' WHERE id='$id'";
mysql_query($query);
mysql_close();
?>
What I'm I doing wrong so that I can update the value first and last of database for a specific ID ?
Try this code
<script type="text/javascript">
function updateuser() {
var ud_id = document.getElementById('ud_id').value;
var ud_first = document.getElementById('ud_first').value;
var ud_last = document.getElementById('ud_last').value;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtuser").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ajaxupdate.php?ud_id=" + ud_id + "&ud_first="+ud_first+"&ud_last="+ud_last, true);
xmlhttp.send();
}
</script>
HTML
<form name="test">
ID Number: <input name="ud_id"><br>
First Name: <input type="text" name="ud_first"><br>
Last Name: <input type="text" name="ud_last"><br>
<input type="button" onClick="updateuser()" value="Update">
</form>
In your javascript, do this
function updateuser() {
var ud_id = $('input[name="ud_id"]').val();
var ud_first = $('input[name="ud_first"]').val();
var ud_last = $('input[name="ud_last"]').val();
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtuser").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ajaxupdate.php?ud_id=" + ud_id + "&ud_first="+ud_first+"&ud_last="+ud_last, true);
xmlhttp.send();
}
If you want to use the updateuser() function on submit, then it must prevent the form from actually submitting. Make it return false, otherwise the form gets submitted by the browser before the function has time to execute.
The browser runs the function before submitting the form (that's how on submit works). If the function doesn't return false, then it interprets that as "everything is OK, you can safely submit the form". The form then gets submitted as usual.
In the mean time, the function initiates the asynchronous request. But since the browser has already submitted the form, now you're on a totally different page, thus the connection and the asynchronous request get disconnected and most likely ignored (unless of course the request made it before the page was changed, in which case both requests are processed).
As an alternative, you could execute the function without placing it in the on submit event. See sam_13's answer.
Check this it will work as expected
ud_id = document.getElementById('ud_id').value;
ud_first = document.getElementById('ud_first').value;
ud_last = document.getElementById('ud_last').value;
xmlhttp.open("GET", "ajaxupdate.php?ud_id=" + ud_id +"&ud_first=" +ud_first+ "ud_last="+ud_last, true);
<form onsubmit="updateuser()">
ID Number: <input name="ud_id" id="ud_id"><br>
First Name: <input type="text" name="ud_first" id="ud_first"><br>
Last Name: <input type="text" name="ud_last" id="ud_last"><br>
<input type="Submit" value="Update">
</form>
I came accross this example because i am also running into a similar issue. however I couldnt help but notice that you do not specify a method for your form and your AJAX is assuming it should use the GET method. just food for thought... cheers
This code is tested and works. I needed to do the same thing, update MySql with ajax and combining the above with a wider research I got this to work.
The php file is called ajaxupdate.php:
<?php
$id= $_GET['ud_id'];
$first= $_GET['ud_first'];
$last= $_GET['ud_last'];
require_once ('mysqli_connect.php'); //connection to the database
$sql = "UPDATE contacts SET FirstName ='$first', LastName='$last' WHERE id='$id'";
$result = mysqli_query($dbc,$sql);
mysqli_close($dbc);
?>
The Html file called anyNameYouWish.html:
<html>
<head>
</SCRIPT>
<script language="javascript" type="text/javascript">
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
function MsgBox (textstring) {
alert (textstring) }
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var ud_id = document.getElementById('ud_id').value;
var ud_first = document.getElementById('ud_first').value;
var ud_last = document.getElementById('ud_last').value;
var queryString = "?ud_id=" + ud_id + "&ud_first="+ud_first+"&ud_last="+ud_last;
ajaxRequest.open("GET", "ajaxupdate.php" + queryString + "&random=" + Math.random(), true);
ajaxRequest.send(null);
}
</script>
</head>
<body>
<form method="post" name="test" onsubmit="ajaxFunction()">
ID Number: <input id="ud_id" name="ud_id"><br>
First Name: <input id="ud_first" type="text" name="ud_first"><br>
Last Name: <input id="ud_last" type="text" name="ud_last"><br>
<input type="submit" value="Update">
</form>
</body>
</html>
This is a Google suggestion-like script.
I rewrote the AJAX Call code by splitting it up into multiple functions and seems this is a better cross-browser/usability approach. Now I need to pass the input variable that I read from the input #search_text to a php file where I actually fetch the data from database.
For moment all I need is to pass search_text and display it with echo $_GET['search_text'];
Can someone help me?
Here is the script
<script type="text/javascript">
/*note xmlHttp needs to be a global variable. Because it is not it requires that function handleStateChange to pass the xmlHttp
handleStateChange is written in such a way that is expects xmlHttp to be a global variable.*/
function startRequest(getURL){
var xmlHttp = false;
xmlHttp = createXMLHttpRequest();
//xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.onreadystatechange=function(){handleStateChange(xmlHttp);}
xmlHttp.open("GET", getURL ,true);
xmlHttp.send();
}
function createXMLHttpRequest() {
var _msxml_progid = [
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP.3.0',
'MSXML3.XMLHTTP',
'MSXML2.XMLHTTP.6.0'
];
//req is assiqning to xmlhttp through a self invoking function
var xmlHttp = (function() {
var req;
try {
req = new XMLHttpRequest();
} catch( e ) {
var len = _msxml_progid.length;
while( len-- ) {
try {
req = new ActiveXObject(_msxml_progid[len]);
break;
} catch(e2) { }
}
} finally {
return req;
}
}());
return xmlHttp;
}
//handleStateChange is written in such a way that is expects xmlHttp to be a global variable.
function handleStateChange(xmlHttp){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
//alert(xmlHttp.status);
//alert(xmlHttp.responseText);
document.getElementById("results").innerHTML = xmlHttp.responseText;
}
}
}
function suggest() {
startRequest("ajax-submit.php");
}
</script>
<body>
<form action="" name="search" id="search">
<input type="text" name="search_text" id="search_text" onkeydown="suggest();" />
</form>
<div id="results" style="background:yellow"></div>
</body>
and the php file is:
<?php
echo 'Something';//'while typing it displays Something in result div
//echo $_GET['search_text'];
?>
Thanks
The issue is that you're not actually passing in any data to the PHP script. In this case, you need to stick the 'search_text' parameter on the end of the URL, since you're expecting it to be a GET request.
startRequest("ajax-submit.php");
should be
startRequest("ajax-submit.php?search_text="+document.search.search_text.value);
this jQuery Solution is way easier and Cross-Browser compatible:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready( function(){
$('#search_text').keydown(function(){ // Bind event to KeyDown
var search_text = $(this).val(); // get value of input field
$.ajax({ // fire Ajax Request
url: "ajax-submit.php?search_text=" + search_text,
success: function(result){
$("#results").html(result); // on success show result.
}
});
});
});
</script>
<body>
<form action="" name="search" id="search">
<input type="text" name="search_text" id="search_text" />
</form>
<div id="results" style="background:yellow"></div>
</body>