Ajax prevent form action and post form data - php

I have been searching through examples for days trying to troubleshoot my simple email signup form. I am trying to just submit an email to a database without leaving or reloading the current page. I am able to insert new data to my database, but not through my Ajax function. I am starting to think that my Ajax function is not being called, because even with the event.preventDefault(); function, my page is redirected to the .php file. I have listed my script below which currently resides in the <head></head> section of my HTML.
<script type="text/javascript">
$(document).ready(Function() {
$("#submitbtn").click(function(event) {
event.preventDefault();
var form = $(this),
emailcode = form.serialize(),
formUrl = form.attr('action'),
formMethod = form.attr('method');
/* responseMsg = $('#signup-response') */
if ( formData.length===0 ) {
function(msg){
alert('Invalid Email');
}
return false;
} else {
//send data to server
$.ajax({
url: formUrl,
type: formMethod,
data: emailcode,
success:function(data){
alert('Email Saved');
}
return false;
});
};
});
});
HTML
<form class="col-lg-5 form-group pull-right well" id="emailform" action="collector.php" method="POST" style="padding-top:6px;">
<label for="email-input">Sign up to receive updates</label>
<input type="email" class="form-control" id="emailcode" placeholder="Email" name="emaildata" autofocus></input>
<button type="submit" id="submitbtn" class="btn btn-success" style="width:60%">Sign Up</button>
</form>
PHP
$emailcode = $_POST['emailcode'];
//Fetching from your database table.
$query = "INSERT INTO EmailCollector (EmailID, EmailCode, Active)
VALUES (NULL,'$emailcode', 0)";
$result = mysql_query($query);
mysql_close();
?>

A quick thing i noticed.
form = $(this) //it is holding submit button, not the form
emailcode = form.serialize(),
formUrl = form.attr('action'), //there is no attribute `action` to select because form is holding submit button
formMethod = form.attr('method'); //similarly, there is no attribute method
change your form selector to:
form = $('#emailForm')

Related

wizard-form tow button different call ajax

I apologize for the ease of this question for you.
But I looked at your beautiful site for an answer to my problem, but I was not lucky.
I'm trying to build my own,form-wizard for student registration, in easy steps as a graduate project for university.
I use PHP, JQuery and AJAX to send data .
My problem:
I have a single form and to button ,
The first three input are searched in the database via the submit button and it is worked good ,
then automatically form-wizard moves to the next fieldset and then displays the inpust field to
student to enter his information .
finally thir is button to save data to database
by AJAX and this button is my problem .
the php say undefined index .
this is code for html wizard-form
$('form').on('submit', function(e) {
var $formInput = $(this).find('.fi');
$formInput.each(function(i) {
if (!$(this).val()) {
e.preventDefault();
$(this).addClass('input-error');
return false;
} else {
if ($formInput.length === i + 1) {
var id_high_school = $('[name="id_high_school"]').val();
var SEC_SCHOOL_YEAR = $('[name="SEC_SCHOOL_YEAR"]').val().toString();
var sum_high_school = $('[name="sum_high_school"]').val();
alert(SEC_SCHOOL_YEAR);
$.ajax({
url: "select_for_modal_serch.php",
method: "post",
data: {
id_high_school: id_high_school,
SEC_SCHOOL_YEAR: SEC_SCHOOL_YEAR,
sum_high_school: sum_high_school
}
}).done(function(datas) {
$('#studint_detail').html(datas);
$('#dataModal').modal("show");
}).fail(function() {
alert('fail..');
});
}
}
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<form name="mainForm" action=" <?php echo $_SERVER['PHP_SELF'] . '#form1' ?> " id="form1" method="POST" enctype="multipart/form-data">
<!-- condetion for regster -->
<fieldset>
<iframe src="license.html"></iframe>
<input class="form-check-input" id="check_qury" type="checkbox" value="yes">
<div class="wizard-buttons">
<button type="button" class="btn btn-next">التالي</button>
</div>
</fieldset>
<fieldset>
<!-- 3 <input type = text > to search for data from mysql -->
<!--her is the submit button and is get data by ajax -->
<input type="submit" class="form-control btn btn-primary view-data" id="submit_high_school" value="بحث" name="submit_high_school" />
<!-- by ajax is work and then is go to the next filedset -->
</fieldset>
<fieldset>
<!-- mor data <input type = text > to search for data from mysql -->
<button type="button" id="sava_data_to_tables" name="sava_data_to_tables" class="btn btn-next">
<!-- this is the button of my problem cant send this form data to mysql -->
</fieldset>
I doing this code to solve the problem but nothing work :
$('#sava_data_to_tables').on('click', function (event) {
var form_data = $(this).parents('form').serialize();
var colage = $('[name="colage"]').val();
var spichelest = $('[name="spichelest"]').val();
// and rest of input type
$.ajax({
url: "insert_into_info_contact.php",
method: "POST",
data: form_data,
success: function (data) {
alert(data);
}, cache: false,
contentType: false,
processData: false
});
});
and my PHP :
<?php
// isset($_POST['sava_data_to_tables'])
//$_SERVER['REQUEST_METHOD']==='POST'
// !empty($_POST)
if ($_SERVER['REQUEST_METHOD']==='post')
{ echo "you submit data"
;}
else {
echo "its not work" ; }
?>
I found some help from a friend ..
He just change this :
var form_data = $(this).closest('form').serialize();
to this :
var form_data = new FormData($(this).closest('#form1').get(0));
He solved my problem.
I honestly did not understand what the problem was, but he told me I had sent a different kind of data >> Thanks every One . :)

Processing Jquery Post with PHP

I've been at this for hours, and i'm at a complete loss.... I've tried everything I can but the problem is that i'm not very familiar with Jquery, this is the first time I've ever used it.... Basically, i'm attempting to pass form data to a php script, and then return a variable which will contain the source code of a webpage.
Here is the jquery:
$("button").click(function(){
hi = $("#domain").serialize();
var page;
$.ajax({
type: "POST",
url: "webcrawler.php",
data: hi,
//dataType: "text",
success: function(data){
page = data;
document.write(page);
}
});
});
Here is the html it references:
<div id="contact_form">
<form name="contact" action="">
<fieldset>
<label for="domain" id="domain_label">Name</label>
<input type="text" name="domain" id="domain" size="30" value="" class="text-input" />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</fieldset>
</form>
</div>
Here is the PHP that process it:
$search = $_POST["domain"];
if(!$fp = fopen($search,"r" )) {
return false;
}
fopen($search,"r" );
$data = "";
while(!feof($fp)) {
$data .= fgets($fp, 1024);
}
fclose($fp);
return $data;
?>
I think the variable $search is blank, but is that because i'm not sending it correctly with jquery or receiving it correctly with php? Thanks!
Well, when you serialize form data using jQuery, you should serialize the <form>, not the <input> field.
So try this:
$("button").click(function() {
var formData = $('form[name="contact"]').serialize();
var page;
$.ajax({
type: "POST",
url: "webcrawler.php",
data: formData,
success: function(data) {
page = data;
document.write(page);
}
});
});
See you have to do several things:
$("form[id='contact_form']").submit(function (e) {//<---instead click submit form
e.preventDefault(); //<----------------you have to stop the submit for ajax
Data = $(this).serialize(); //<----------$(this) is form here to serialize
var page;
$.ajax({
type: "POST",
url: "webcrawler.php",
data: Data,
success: function (data) {
page = data;
document.write(page);
}
});
});
So as in comments:
Submit form instead button click
Stop the form submission otherwise page will get refreshed.
$(this).serialize() is serializing the form here because here $(this) is the form itself.

JQuery's ajax post request does not work as it's supposed to be

The page's link is: localhost/mysite/create-user
This is the code:
<form class="form-horizontal" name = "signUp1F" id = "signUp1F">
<input class="input-xlarge focused" name="pskil" id ="pskil" type="text" placeholder = "Doctor, Trainer, Human Resource etc.">
<input type="hidden" name="neoid" id="neoid" value="<?php echo $neoid; ?>" />
<span><button id = "plus" class="btn btn-success">Plus</button></span>
<div id="skillsAdded"></div>
</form>
The jquery code:
<script type="text/javascript">
$('#plus').click( function(event){
var pskil = $('#pskil').val();
var neoid = $('#neoid').val();
if( !pskil){
alert( "Please write a skill.");
return false;
}
$.ajax({
type: 'post',
url: "localhost/mysite/add-skill",
data: { pskil: pskil, neoid: neoid},
success: function( response){
$('#skillsAdded').append( pskil + "<br>");
return false;
}
});
});
</script>
The purpose is this: user enters a skill value to the input, clicks the Plus button, an ajax request is sent to add the skill to the database. And the code that handles this request is on localhost/mysite/add-skill.
But things go wrong. When I click the "plus" button, it goes to the page localhost/mysite/create-user?pskil=php&neoid=53. What can possibly make this direction? I've been working on this issue for almost 2 hours and I cannot manage to handle it.
The issue is that your button tag submit your form. Here is a updated JavaScript source that you can use. jQuery got a built in preventDefault() method for events. This will for an example prevent the button to submit the form.
<script type="text/javascript">
$('#plus').click( function(event){
event.preventDefault();
var pskil = $('#pskil').val();
var neoid = $('#neoid').val();
if( !pskil){
alert( "Please write a skill.");
return false;
}
$.ajax({
type: 'post',
url: "localhost/mysite/add-skill",
data: { pskil: pskil, neoid: neoid},
success: function( response){
$('#skillsAdded').append( pskil + "<br>");
return false;
}
});
});
</script>
Tryout: http://jsfiddle.net/3A7Mg/1/

Send single input with ajax/jquery/php

I'm new to jQuery / AJAX.
I'm trying to send single input with jquery/ajax/php.
LIVE EXAMPLE
But, after pressing submit nothing is happening, where is my error?
Any help much appreciated.
HTML:
<form action="submit.php">
<input id="number" name="number" type="text" />
<input id="submit" name="submit" type="submit" />
</form>
JQUERY / AJAX:
$(document).ready(function(e) {
$('input#submit').click(function() {
var number = $('input[name=number]');
var data = 'number=' + number.val();
$.ajax({
url: "submit.php",
type: "GET",
data: data,
cache: false,
success: function(html) {
if (html == 1) {
alert('wyslane');
}
else {
alert('error');
}
}
});
return false;
});
});
PHP:
<?php
$mailTo = 'email#gmail.com';
$mailFrom = 'email#gmail.com';
$subject = 'Call Back';
$number = ($_GET['number']) ? $_GET['number'] : $_POST['number'];
mail($mailTo, $subject, $number, "From: ".$mailFrom);
?>
HTML:
<form id=submit action="">
<input id="number" name="number" type="text" />
<input name="submit" type="submit" />
</form>
The action URL is irrelevant as you want to submit your data via AJAX. Add the submit id to the form and override the default submit behavior, instead of overriding the onclick handler of the submit button. I'll explain in the JS section.
JS:
var number = $('input[name="number"]');
Quotes were missing.
$(document).ready(function(e) {
$('#submit').submit(function() {
var number = $('input[name=number]');
var data = 'number=' + number.val();
$.ajax({
url: "submit.php",
type: "GET",
data: data,
cache: false,
success: function(html) {
if (html == 1) {
alert('wyslane');
}
else {
alert('error');
}
}
});
return false;
});
});
I don't really understand your success callback, why do you expect that html should be equal to 1?
Atleast I got 404 error when pressed your submit button:
Not Found
The requested URL /index.php was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
When you get it to work, remember to add mysql_real_escape_string function to avoid SQL injections http://php.net/manual/en/function.mysql-real-escape-string.php
Since you are also using ID for number, you could just use: var data = 'number=' + $('#number').val()
Also if you add ID to your form, you can use:
$('#formId').submit(function(){
});
instead of that click. This function will launch when that form is submitted. This is better way because users can submit the form with other ways aswell than just clicking the submit button (enter).
var number = $('input[name=number]');
is wrong. It's
var number = $('input[name="number"]');

Update Twitter with AJAX-powered form

I'm trying to make an AJAX form that will update a twitter status when updated. I have the form working currently with php, but am not sure how to add AJAX functionality.
Here's the form:
<form id = "yourwhisper" method = "post" >
<label for="whisper">Enter your status update</label>
<textarea id="whisper" name="whisper" rows="2" cols="50" required></textarea>
<label class="error" for="whisper" id="whisper_error">Must be no more than 140 characters.</label>
<input id="lat" name="lat" style = "display:none"></input>
<input id="lon" name="lon" style = "display:none"></input>
<button type="submit" id = "submit">Pass it on</button>
</form>
This is the php which I had as the form action (it calls a php function from a twitter api library). I've now moved it to form-manager.php:
$t->update($_POST["whisper"], false, $_POST["lat"], $_POST["lon"]);
Finally, this is the jQuery code that adds the AJAX functionality. It takes the text for the update, along with the geolocation data, and passes it to the form-manager.php file in the form of the 'dataString'.
<script type="text/javascript" charset="utf-8">
$(function() {
$('.error').hide();
$(".submit").click(function() {
// validate and process form here
$('.error').hide();
var whisper = $("textarea#whisper").val();
var lat= $("input#lat").val();
var lon = $("input#lon").val();
if (whisper == "") {
$("label#whisper_error").show();
$("textarea#whisper").focus();
return false;
}
var dataString = 'whisper='+ whisper + '&lat=' + lat + '&lon=' + lon;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "form-manager.php",
data: dataString,
success: function() {
// alert ("form sent");
});
}
});
return false;
});
});
</script>
My problem is, how do I then get form-manager.php to take that info and put it into the 3 variables it needs to update twitter?
the dataString should be available to PHP as $_POST['dataString']. It is only a single var that contains a string. You should explode it.
Or if you want you can set the data property of the ajax method like { whisper: "Foo", lat: "fooLat" } so they will show up like $_POST['whisper'] and $_POST['lat']

Categories