jquery post not working with HTML form - php

I am a beginner in Ajax and trying to build a simple ajax sample with jquery.
For some reason, my $.post is not working if I am putting my submit button in form tag.
Here is my creat_user.php:
<?php
$user_login = $_REQUEST['login_name'];
echo $user_login;
?>
Here is my html:
<form id='create_user_form'>
<p><label>Login Name : </label><input type='text' name = 'login_name'></p>
<p><label>Password : </label><input type='password' name='login_pw'></p>
<p><label>Re-Enter Password : </label><input type='password' name='login_pw2'></p>
<p><label>Email : </label><input type='email' name='email'></label></p>
<p><label>Date of Birth : </label><input type='date' name='date'></p>
<p><input type='submit' name='submit' id='create' value='create'></p>
</form>
And jquery:
$(document).ready(function(){
$("#create_user_form").submit(function(){
var serialize = $(this).serialize();
alert('Here');
$.post("create_user.php",serialize,function(response){
alert('Here2');
alert(response);
console.log("Response: "+response);
});
});
});
For some reason, the alert('Here2') is never fired, but it will work if I move the submit button out from the form tag, it works.(I do changed the selector in jquery code and changed submit() to click() ):
<form id='create_user_form'>
<p><label>Login Name : </label><input type='text' name = 'login_name'></p>
<p><label>Password : </label><input type='password' name='login_pw'></p>
<p><label>Re-Enter Password : </label><input type='password' name='login_pw2'></p>
<p><label>Email : </label><input type='email' name='email'></label></p>
<p><label>Date of Birth : </label><input type='date' name='date'></p>
</form>
<p><input type='submit' name='submit' id='create' value='create'></p>
SO, is that anything wrong from my code makes .post() not working if I put the submit button into form tag?

Maybe you need add
return false;
at the submit event?

You're missing return false or preventDefault() in the submit handler:
$("#create_user_form").submit(function(){
...
return false;
});
Or
$("#create_user_form").submit(function(e){
e.preventDefault();
...
});
This will prevent the browser from submitting the form after the ajax request is sent.

The default form submit is occurring prior to the Ajax call returning. You should prevent the default action of the form.
$(document).ready(function(){
$("#create_user_form").submit(function(e){
e.preventDefault(); //do not submit the form.
var serialize = $(this).serialize();
alert('Here');
$.post("create_user.php",serialize,function(response){
alert('Here2');
alert(response);
console.log("Response: "+response);
});
});
});

Related

Post form with ajax tab loading

I have a page with a POST form, when I submit the form the details are updated in a database.
And I have another page where I use AJAX TAB, which means I load the first page with AJAX, when I do this and use the Form, the details are not updated in the database.
I would appreciate help.
<?php
if( isset($_POST['newcst']) )
{
/*client add*/
//getting post from user add form
$c_name = $_POST['c_name'];
$c_adress = $_POST['c_adress'];
$c_idnum = $_POST['c_idnum'];
$c_phone = $_POST['c_phone'];
$c_mail = $_POST['c_mail'];
echo $c_num;
//insert client into SQL
$wpdb->insert('se_clients',array(
'c_name' => $c_name,
'c_adress' => $c_adress,
'user_id'=>$cur_id,
'c_num'=>$c_idnum,
'c_phone'=>$c_phone,
'c_mail'=>$c_mail,
));
}
?>
<html>
</head>
<body>
<div id="newcst">
<form action="" method="post">
<label>Full name:</label>
<input type='text' name='c_name' /><br><br>
<label>ID: </label>
<input type='text' name='c_idnum' /><br><br>
<label>PHONE:</label>
<input type='text' name='c_phone' /><br><br>
<label>ADRESS: </label>
<input type='text' name='c_adress' /><br><br>
<label>EMAIL: </label>
<input type='text' name='c_mail' /><br><br>
<input name="newcst" type="submit" value="create">
</form>
</div>
</body>
</html>
Ajax tab:
$(document).ready(function() {
$("#nav li a").click(function() {
$("#ajax-content").empty().append("<div id='loading'><img src='http://wigot.net/project/wp-content/themes/projthem/vendor/images/loader.gif' alt='Loading' /></div>");
$("#nav li a").removeClass('current');
$(this).addClass('current');
$.ajax({ url: this.href, success: function(html) {
$("#ajax-content").empty().append(html);
}
});
return false;
});
$("#ajax-content").empty().append("<div id='loading'><img src='http://wigot.net/project/wp-content/themes/projthem/vendor/images/loader.gif' alt='Loading' /></div>");
$.ajax({ url: 'invoice', success: function(html) {
$("#ajax-content").empty().append(html);
}
});
});
hover(), click(), bind(), on() and others works only after reloading page.
So you can use live()
or
$(document).on('click', 'element', function () {
...
});
I found the solution, you need to add the PHP code that is responsible for entering data to the database on the main page that contains the AJAX and not the page with the form itself.

how to post a field value which is available in iframe in php

How to post iframe value in php.
Example:
Username.php
<form action='data.php' method='post'>
<input type='text' name='username' id='username'>
<iframe src='password.php'></iframe>
<input type='submit'>
</form>
Password.php
<input type='text' name='password' id='passwprd'>
I want to post password and username value to data.php
You can do it without session or cookie but with pure javascript.Give your iframe an id.
<iframe id='iframePassword' src='password.php'></iframe>
You can grab username with this
var username = document.getElementById('username').value;
You can access the password field inside the iframe with this.
var ifr = document.getElementById('iframePassword');
var password = ifr.contentWindow.document.getElementById('passwprd').value;
Now make an ajax call with username and password.
try this,
<form action='data.php' method='post'>
<input type='text' name='username' id='username'>
<iframe id="iframe_pass" src='password.php'>
</iframe>
<input id="submit" type='button' value="submit">
</form>
<p id="password_from_frame"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$("#submit").on('click', function(){
var pass_field = $("#iframe_pass").contents().find("#password");
var username = $("#username");
var data = {username : username.val(), password : pass_field.val()};
// make an ajax call to submit form
$.ajax({
url : "data.php",
type : "POST",
data : data,
success : function(data) {
console.log(data);
alert(data);
},
error : function() {
}
});
});
// you can use keyup, keydown, focusout, keypress event
$("#iframe_pass").contents().find("#password").on('keyup', function(){
$("#password_from_frame").html($(this).val());
});
</script>
and password.php
<input type='text' name='password' id='password'>
and on the data.php use the print_r to send back the value to the ajax request
print_r($_POST);
If I understood your question correctly, you can store the username and password in PHP session variables and then you can fetch that data from session variables in data.php. As you have two values, its better to store them in an array and then assign the array to the session.

AJAX code not working on button click

Hi I am using AJAX for the first time and I'm watching this tutorial so I can implement the feature on my website: https://www.youtube.com/watch?v=PLOMd5Ib69Y. What I'm trying to do is make a contact us form where the user can write a message and when he click a button the message is sent to my email. With AJAX I'm trying to change the button content without reloading.
I have this AJAX code:
<script src="/js/jquery-1.4.3.min.js" type="text/javascript"></script>
<script>
var ajax =
{
send: function()
{
var userName = $("input[name=un]").val();
var userEmail = $("input[name=email]").val();
var userMsg = $("input[name=msg]").val();
if(userName == "" || userEmail == "" || userMsg == "")
{
alert("All fields are required!");
}
else
{
ajax.SetText("Sending...");
$.post("sendMSG.php", {
name : userName, email : userEmail, message : userMsg
}, function(data){
ajax.SetText(data);
});
}
},
SetText: function(text)
{
$("input[type=button]").val(text);
}
}
</script>
And the html form:
Name: <br> <input type="text" size="40" name="un">
<br>
Email: <br> <input type="text" size="40" name="email">
<br>
Write us a Message!
<br>
<textarea rows="4" cols="50" name="msg" id="content"></textarea>
<br/>
<input type="button" value="Send Message!" onClick="ajax.send()" />
For some reason when I click on the button nothings happens. As I said this is my first time using AJAX and I don't have idea how to use AJAX code. So please take it easy on me if the answer is simple :p
Thanks
You seem to be using a rather old version of jQuery. You should use the latest one which can be found on the jQuery Website.
Now for this example we'll use the submit event listener.
First you need to set up a form correctly:
<form id="myform" method="post">
Name: <br> <input type="text" size="40" name="un">
<br />
Email: <br> <input type="text" size="40" name="email">
<br />
Write us a Message!
<br />
<textarea rows="4" cols="50" name="msg" id="content"></textarea>
<br />
<input type="submit" value="Send Message!"/>
</form>
Now for the jQuery (as stated above; we'll be using the submit event.) But first we have to ensure the DOM element is loaded before running our jQuery. That is done by using:
$(document).ready(function(){});
Setting up our jquery is as simple as writing what we want to do in our submit event listener:
$(document).ready(function(){
$('#myform').submit(function(e){
e.preventDefault();
$.post('sendMSG.php',{name: userName, email: userEmail, message: userMsg}, function(data) {
console.log(data);
});
});
});
Obviously doing all the proccessing you require before running the $.post ajax request.
A Few Notes:
You could use e.preventDefault() or return false; within your event to stop the default actions taking place. (see below)
e.PreventDefault()
$('#myform').submit(function(e){
e.preventDefault();
// do ajax and processing stuff
});
return false;
$('#myform').submit(function(e){
// do ajax and processing stuff
return false;
});
You should look into using jQuery.ajax instead of the jQuery.post as it gives you more options.
I think you are using jquery,So you should put each code in
$(document).ready(function(){});

jQuery serialize form update MySQL based on form ID?

I populate a list of <form> using a PHP while loop, and fill the fields with values from MySQL. Now I want to be able to update all forms with one submit- button.
The form looks something like this in HTML (note, on my actual page there are multiple like this. The only thing that differes is the <form id='X'>:
<form id='34' name='customercontact' method='post' action='customerUpdate.php'>
Förnamn: <br /><input type='text' name='contact_firstname' class='textbox' value='text....'>
Efternamn: <br /><input type='text' name='contact_lastname' class='textbox' value='text....'>
Telefonnummer: <br /><input type='text' name='contact_phone' class='textbox' value='text....'>
Mobiltelefon: <br /><input type='text' name='contact_cellphone' class='textbox' value='text....'>
E-mail: <br /><input type='text' name='contact_email' class='textbox' value='text....'>
<select name='isActive'>
<option value="0" selected>Inaktiv</option>
<option value="1">Aktiv</option>
</select>
</form>
How do I use jQuery serialize to send each form and all the values as a string? I don'r really know where to start.
You can select all forms on the page $('form') and then iterate through them and 'submit' values via AJAX.
UPDATE:
<script type="text/javascript">
$(document).ready(function() {
$('#customer_contact_save').live('click', function(e){
e.preventDefault(); // prevent form submit
$.each($('form'), function(index) {
var sData = $(this).serialize(); // get data from form for submit
$.ajax({
type: "POST",// path to php script that saves data to db
url: "some.php",
data: sData,
success: function(someMessageFromPhp) {
alert(someMessageFromPhp); // alert to user what some.php returned
}
});
});
});
});
</script>

How to send value of checkbox and file from form with ajax

I have form and I want to send values from it with ajax to php script, but it doesn't send value of chceckbox if is it checked and doesnt't send file with avatar. So form send only values from text inputs, but not from checkbox and file. Can you help me please what is wrong?
Form:
<form action='' id='form1' method='post' name='form1' ENCTYPE='multipart/form-data'>
<input type='text' name='name' id='name' value=''>
<input type='text' name='age' id='age' value=''>
<input type='text' name='hobby' id='age' hobby=''>
<input type="checkbox" name="chkPHP" id="chkPHP" value="checked">
<input type='file' name='avatar' id='avatar' value='insert avatar' SIZE='30' accept=''>
<input type='submit' name='submit' id='submit' value='submit'>
</form>
Script to send values from form:
<script src="jquery.js" type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function(){
$('#submit').click(function() {
$('#waiting').show(0);
$('#form1');
$('#error').hide(0);
$.ajax({
type : 'POST',
url : 'pksZpacuj.php',
dataType : 'json',
data: {
name: $('#name').val(),
age: $('#age').val(),
hobby: $('#hobby').val(),
chkPHP: $('#chkPHP').val(),
avatar: $('#avatar').val()
},
success : function(data){
$('#waiting').hide(0);
$('#error').removeClass().addClass((data.error === true) ? 'error' : 'success')
.html(data.msg).show(0);
if (data.error === true)
$('#form1');
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(0);
$('#error').removeClass().addClass('error')
.text('There was an error.').show(0);
$('#form1');
}
});
return false;
});
});
</script>
In your ajax call, it may be easier to just send data: $('#form1').serialize() instead of each value separately.
FYI the file you send will be in the $_FILES array, not the $_POST in your php script.
Uploading files via AJAX is quite hard, and won't work in all browsers. I would strongly recommend against it.
If you really want to, you could follow this great post: http://net.tutsplus.com/tutorials/javascript-ajax/uploading-files-with-ajax/

Categories