Submitting a form via Ajax issue - php

I have a page that dynamically generates a list of items, in each one of those items is a button that submits a from containing data from that item in the list (that is sorted and working). I submit the form via this code (Jquery):
<script type="text/javascript" src="./js/jquery.form.js"></script>
<script type="text/javascript">
$('document').ready(function(){
$('#readlatersubmit').ajaxForm( {
target: '#result',
success: function() {
//$('#readlatersubmit').fadeOut('1000');   
//$("#loader").fadeOut();
}
});
return false;
});
</script>
When I click the button it submits the correct data and without the refreshing the whole page. The problem is that if I then go and click another one of the buttons in another one of the list items it goes to the form process page (does not submit via the Jquery).
Does anyone know how I can fix this issue?
Edit
This is what my form currently looks like:
<form id='readlatersubmit' action='RL.php' method='post'>
<input type='hidden' name='RLURL' value='".$item->get_link()."'/>
<input type='hidden' name='RLTitle' value='".$item->get_title()."' />
<input type='hidden' name='user-id' value='$loggedInUser->user_id' />
<input type='image' src='images/ReadLaterRibbon_Active.png' name='submit' value='Submit' class='button' />
</form>
<div id='result'></div>

Remove return false and let it check. because when you click on submit once, this will hold you on false but you don't need false, just remove return or use return true,
<script type="text/javascript" src="./js/jquery.form.js"></script>
<script type="text/javascript">
function doitRun() {
$('#readlatersubmit').ajaxForm( {
target: '#result',
success: function() {
//$('#readlatersubmit').fadeOut('1000');
//$("#loader").fadeOut();
}
});
}
</script>

Related

Redirecting to PHP page with post data format

I have seen many of the posts in stackoverflow but i'm unable to find my answers so thats why i'm posting here.
Scenario is this:
My Page is having many div containers and each div is having EDIT Button and when a user clicks EDIT of any DIV i want the user to be redirected to another page with ID of that DIV,
I want to do this whole this using POST method.
File edit.php
<button class="edit_btn" onclick="edit_ID('$btn_id')">
<script type="text/javascript">
function edit_ID(array){
$.ajax({ type:"POST",
url:'redirecter.php',
data:{editorID:array.split("_")[1]},
success:function(data){
//window.location.href="editapplication.php";
}
});
}
</script>
File redirector.php
<form action='editapplication.php' method='post' name='frm'>
<?php
foreach ($_POST as $a => $b) {
echo "<input type='hidden' name='".htmlentities($a)."' value='".htmlentities($b)."'>";
}
?>
</form>
<script language="JavaScript" type="text/JavaScript">
document.frm.submit();
</script>
you need to hook the click event of the button, and perform your actions there:
$(function() {
$('#buttonID').bind('click', function(event){
var id = $(this).parent().id;
$.ajax({....});
});
});

How to have two buttons in a same form to do different actions in ajax?

I have a form, which take name from form and it sends to javascript codes and show in php by Ajax. these actions are done with clicking by submit button, I need to have another button, as review in my main page. how can I address to ajax that in process.php page have "if isset(submit)" or "if isset(review)"?
I need to do different sql action when each of buttons are clicked.
how can I add another button and be able to do different action on php part in process.php page?
<script type="text/javascript">
$(document).ready(function(){
$("#myform").validate({
debug: false,
submitHandler: function(form) {
$.post('process.php', $("#myform").serialize(), function(data) {
$('#results').html(data);
});
}
});
});
</script>
<body>
<form name="myform" id="myform" action="" method="POST">
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value=""/>
<br>
<input type="submit" name="submit" value="Submit">
</form>
<div id="results"><div>
</body>
process.php:
<?php
print "<br>Your name is <b>".$_POST['name']."</b> ";
?>
You just need to add a button and an onclick handler for it.
Html:
<input type="button" id="review" value="Review"/>
Js:
$("#review").click(function(){
var myData = $("#myform").serialize() + "&review=review";
$.post('process.php', myData , function(data) {
$('#results').html(data);
});
}
);
Since you have set a variable review here, you can use it to know that is call has come by clicking the review button.
Bind the event handlers to the buttons' click events instead of the form's submit event.
Use the different event handler functions to add different pieces of extra data to the data object you pass to the ajax method.

JQuery and AJAX post to php without reloading page in Wordpress

I'm developing a plugin in Wordpress and am having difficulty trying to post data to a separate PHP file using Ajax without reloading the page. On the backend, the PHP file is relying on if( isset() ) to execute an SQL query. On the client side, the user should see individual records fadeOut and a message that records were successfully deleted.
UPDATE: The javascript is working so far, once the form button is clicked, the correct div-s fade in and fade out. However, the PHP file is not getting any value posted to it, as tested with a var_dump.
HTML Code:
<!-- problem: when setting "action" to a url, that page is automatically loaded. I want to stay on the existing page. -->
<form action='' id='form-delete-assoc' method='post'>
<input name='remove_all' type='submit' id='remove-all' value='Remove All'></input>
</form>
JQUERY: (updated with some fixes suggested by answerers)
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('tr.assoc_row').show();
$('#settings-removed-msg').hide();
$('#new-assoc-msg').hide();
$('#formdeleteassoc').submit(function(e){
e.preventDefault();
$.ajax ({
type: 'POST',
url: '<?php echo $cb_t2c_remove_all_url; ?>',
data: {removeall: 'yes'
},
success: function() {
$('#settings-removed-msg').fadeIn('fast');
$('tr.assoc_row').fadeOut('fast');
}
});
});
$('#formsavesettings').submit(function(){
$('#new-assoc-msg').fadeIn('fast');
});
});
</script>
remove_all.php:
<?php
//remove_all.php
global $wpdb;
$prefix = $wpdb->prefix;
$remove_var_dump = $_POST['removeall']; //returning NULL
var_dump($remove_var_dump);
if ( isset( $_POST['removeall'] ) ){
$wpdb->query("DELETE FROM ".$prefix."cb_tags2cats");
}
?>
Like the others said, you need to either return false or use preventDefault(). You should also move your calls to fadeOut and fadeIn into the success callback. If you don't and the request is unsuccessful for some reason, the user may be misled into thinking it was successful.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('tr.assoc_row').show();
$('#settings-removed-msg').hide();
$('#form-delete-assoc').submit(function(e){
// prevent the form from submitting normally
e.preventDefault();
$.ajax ({
type: 'POST',
url: '/delete-assoc.php', // Relative paths work fine
data: { removeall: 'delete-all' },
success: function(){
$('tr.assoc_row').fadeOut('slow');
$('#settings-removed-msg').fadeIn('slow');
}
});
});
});
</script>
Your form submit event needs to return false, to stop the form from actually submitting.
$('#form-delete-assoc').submit(function(){
... rest of your code here...
return false;
}
to post data to a separate php page without reloading current (parent or top) page, create a hidden iFrame and use it as the submit target. this type of solution allows posting and retrieving json responses. this snippet uploads a file to a php page.
<script type="text/javascript">
function init() {
document.getElementById('file_upload_form').onsubmit=function() {
document.getElementById('file_upload_form').target = 'upload_target'; //'upload_target' is the name of the iframe
}
}
window.onload=init;
</script>
</head><body>
<form id="file_upload_form" method="post" enctype="multipart/form-data" action="upload.php">
<input name="file" id="file" size="27" type="file" /><br />
<input type="submit" name="action" value="Upload" /><br />
<iframe id="upload_target" name="upload_target" src="" style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>
this tutorial explains the process step by step ->
http://www.openjs.com/articles/ajax/ajax_file_upload/
follow up on how to parse the response ->
http://www.openjs.com/articles/ajax/ajax_file_upload/response_data.php

Displaying jQuery UI dialog with multiple checkboxes

I'm trying to display multiple checkboxes and then submit the selected checkboxes as HTTP GET (i.e. as parameters in URL string) to the same script:
Here is my simplified test code - test.php:
<html>
<head>
<style type="text/css" title="currentStyle">
#import "http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css";
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() {
$('#name').dialog({ autoOpen: false, modal: true });
});
</script>
</head>
<body>
<form>
<p><input type="button" value="Select name"
onclick="$('#name').dialog('open');"></p>
<div id="name" title="name">
<?php
$NAMES = array(
'project one',
'project two',
'project three',
);
foreach ($NAMES as $name) {
printf('<p><label><input type="checkbox" name="name" value="%s">%s</label></p>',
urlencode($name),
htmlspecialchars(substr($name, 0, 120))
);
}
?>
</div>
<input type="submit">
</form>
</body>
</html>
But for some reason, when I select the first 2 checkboxes click the "Submit" button (sorry for the non-English name in the screenshot), then the script http://myserver/test.php? is being submitted and not http://myserver/test.php?name=project+one&name=project+two as I would expect.
If I get rid of all JQuery UI stuff, then it works.
What am I doing wrong? (besides using name="name" which is because that's a database table column name and doesn't seem to be the reason for this problem anyway)
UPDATE:
In my real program (not the above test case) I actually have several such dialogs and would like to set some settings in each dialog and only after that that click a Submit button. So the Submit button must be outside the dialog(s).
Thank you!
Assuming all the form inputs are checkboxes you can use the following to compile and submit the details as a GET.
using your original code add the following function
function compileInputs(){
var string = '';
var inputs = new Array();
//loop through all checkboxes
$(':checkbox').each(function(){
if($(this).is(':checked')){
inputs.push($(this).attr('name')+"="+$(this).val());
}
});
string = "?"+inputs.join("&");
window.location.replace(string);
}
you will need to change the names of the inputs from name='name' to name='name[]'
then change the submit to a button as follows:
<input type="button" onClick='compileInputs()' value='submit'>
you will no longer need the <form> tags
for a more selective approach:
//get all checkboxes from div#name
$('div#name :checkbox').each(function(){
if($(this).is(':checked')){
inputs.push($(this).attr('name')+"="+$(this).val());
}
});
//get all checkboxes from div#appsversion
$('div#appsversion :checkbox').each(function(){
if($(this).is(':checked')){
inputs.push($(this).attr('name')+"="+$(this).val());
}
});
//get all checkboxes from div#osversion
$('div#osversion :checkbox').each(function(){
if($(this).is(':checked')){
inputs.push($(this).attr('name')+"="+$(this).val());
}
});
You may need to wrap the whole form in a div and then dialog the new div in the dialog rather than just the div #name
Try this:
$("#submitButton").click(function(){
$("#formId").submit();
});
Should you not do name="name[]" . Then on the form submit (however you submit it (AJAX or non AJAX), you can get the "name" array as your post variable and handle it as you may wish. Correct me if I am wrong
Assuming the dialog is actually the problem, you may have to have your dialogs populate some hidden fields on the page to actually submit.
Here is a very simple sample to get you started.
http://jsfiddle.net/jUH9g/
When you click ok in the dialog it populates the 'names' textbox inside the form that actually gets submitted. In your real code you would change input type="textbox" to input type="hidden"
$("#dlg").dialog({autoOpen: false,
buttons: {
"OK": function () {
var names = "";
$("input:checkbox").each(function () {
if (this.checked) {
names += $(this).val() + ",";
}
});
$("#names").val(names);
}
}
});

jquery form plugin & programmatic submit

There are similar questions at SO, but none that seem to address this.
Below is a very simplified variant of my situation. Drupal/PHP site -- I have a form w/ submit button that I am using jquery.form plugin to ajax-ly submit. It works fine if I use the submit (#submit) button.
Now, I want to programmatically fire that button using another button (#submit2) outside of the form. I can do that using jquery click() function, but the content coming back isn't going to the ajax target as I would expect.
I do not have much freedom to re-organize this code, else i would.
(Note I tried to make this code easy for you to run by src-ing jquery and the form plugin from my website.)
Ideas? Thanks!
<?php
if ($_REQUEST['submit'] == 'Submit') {
print 'ajax returns ... ' . $_REQUEST['text'];
exit;
}
?>
<html>
<head>
<script type="text/javascript" src="http://enjoy3d.com/scripts/jquery-1.2.6.js"></script>
<script type="text/javascript" src="http://enjoy3d.com/scripts/jquery.form.js"></script>
<script type="text/javascript">
$(function() {
$('#form').ajaxForm( { target: $('#span') } );
$('#submit2').click( function() { $('#submit').click(); } );
});
</script>
</head>
<body>
<span id='span'>target span</span>
<form method='post' id='form'>
<input type='text' name='text' size='50' />
<input type='submit' id='submit' name='submit' value='Submit'/>
</form>
<input type='submit' id='submit2' name='submit2' value='Submit Too?' />
</body>
</html>
I managed to solve a similar situation to yours. If the only objective of simulating a click on submit1 is to submit the form, you might try:
$('#submit2').click(function() {
$('#form').trigger('submit');
});
You may also need to return false immediately after triggering the form submit button from the non-form submit button click event code. For example:
<script type="text/javascript">
$(function() {
$('#form').ajaxForm({ target: $('#span') });
$('#submit2').click(function() { $('#submit').click(); return false; });
});
</script>
It works for me. Is that what you are looking for?
Have you tried giving a name to the form, and instead of
$('#submit2').click( function() { $('#submit').click(); } );
doing
$('#submit2').click( function() { document.myForm.submit(); } );
That should do the same thing as having the submit button clicked if the form has been ajaxified.

Categories