Why doesn't my Ajax function work? - php

I am trying to use a form to submit two javascript variables to a php script and return the output to a new Div on the same page via an ajax function. It doesn't work.
here is my code
javascript/html
<link href="style/background.css" rel="stylesheet" type="text/css">
<script src="scripts/jquery-1.9.1.js"></script>
<script type="text/javascript">
fbPageOptions = {
shadowType: 'halo',
resizeDuration: 5.5,
imageFadeDuration: 4.5,
overlayFadeDuration: 0,
navType: 'both',
width: 580,
height: 405
};
</script>
<body>
<div id ="userForm">Add New User
<br>
<br>
<form id ="form">
First name: <input type="text" name="firstname" id="firstname"><br>
Last name: <input type="text" name="lastname" id="lastname" ><br>
<input type="submit" value="Submit" id="submit">
</form>
</div>
<script type="text/javascript">
var firstname = "";
var lastname = "";
$('#form').submit(function() {
firstname = $("input#firstname").val();
lastname = $("input#lastname").val();
alert(firstname + lastname);
$.ajax({
type: "POST",
url: "my url is in here",
data: {firstname: firstname, lastname: lastname},
success: function(data) {
$("#submitted").html(data);
alert("success");
}
});
});
</script>
<br>
<div id="submitted"></div>
</body>
here is the php code
<?php
$firstname = $_POST["firstname"];
echo "First name added is $firstname";
echo "<br>";
$lastname = $_POST["lastname"];
echo "Last name added is $lastname";
?>
when I submit the form the alert box triggers but the div is not updated. I'm using virtually the same code on another page and it works fine. :( Any ideas?
Thanks so much.

The form submits, reloading the page, you need to prevent the default submit event :
$('#form').on('submit', function (e) {
e.preventDefault();
var firstname = $("#firstname").val(),
lastname = $("#lastname").val();
$.ajax({
type: "POST",
url: "my url is in here",
data: {
firstname: firstname,
lastname: lastname
}
}).done(function (data) {
$("#submitted").html(data);
alert("success");
});
});

return false in submit function to prevent the default behaviour of submit which is causing the problem.
$('#form').submit(function() {
firstname = $("input#firstname").val();
lastname = $("input#lastname").val();
alert(firstname + lastname);
$.ajax({
......
});
return false;
});

You should use methods like $.param or .serialize to send you data.
http://api.jquery.com/jQuery.param/
http://api.jquery.com/serialize/

Related

html form submit using php and ajax

trying to store simple email data from website to mysql database, i've written the code however it is not working and i can't figure it out
<form class="subfield">
<input type="text" id="emailInput" name="email" type='email' placeholder="Enter Your Email here" required>
<input type="submit" id="inputSubmit" value="Subscribe">
<span id="st">Email Subscribed!</span>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#inputSubmit').click(function(){
var email = $('#emailInput').val();
$.ajax({
url:"form_process.php",
method:"POST",
data:{email:email},
success:function(data){
$("form").trigger("reset");
$('#st').fadeIn().html(data);
setTimeout(function(){
$('#st').fadeOut("Slow");
}, 2000);
}
});
});
});
</script>
<?php
//insert.php
$connect = mysqli_connect("localhost", "root", "", "testing");
if(isset($_POST["email"]))
{
$email = mysqli_real_escape_string($connect, $_POST["email"]);
$sql = "INSERT INTO `emails_list`(`email`) VALUES ('".$email."')";
if(mysqli_query($connect, $sql))
{
echo "email Subscribed";
}
}
?>
when submit button is clicked it redirects to the home page as it should and the url also shows the ?email= part but no data is stored on the database also seems no echo is sent from php
EDIT : i noticed the files are saved as index.php instead of index.html is it necessary to save as index.php
possibly way to to prevent deafult browser action. Then call ajax request on submit.
$(document).ready(function(){
$('#inputSubmit').click(function(e){
e.preventdefault();
var email = $('#emailInput').val();
$.ajax({
url:"form_process.php",
method:"POST",
data:{email:email},
success:function(data){
$("form").trigger("reset");
$('#st').fadeIn().html(data);
setTimeout(function(){
$('#st').fadeOut("Slow");
}, 2000);
}
});
});
});
There are two thing you can do about:
Use a button instead of submit
this:
<input type="submit" id="inputSubmit" value="Subscribe">
to:
<input type="button" id="inputSubmit" value="Subscribe">
use preventDefault Method
$(document).ready(function() {
$("#inputSubmit").click(function(e) {
e.preventDefault();
var email = $("#emailInput").val();
$.ajax({
url: "form_process.php",
method: "POST",
data: { email: email },
success: function(data) {
$("form").trigger("reset");
$("#st")
.fadeIn()
.html(data);
setTimeout(function() {
$("#st").fadeOut("Slow");
}, 2000);
}
});
});
});
$(document).ready(function(){
$('#inputSubmit').click(function(e){
e.preventdefault();
var email = $('#emailInput').val();
$.ajax({
url:"form_process.php",
method:"POST",
data:{email:email},
success:function(data){
$("form").trigger("reset");
$('#st').fadeIn().html(data);
setTimeout(function(){
$('#st').fadeOut("Slow");
}, 2000);
}
});
return false;
});
});

AJAX submit form data fails. It works using $_GET when i turn off e.preventdefault

This is my first post here. Sorry if my English appears to be bad.
I attempted to use the following codes to submit form data to my signup/submit/index.php.
Here is my sample HTML
<form name="signup_form" id="signup_form" action="submit">
<input type="text" class="form-control" placeholder="CreateUsername" name="username" id="username" autocomplete="off">
<input type="password" class="form-control" placeholder="CreatePassword" name="password" id="password"></form>
Here is my Ajax
.on('success.form.fv', function(e) {
e.preventDefault();
loadshow();
var $form = $(e.target),
fv = $form.data('formValidation');
// Use Ajax
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: $('#signup_form').serialize(), //or $form.serialize()
success: function(result) {
// ... Process the result ...
//alert(result);
if (result=="2")
{
swal({
type: "success",
title: "HiHi!",
text: "GoodLuck",
animation: "slide-from-top",
showConfirmButton: true
}, function(){
var username = $("#username").val();
var password = $("#password").val();
functionA(username,password).done(functionB);
});
}
else (result=="agent_na")
{
swal({
type: "error",
title: "ERROR",
text: "N/A",
animation: "slide-from-top",
showConfirmButton: true
});
Here goes my PhP
<?php
$params = array();
$gett = $_POST["username"];
parse_str($gett,$params);
print_r ($gett); // it prints an empty array
print_r ($gett); // it prints an empty array
echo $params["username"] // it shows undefined username index
?>
I have attempted to serialize $gett before parse_str it. It returns me (){}[].
Could please assist me on this?? I spent almost 20 hours on this, google and tried a lot. Am new to JS.
I try to keep it simple
HTML
<!-- Include Jquery Plugin -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="signup_form">
<input type="text" name="username" placeholder="Enter the user name" />
<input type="password" name="password" placeholder="Enter password here" />
<input type="submit" value="Login" />
</form>
<script>
/* Page loaded */
$(function(){
/* Trigger when the form submitted */
$("#signup_form").submit(function(e) {
var form = $(this);
$.ajax({
type: "POST",
url: "backend.php",
data: form.serialize(), // Checkout the document - https://api.jquery.com/serialize/
success: function(data) {
// handle the return data from server
console.log(data);
}
});
e.preventDefault();
return false;
})
})
</script>
PHP (backend.php)
<?php
// Always check param exists before accessing it
if(isset($_POST['username']) && isset($_POST['password'])){
// Print all the post params
print_r($_POST);
// or by param
// echo "User Name: " . $_POST['username']. " <br />";
// echo "Password: " . $_POST['username']. " <br />";
}
?>
Hope this helps!
This is a sample of how you can debug an ajax call:
Javascript:
$(function(){
$("#signup_form").submit(function(e) {
var formData = new FormData($(this));
$.ajax({
type: "POST",
url: "backend.php",
data: formData,
success: function(data) {
console.log(data);
// if (data.length > 0) ....
}
});
e.preventDefault();
return false;
});
});
PHP:
<?php
if (isset($_POST['signup_form'])){
$params = array();
$gett = $_POST['username'];
parse_str($gett,$params);
print_r ($gett);
echo $_POST['username'];
}else{
die('No $_POST data.');
}
?>
Your php code had some problems in it, you missed a semi-colon and you tried to print from an empty array, calls through ajax won't show any run time errors, and thus you need to be very careful when you're trying to debug an ajax to php call.
Hope this helps.

Sending Multiple data to PHP page without reloading page

Please I am new to jQuery so i just copied the code:
<div id="container">
<input type="text" id="name" placeholder="Type here and press Enter">
</div>
<div id="result"></div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#name').focus();
$('#name').keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 13) {
var info = $('#name').val();
$.ajax({
method: "POST",
url: "action.php",
data: {name: info},
success: function(status) {
$('#result').append(status);
$('#name').val('');
}
});
};
});
});
</script>
And here is the php code:
<?php
if (isset($_POST['name'])) {
echo '<h1>'.$_POST['name'];
}
?>
Its Working perfectly but now i want to have more than one input field like this:
<input type="text" id="name" >
<input type="text" id="job">
but i don't know how to run the jQuery code for the 2 input fields so that it can transfer them to the php page. Please i need help
You can pass multiple values using data param of ajax request like this.
$.ajax({
method: "POST",
url: "action.php",
data: {
name: $('#name').val(),
job: $('#job').val()
},
success: function(status) {
$('#result').append(status);
$('#name, #job').val(''); // Reset value of both fields
}
});
You need to change your code with some addition in html and JS.
Wrap your inputs in form tag. and add a preventDefault on submit.
Use jQuery .serialize() method
and event.preventDefault()
event.preventDefault() : If this method is called, the default
action of the event will not be triggered. (it will prevent page
reload / redirection) to any page.
.serialize() : Encode a set of form elements as a string for
submission.
serialized string output will be like key=value pair with & separated. :
name=john&job=developer.....
HTML
<form id="myform">
<input type="text" id="name" placeholder="Type here and press submit">
<input type="text" id="job" placeholder="Type here and press submit">
<input type="submit" name="submit" value="Submit Form">
</form>
JS
$(document).ready(function() {
$('#myform').submit(function(event) {
event.preventDefault();
var serialized = $('#myform').serialize();
$.ajax({
method: "POST",
url: "action.php",
data: serialized,
success: function(status) {
$('#result').append(status);
$('#myform').reset();
}
});
});
});

Php Form Submit without Refresh - Ajax not working

I am trying to get get my form to submit without having the page refreshing everytime
However, when I insert the ajax and place the php into a new file the form doesnt submit and I dont understand why?
Any advice would be appreicated!
PHP
<?php
if(isset($_POST['name'], $_POST['email'], $_POST['phone'], $_POST['message'])){
//Post data
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
//mail settings
$to = "arshdsoni#gmail.com";
$subject = 'Soni Repairs - Support Request';
$body = <<<EMAIL
Hi There!
My name is $name.
Message: $message.
My email is: $email
Phone Number: $phone
Kind Regards
EMAIL;
$header = "From: $email";
if($_POST) {
if($name == '' || $email == '' || $phone == '' || $message == '') {
echo $feedback = "<font color='red'> *Please Fill in All Fields!";
}
else {
mail($to, $subject, $body, $header);
echo $feedback = "<font color='green'> *Message sent! You will receive a reply shortly!";
}
}
}
else{
echo $feedback = "<font color='red'> Missing Params";
}
?>
AJAX
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("#submitBtn").click(function( event ) {
//values
var name=document.getElementById('name').value;
var email=document.getElementById('email').value;
var phone=document.getElementById('phone').value;
var message=document.getElementById('message').value;
var occasion=document.getElementById('occasion').value;
var dataString = $("#contact").serialize();
$.ajax({
type:"post",
url:"php.php",
data: dataString,
success: function(html) {
$('#feedback').html(html);
}
});
event.preventDefault();
});
});
</script>
HTML CODE HERE: http://www.codeply.com/go/e3jAo1WrPl
The .bind() function may be the way to go with this form, since it binds the action of clicking the button to the event handler.
It also may be beneficial to have the event.preventDefault() before your ajax call.
$(document).ready(function(){
$("#submitBtn").bind([boundElement],function( event ) {
event.preventDefault();
var name=document.getElementById('name').value;
var email=document.getElementById('email').value;
var phone=document.getElementById('phone').value;
var message=document.getElementById('message').value;
var occasion=document.getElementById('occasion').value;
var dataString = $("#contact").serialize();
$.ajax({
type:"post",
url:"php.php",
data: dataString,
success: function(html) {
$('#feedback').html(html);
}
});
return true;
});
});
I would recommend double-checking the syntax for the bound element in the .bind() parameters. It is single quote marks for referring to a named form element
Example HTML:
This might help you with your problem:
$(document).ready(function() {
$("#contact").submit(function(event) {
event.preventDefault();
var name = $('#name').val(),
email = $('#email').val(),
phone = $('#phone').val(),
message = $('#message').val(),
occasion = $('#occasion').val(),
dataString = $(this).serialize();
$.ajax({
url: 'php.php',
type: 'post',
data: dataString,
})
.done( function( html ) {
$( '#feedback' ).html( html );
})
.fail( function( response ) {
console.log( response );
});
});
});
Firs of all, you have the form and the submit button, so when you press the button, the event 'submit' is triggered, so you prevent the event to be fired, then you do your coding, the variables, but I cannot understand why you declare all those, if you don't use them, but that's up to you.
Here is a suggestion with using a button in stead of a submit. I commented out the preventDefault, because it is unnecessary in this case -- we are not actually submitting the form. This gives us more control.
The request is submitted. In this case, it obviously fails. In your case, whether or not it fails is going to depend on what you have going on server side.
http://plnkr.co/edit/txuxaFUkgFq9SFDcqUdp
<form action="http://www.yahoo.com" id="contactForm" method="get" target="_blank">
<div class="innerForm">
<label for="name">Name:</label>
<input id="name" name="name" type="text" />
<label for="phone">Phone:</label>
<input id="phone" name="phone" type="text" />
<label for="email">Email:</label>
<input id="email" name="email" type="text" />
<label for="occasion">Occasion:</label>
<input id="occasion" type="text" name="occasion" />
<label id="messageLabel" for="message">Message:</label>
<textarea id="message" name="message"></textarea>
<button id="test">test</button>
<!--input type="submit" value="Submit" id="submitBtn" name="submit" onclick="return chk();"/ -->
</div>
<div id="feedback"></div>
</form>
$(document).ready(function(){
$("#test").click(function (event) {
//values
alert("test clicked");
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var phone = document.getElementById('phone').value;
var message = document.getElementById('message').value;
var occasion = document.getElementById('occasion').value;
var dataString = $("#contactForm").serialize();
$.ajax({
type: "get",
url: "http://www.yahoo.com",
data: dataString,
success: function (html) {
alert("success");
//$('#feedback').html(html);
},
error: function(result){
alert("failure");
}
});
//event.preventDefault();
});
});

Submit a Form without Reloading

I got this simple form page that will submit the last name and first name of a user
<?php
include 'dbconnect.php';
if (isset($_POST['lname']) && isset($_POST['fname'])){
$ln = $_POST['lname'];
$fn = $_POST['fname'];
$sql = "INSERT INTO user_tbl (`lastname`,`firstname`) VALUES ('$ln','$fn')";
$result = mysql_query($sql);
}
?>
<!DOCTYPE html>
<html>
<head>
<script >var frm = $('#nameFrm');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
</script>
</head>
<body>
<form id = "nameFrm" name = "frmName" method = "POST" >
Last Name : <input type = "text" name = "lname"><br />
First Name: <input type = "text" name = "fname"><br />
<input type = "submit" value = "submit" name= "subbtn" >
</form>
</body>
my script does not work that script is suppose to avoid the page from reloading and i am pretty sure that it is reloading everytime the page is submitted
also when i seperate the php code
if (isset($_POST['lname']) && isset($_POST['fname'])){
$ln = $_POST['lname'];
$fn = $_POST['fname'];
$sql = "INSERT INTO user_tbl (`lastname`,`firstname`) VALUES ('$ln','$fn')";
$result = mysql_query($sql);
}
it still redirects it to the new php file
What to do is create a new file called requests.php / or whatever
in this file have a switch statement..
requests.php
<?php
if(isset($_POST['action']) && ($_POST['action']!='')){
$action = $_POST['action'];
switch($action){
case "submitForm" :
include 'dbconnect.php';
if ( (isset($_POST['lname'])) && (isset($_POST['fname'])) ){
$ln = mysql_real_escape_string($_POST['lname']);
$fn = mysql_real_escape_string($_POST['fname']);
$sql = "INSERT INTO user_tbl (`lastname`,`firstname`) VALUES ('$ln','$fn')";
mysql_query($sql);
echo "New values updated: ".$fn." ".$ln;
}
break;
}
}
?>
Then copy this crude html..
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#nameFrm").submit(function (e) {
e.preventDefault();
var frm = jQuery('#nameFrm');
var outPut = jQuery('#results');
var loadImg = jQuery('#loadingImage');
var fname = jQuery('#fname').val();
var lname = jQuery('#lname').val();
jQuery.ajax({
type: 'POST',
data:'action=submitForm&fname='+fname+'&lname='+lname,
url: 'requests.php',
beforeSend: function(){
loadImg.show();
},
complete: function(){
loadImg.hide();
},
success: function(data) {
frm.hide();
outPut.html(data);
}
});
});
});
</script>
</head>
<body>
<form action="requests.php" id="nameFrm" name="frmName" method="POST" >
Last Name : <input type="text" id="lname" name="lname"><br />
First Name: <input type="text" id="fname" name="fname"><br />
<input type = "submit" value = "submit" name= "subbtn" >
</form>
<div id="loadingImage" style="display:none; text-align:center;">
<img src="http://craigmaslowski.com/images/activity-indicator.gif" />
</div>
<div id="results"></div>
</body>
What its doing is when you click the submit button, the jquery will fire,
it will grab the 2 values from fname & lname (these have been given an id)
the 2 values will then be added to the jquery.ajax URL, this url will be the form action url, which for this is requests.php
in requests.php the 2 post values are passed over and processed, the output will be sent back to the original page, were the data will be passed to the div#results, to show the output....
Also I've added a few other things, like a loading image, for both the beforeSend call and Complete,
**ALSO,
please be-aware that you should really think about moving from using the mysql_query syntax to mysqli_query.. have a look at MackieeE's comment!
**
Have a play around with it.. hopefully its what your looking for..
Good luck..
Marty
The browser executes the javascript BEFORE knowing the form.
Put the javascript AFTER the form or into a $(window).load():
<script>
$( window ).load(function() {
var frm = $('#nameFrm');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
});
</script>

Categories