I am trying to implement an autosave functionality using ajax and php. Here is my script:
function autosave() {
alert($("#myform").serialize());
$.ajax({
url: "form_creator.php",
data: $("#myform").serialize(),
type: 'POST',
success: function(data){
if(data && data == 'success') {
alert("saved");
// Save successfully completed, no need to do anything
}else{
alert(data);
// Save failed, report the error if you desire
// ....
}
}// end successful POST function
}); // end jQuery ajax call
// end setting up the autosave on every form on the page
}// end function autosave()
setInterval(autosave, 5000);
The problem is that I am getting different strings in the first alert and in the second one (in else section). In the first alert, the string seems to be correct with key=value&key2=value2.... but the second alert in else section gives me all html page. Is this correct behaviour? The autosave functionality doesn't work... Am I missing something?
<?php if((isset($_POST['sub'])) || (isset($_POST["autosave_check"])))
{ //save to db
}else{
?>
<form action="" method="post" id="myform" class="ajax_form" name="myform" enctype='multipart/form-data'>
<ul class="sorting dd-list" id="my_list">
//generate inputs
</ul>
<input type="hidden" name="chbox" class='hdbox' id="chbox" value="" />
<input type="hidden" name="save" value="<?php echo $idn?>" />
<input type="hidden" id="autosave_check" name="autosave_check" value="1">
<br class="clear" /> <br />
<div class="creator-buttons">
<h2 class="subheader-creator"> Akce </h2>
<table>
<tr>
<td>
<a href="javascript:;" class='radiusz addchbox' id="ch" value="Checkbox field"><?php echo $langa['formc'][10];?>
</a>
</td>
<td align='right'>
<input type="hidden" id="paths" value="<?php echo $patH?>" />
<input type="submit" name='sub' value='<?php echo $langa['formc'][13]?>' id="saveT" class='dugme1 submitforms' style="float:right;" />
</td>
</tr>
</table>
</div>
</form>
<?php } ?>
Its quite long code so just some parts.. Saving on button click works perfectly as for any other form.
Related
A form is dynamically created with PHP loop and presents one row from DB. I'm asking a user for input through prompt when he changes qty, but when I send it with AJAX to PHP it's empty. I guess it's because hidden input "new_message" is filled at the same time AJAX is sending values to PHP script so at that moment is blank. For the first row generated I get a message, but not for any other row.
Can you help me how to pass prompt input to PHP script?
//Update qty on article
$('.update_qty').on('change', function() {
var message = prompt("Upišite razlog za izmjenu količine:");
//e.preventDefault();
//Get message value
$('#new_message').val(message);
var data = $('#form1').serializeArray();
if (message != "" || message != NULL) {
$.ajax({
type: 'POST',
url: 'update_qty.php',
data: data,
success: function(data) {
alert(data);
}
});
} else {
alert("Empty");
e.PreventDefault();
return false;
}
});
<tbody>
<?php if (!empty($sales_plan_list)) {
foreach($sales_plan_list as $sales_key => $sales_value) {
?>
<tr class="new">
<td>
<a href="view_product_sales.php?id=<?php echo $sales_value['article_id']; ?>">
<?php echo $sales_value['article_no']; ?>
</a>
</td>
<td><?php echo $sales_value['description']; ?></td>
<td><?php echo myNumberFormat($sales_value['rrp']); ?></td>
<td>
<form name="form1" id="form1" method="POST" action="update_qty.php">
<input type="text" name="update_qty" class="update_qty" id="qty" value="<?php echo $sales_value['qty'] ?>"><?php echo ' Kom'; ?>
<input type="hidden" name="article_id" id="article_id" value="<?php echo $sales_value['article_id']; ?>">
<input type="hidden" name="sales_plan_id" id="sales_plan_id" value="<?php echo $sales_plan_id; ?>">
<input type="hidden" name="product_mix_id" id="product_mix_id" value="<?php echo $product_mix_id; ?>">
<input type="hidden" name="new_message" id="new_message" value="">
</form>
</td>
<td>
</td>
</tr>
<?php
}
}
?>
</tbody>
The problem is that you have multiple elements with the same id. You should NOT do that. You check the value in jQuery and then send different form data.
This is all just quessing, I am unable to check it. But try changing id to class and make sure that you send the right form data.
For example change this
<form name="form1" id="form1" method="POST" action="update_qty.php">
to this
<form name="form1" id="form<?= $sales_key; ?>" method="POST" action="update_qty.php">
I'm pulling an array of objects from my database and iterating through them using PHP to display a table. Each result row of the table has the option of deleting that particular record from the database. Each row is also an object, and the object type has a method that will delete itself from the database.
The problem I'm having is thinking through how to get this to work in the view. Right now if you click the delete button, it sets a POST variable to "delete" and reloads the same page wherein a listener process detects the variable and initiates the delete via a hidden input that contains the records database id.
This is all well and good, but these are all objects. Shouldn't each object be able to access it's own methods? It seems the only barrier to this is the interplay between PHP script and HTML forms. My code is below. Ideally, when the delete button is pressed, that particular instance of the object teamleader can run its method teamleader->delete_team_leader().
<?php foreach($teamleaders as $teamleader) { ?>
<tr>
<td><?php echo $teamleader->first_name; ?></td>
<td><?php echo $teamleader->last_name; ?></td>
<td><img src="<?php echo '../img/' . $teamleader->photo;?>" alt="" class="img-fluid tiny-tl-img"></td>
<td><?php echo nl2br(substr($teamleader->bio, 0, 100));?>...</td>
<td><?php echo $teamleader->url_name;?></td>
<form action="index.php?a=edittl" method="post">
<td>
<input type="hidden" name="id" value="<?php echo $teamleader->id?>">
<input type="submit" class="btn btn-default" name="edit" value="Edit">
</td>
</form>
<form action="index.php" method="post">
<td>
<input type="hidden" value="<?php echo $teamleader->id?>" name="id">
<input type="submit" class="btn btn-danger" name="delete" value="Delete" onclick="return confirm('Are you sure you want to delete this team leader?')">
</td>
</form>
</tr>
<?php } ?>
In your case, the best solution I think you can use ajax/jQuery for editing or deleting action.
You don't need to use many forms as now.
The code in front-end like this:
<head>
<script src="jquery.min.js"></script>
</head>
...
<?php foreach($teamleaders as $teamleader) { ?>
...
<td><?php echo $teamleader->url_name;?></td>
<td>
<input type="submit" class="btn btn-default btn-edit" name="edit" value="Edit" data-teamleaderid="<?php echo $teamleader->id?>">
</td>
<td>
<input type="submit" class="btn btn-danger btn-delete" name="delete" value="Delete" data-teamleaderid="<?php echo $teamleader->id?>">
</td>
</tr>
<?php } ?>
And the code with using ajax/jQuery is:
$(document).ready(function(){
$('.btn-delete').on('click',function(){
var _this = $(this);
var _teamleaderid = $(this).data('teamleaderid');
if (!confirm('Are you sure you want to delete this team leader?')) return false;
$.ajax(
url:'delete.php',
type:'post',
data: {
teamleaderid: _teamleaderid
},
dataType:'json',
success:function(data) {
if (data.return) {
$(_this).parent().parent().remove();/*Remove the current row in table html*/
alert('This teamleader has been deleted');
}
}
);
});
});
The delete.php code in backend is:
<?php
... #connect database
$teamleader_id = filter_input(INPUT_POST,'teamleader');
$check_delete = $dbconn->query("DELETE from teamleader_table WHERE id={$teamleader_id}");
print json_encode('return'=>$check_delete);
die();
?>
I have the code below that gets an id if there is any and asks you to click a button to show you data.
<input type="text" id="date" value="<?php echo $_GET['id']?>" class="css-input" placeholder="Posting Date..." readonly="readonly" /><br /><br />
<input type="button" id="validate" value="Let's get to work!" class="btn" />
The code below takes you to the data automatically without needing to click a button if there is an id there.:
jQuery(document).ready(function() {
jQuery("#validate").click();
});
How can I do an if statement that if #validate is not null then execute the jQuery code else don't. How could I do that whenever I do <?php if(#date != null) I get an error, any ideas?
<?php
if($_GET['id'] != NULL){
?>
<script>
jQuery(document).ready(function()
{
jQuery("#validate").click();
});
</script>
<?php }?>
</head>
I'm a complete Ajax newbie.
My non-ajax form currently looks like this:
<form id='myform' action=".htmlspecialchars($_SERVER["PHP_SELF"])." method='post''/>
<input type='hidden' name='id' value='$id' />
<td>
<input style='height:18px' type='date' name='date' value='$date' required/>
</td>
<td>
<select name='status' form='myform' required/>
<option>$status</option>
<option value='status_one'>status_one</option>
</select>
</td>
<td>
<input form='myform' type='text' name='memo' value='$memo'/>
</td>
<td>
<input form='myform' type='submit' value='Save' />
</form>
</td>
As the data is posted to the same page, the following code retrieves it upon submission:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//do stuff
}
This works fine, except that I want to be able to submit without refreshing the page, so the form info is submitted in the background. I know Ajax is the way to go here and I read lots about it, but I'm having trouble getting it to work. I'm unsure if the Ajax script is supposed to replace the retrieve part or it works in conjunction.
Much appreciated.
Use jQuery $.post
<script>
$(function(){
$("#submit").click(function()
{
var form = $("#myform").serialize();
$.post('url.php', form, function(data){
alert(data);
});
});
});
</script>
Note: You need to ID the submit button properly.
AJAX replaces the functionality of the submit button with other code that you have in javascript. #getvivekv's solution will work fine for you on that side.
The PHP server side will be easier to do if you separate it into a different script (or else put your ajax handling at the very top and exit; afterwards.)
You will fine life a lot less frustrating if you read through a good tutorial or another one before banging your head too hard against a new type of technology.
If you are doing AJAX for the first time I would actually recommend doing it in plain vanilla javascript so you know how to do it - then when you've got that figured out then see how it works in jquery.
Here's a quick example of how you could do this with keeping it all in one file using Ajax:
First, in the top of your page, add the logic that handles your form data:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// output for example
echo $_POST['id'] . "<br>";
echo $_POST['date'] . "<br>";
echo $_POST['status'] . "<br>";
echo $_POST['memo'] . "<br>";
//do stuff
}
?>
Following that you can add your ajax script:
<!-- remove jQuery if already included -->
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#myform').submit(function() {
$.ajax({
type:'POST',
url:'<?php echo $_SERVER["PHP_SELF"]; ?>',
data: $(this).serialize(),
success: function(data) {
$('#ajax-result').html(data);
}
});
return false;
});
});
</script>
The return false; will prevent the default form submission.
The .serialize() method creates a text string in standard
URL-encoded notation containing your form data.
The .html() method in the success: callback will return the
data to the specified element once processed by your script.
Then, add your form below that:
<?php if (empty($_POST)): ?>
<form id='myform' action="<?php echo $_SERVER["PHP_SELF"]; ?>" method='post'/>
<input type='hidden' name='id' value='$id' />
<td>
<input style='height:18px' type='date' name='date' value='$date' required/>
</td>
<td>
<select name='status' form='myform' required/>
<option>Option 1</option>
<option>Option 2</option>
</select>
</td>
<td>
<input form='myform' type='text' name='memo' value='$memo'/>
</td>
<td>
<input form='myform' name="submit" type='submit' value='Save' />
</form>
</td>
<?php endif; ?>
<!-- This is the div in which your data will be returned. -->
<div id="ajax-result"></div>
Just a note that there are various ways that this I would definitely encourage you to check out the tutorials mentioned here.
i'm creating my own MVC Framework.
I have a basic form in my view
<form action="?" method="post" >
<input type="hidden" name="envoie" value="envoie" />
<?php dico('INSCRIPTION_NOM'); ?><input id="name" type="text" name="name" /><br />
<?php dico('INSCRIPTION_EMAIL'); ?><input id="email" type="text" name="email" /><br />
<?php dico('INSCRIPTION_PWD'); ?><input id="pwd" type="password" name="pwd" /><br />
<input type="button" value="<?php dico('INSCRIPTION_SINSCRIRE'); ?>" onclick="verifForm(document.getElementById('email').value);"/>
</form>
when I clock on the button they have a javascript function like that :
function verifForm(email) {
var url ="?c=Inscription&a=VerifForm&email="+email;
$.get(url, function(data){
alert('resultat == '+data);
});
}
Inscription was my controllers and VerifForm an method of the controller. email was the value of a input.
The Php function was :
public function actionVerifForm() {
echo "OK";
}
When i click on the button i have all the code of the page on my alert but i only want the message "OK".
Thanks for helping me
what you are doing is AJAX, am i right? the data parameter IS your result. AJAX returns the echo-ed page as a string. if you mean to place it in the page, try jQuery .html() or .text() for a text only, escaped version.
function verifForm(email) {
var url ="?c=Inscription&a=VerifForm&email="+email;
$.get(url, function(data){
$('#container-id-here').html(data); //html insert
$('#container-id-here').text(data); //text insert
});
}
and in your PHP, since you are doing AJAX, you should only echo what you need returned, and not the whole HTML mark-up (which means no <html><head>...</head></html>