AJAX PHP - Reload div after submit - php

I'm trying to reload a select with jquery and ajax, this select must be reload after I submit a new entry, right now I reach this point.
$("form").on("submit", function (e) {
e.preventDefault();
var form_id = $(this).attr('id');
var form_details = $('#' + form_id);
$.ajax({
type: "POST",
url: 'Users.php',
data: form_details.serialize(),
success: function (data) {
$('#check_data').html(data);
$('#div_to_update').load('my_page.php #div_to_update');
}
}
});
The div to be reloaded has a html select generate by a php code, the other fields are just plain html:
This is the first form, that must be reloaded with the values I enter in the form2:
<div id="div_to_update">
<form id="form1">
<?php Helper::combo_users(); ?>
/*
...
*/
</form>
</div>
This is the form 2:
<form id="form2" method="post">
<input type="text" id="user_reg" name="user_reg"/>
<input type="text" id="user_name" name="user_name"/>
<input type="submit" value="Add"/>
</form>
The odd thing is, this code will run the first time ok(I enter the values in the form2 and send, the form1 will reload with the new value), but the second time it does not work(when I click submit on the form2 nothing seems to happen) and the third time it will work again (click the submit button again and the value is send and the form 1 is reloaded) and so on.

Simply you are not working for second time since you are serializing a form which is dynamically updated within ajax.
jQuery won't serialize when you load a form elements such as inputs dynamically.
You're solution can be loading your new values with JSON object, and put in a foreach to display new content.

Related

ajax form submit -> receive respone from php

I've been reading multiple threads about similar cases but even now I'm still unable to do it correctly.
What I want to do
Basically, i.e. I have form which allows user to change his login (simply query to database).
PHP script looks like that:
if(isset($_POST['login'])) {
$doEdit = $user->editData("login", $_POST['login']);
if($doEdit) {
$result = displayInfobox('success', 'Good!');
} else {
$result = displayInfobox('warning', 'Bad!');
}
} else {
$error = 'Bad!';
echo $error;
}
displayInfobox is just a div with class i.e. success and content - Good!.
Right now I would like to send this form by AJAX and display $result without reloading page.
HTML:
<form id="changeLogin" method="post" class="form-inline" action="usercp.php?action=editLogin">
<label for="login">Login:</label><br />
<div class="form-group ">
<input type="text" class="form-control" name="login" id="login" required>
<input type="submit" value="ZmieƄ" class="btn btn-primary">
</div>
</form>
And finnally - my jquery/ajax:
$("#changeLogin").submit(function(e) {
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function(result) {
alert(result);
},
error: function(response) {}
});
e.preventDefault();
});
$("#changeLogin").submit();
If I leave "success" blank, it works -> form is submitted by ajax, login changed, but I do not see the result message. Otherwise whole page get reloaded.
Also, when I hit F5 form is being submited once again (even in Ajax).
I cant add comments because i do not have enough reputation but...
You should delete the last line with $("#changeLogin").submit();
And then in your php script file you should echo the result so you can get this result in ajax request. After that in your success method you have to read the result and (for example) append it somewhere to show the success or error box
I think you can use a normal button instead of submit button,just onclick can be an ajax request, the form should not be submitted,good luck.

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.

Form variables passed via jquery potential issue

I have a form for a mailing list script which I am trying to get working with ajax so the form can refresh without reloading. With the $.ajax part of the jquery commented out, the form variables are sent to the URL string.
?email=test%40address.com&sub=sub&submit=Submit+Form
My question is why is the submit=Submit+Form part there given that it isn't part of my "datastring" and will that be a problem when it comes to processing the actual PHP script?
Here is the form :
<form name="email_list" action="">
<p><strong>Your Email Address:</strong><br/>
<input type="text" name="email" id="email" size="40">
<input type="hidden" name="sub" id="sub" value="sub">
<p><input type="submit" name="submit" value="Submit Form" class="email_submit"></p>
</form>
and the JQuery
$(function() {
$('.email_submit').submit(function() {
var email = $("input#email").val();
if (name == "") {
$("input#email").focus();
return false;
}
var sub = $("input#sub").val();
if (name == "") {
$("input#sub").focus();
return false;
}
var dataString = '&email=' + email + '&sub=' + sub;
//alert (dataString);return false;
/*$.ajax({
type: "POST",
url: "mailing_list_add2.php",
data: dataString,
success: function() {
$('#display_block')
.hide()
.fadeIn(2500, function() {
$('#display_block');
});
}
});
return false;
});*/
});
You should put the submit handler on the form, not on the button, even if is a submit button.
<form name="email_list" action="" id="my_form">
Update the javascript
$(function() {
$('#my_form').submit(function() {
...
});
});
To serialize all the inputs into a string you could use $("#my_form").serialize() which builds a string with all the inputs and their data ready for posting:
var dataString = $("#my_form").serialize();
Also note that having a name attribute defined for the submit input means that its value will be sent also in the form. If you don't need that, you can simply remove the name attribute.
Submit+Form is the urlencoded version of Submit Form. The field submit is sent because you specify a name attribute to <input type="submit" name="submit" ... />. It will most likely not cause any problems for you (can't say without looking at your server-side code though).
Also, you really should specify a method attribute to your <form>. It seems to default to GET, which is why the form fields are added to the query string.
If you let your ajax POST happen, since you'r manually creating your dataString you won't see the Submit=, however when you let it submit 'normally' you see it, since the submit button is an input field with a value.
You won't encounter any issues with this. You can access the submit value just the same as any other POST value $_POST['submit'] though I'm not sure why you'd want to.

Enter to submit rather than refresh [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Enter button on Keyboard refreshes rather than submitting
I have the following form structure
structure of my form:
<form name="form">
<label>Name:</label>
<input type="text" name="name" id="id" size="50"/></br>
<label></label>
<input type="button" value="Get Info" onClick="get();">
</form>
<div id="age"></div>
My javascript for the get function is as follows:
function get() {
$.post('XXX.php', { name: form.name.value },
function(output){
$('#age').html(output).show();
});
}
Now when i use button(input type="button") to post information it works well,But when i fill the information and press enter on the keyboard page gets refreshed.
How can i make Enter button to post the info?
Many times the default behavior in a form when enter is pressed in a non-textarea field is to submit, even when a submit button was not pressed or even present.
Try this:
<form name="form" onsubmit="get();return false;">
In fact, using this technique, you would be able to change your input button to a submit to simplify the form with the same outcome:
<input type="submit" value="Get Info"/>
try return false; in your function. This will stop the button from having its usual behaviour:
function get() {
$.post('XXX.php', { name: form.name.value },
function(output){
$('#age').html(output).show();
});
return false;
}
I do it a little differently (which probably means its the wrong way). I dont make a form at all. I just create inputs, selects, etc.. and then when i do my POST i just get the values wen the function is called..
$.ajax({
type: "POST",
url: "someFile.php",
data: { 'name': $("#ElementID").val()},
success: function(data) {
//some function....
{
});
Hope that may be helpful....
I see you posted this as jQuery so I figured I'd give you a solution using that.
$('form[name=form]').submit(function(e) {
var $form = $(this);
$.post( $form.attr('action'), $form.serializeArray(), function( result ) {
$('#age').html( result ).show();
});
e.preventDefault();
});
This will keep you from having to create a crazy json object for the data parameter and from repeating yourself with the form's action attribute. This will also keep the browser's behavior where pressing enter when on an input will submit the form.
Here goes some code I have from an example earlier. The only thing in the form's action file is <?php print_r($_POST); ?>.

Problem using jQuery-AJAX to submit form to PHP and display new content in div without refreshing

I am trying to use jQuery-AJAX to submit the data in my form to my controller (index.php) where it is processed by PHP and inserted via PDO into the database if valid. Once the code is inserted into the database, the div where the form previously existed should be replaced by the contents of another page (newpage.php). The original page should not be refreshed upon submitting of the form, only the div where the form previously existed should be refreshed. There is a particular problem with my code, although I can't seem to find where the issue is at:
Here is my jQuery:
<script type="text/javascript">
function processForm() {
var action= $('#action').val();
var data = $('#data').val();
var dataString = 'action=' + action + '&data=' + data;
$.ajax ({
type: "POST",
url: ".",
data: dataString,
success: function(){
$('#content_main').load('newpage.php');
}
});
}
</script>
Here is my HTML: (As a side note, I noticed that when I take the "return false;" out of the HTML, that the form will submit to my database, but the whole page also reloads - and is blank. When I leave the "return false;" in the HTML, the newpage.php loads correctly into the div, but the data does not make it into the database)
<form action="" method="post" onsubmit="processForm();return false;">
<input type="hidden" name="action" value="action1" />
<input type="text" name="data" id="data" />
<input type="submit" value="CONTINUE TO STEP 2" name="submit" />
</form>
Here is my PHP:
<?php
$action = $_POST['action'];
switch ($action) {
case 'action1':
$data = $_POST['data'];
pdo ($data);
exit;
}
?>
I feel like I am making a silly mistake somewhere, but I just can't put my finger on it. Thanks for any assistance you can provide!
SOLUTION (via Jen):
jQuery:
<script type="text/javascript">
function processForm() {
var dataString = $("#yourForm").serialize();
$.ajax ({
type: 'POST',
url: ".",
data: dataString,
success: function(){
$('#content_main').load('newpage.php');
}
});
return false;
});
</script>
HTML:
<form id="yourForm">
<input type="hidden" name="action" value="action1" />
<input type="text" id="data" name="data" />
<input type="submit" value="CONTINUE TO STEP 2" name="submit" />
</form>
PHP:
<?php
$action = $_POST['action'];
switch ($action) {
case 'action1':
$data = $_POST['data'];
pdo ($data);
exit;
}
?>
What I learned: Use the .serialize() jQuery method if it is an option, as it will save a bunch of time writing out the var for each form value and .serialize() does not typically make mistakes sending the info to php.
Give this a try:
$("#yourForm").submit(function(){
// Could use just this line and not vars below
//dataString = $("#yourForm").serialize();
// vars are being set by selecting inputs by id but id not set in form fields
var action= $('#action').val(); // value of id='action'
var data = $('#data').val(); // value of id='data'
var dataString = 'action=' + action + '&data=' + data;
// dataString = 'action=&data=' so nothing is posted to db
// because input fields cannot be found by id
// fix by adding id fields to form fields
$.ajax ({
type: "POST",
url: ".",
data: dataString,
success: function(){
$('#content_main').load('newpage.php');
}
});
return false;
});
And change the form to (I added the id attributes):
<form id="yourForm">
<input type="hidden" id="action" name="action" value="action1" />
<input type="text" id="data" name="data" id="data" />
<input type="submit" value="CONTINUE TO STEP 2" name="submit" />
</form>
Seems like you need an explanation rather than a fix of code. Here is a brief explanation for the 2 cases:
When you take out return false; the code will treat your form as a normal HTML form that will be submitted to the server via action="", which leads to nowhere. The Javascript, however, also does its job in this case but because the page is redirected to nowhere, then it turns blank at the end.
When you put return false; back to the form, the form will catch the event handler and know that this form will be returned FALSE to submit. That's why you can see how your Javascript code does the job. However, one thing you should notice is that your jQuery AJAX function needs to POST (or GET) to a processing file, not '.'
Considering this reply based on no knowledge of your real situation. You need to look back over your code and see how you can edit it. Would be happy to reply if you have any questions.
Hope this small hint helps (:

Categories