jquery ajax form: loading image only and doesnt stop and success message not working
this is my contact form
<form method="post" action="" class="comments-form" id="contactform" />
<p class="input-block">
<label for="name">Name:</label>
<input type="text" name="name" id="name" />
</p>
<p class="input-block">
<label for="email">E-mail:</label>
<input type="text" name="email" id="email" />
</p>
<p class="input-block">
<label for="message">Message:</label>
<textarea name="message" id="message" cols="30" rows="10"></textarea>
</p>
<p class="input-block">
<button class="button default" type="submit" id="submit">Submit</button>
</p>
</form>
and this is my jquery ajax function that is not working
(function() {
if($('#contactform').length) {
var $form = $('#contactform'),
$loader = '<img src="images/preloader.gif" alt="Loading..." />';
$form.append('<div class="hidden" id="contact_form_responce">');
var $response = $('#contact_form_responce');
var $p
$response.append('<p></p>');
$form.submit(function(e){
$response.find('p').html($loader);
var data = {
action: "contact_form_request",
values: $("#contactform").serialize()
};
//send data to server
$.post("php/contact-send.php", data, function(response) {
response = $.parseJSON(response);
$(".wrong-data").removeClass("wrong-data");
$response.find('img').remove();
if(response.is_errors){
$response.find('p').removeClass().addClass("error type-2");
$.each(response.info,function(input_name, input_label) {
$("[name="+input_name+"]").addClass("wrong-data");
$response.find('p').append('Please enter correctly "'+input_label+'"!'+ '</br>');
});
} else {
$response.find('p').removeClass().addClass('success type-2');
if(response.info == 'success'){
$response.find('p').append('Your email has been sent!');
$form.find('input:not(input[type="submit"], button), textarea, select').val('').attr( 'checked', false );
$response.delay(1500).hide(400);
}
if(response.info == 'server_fail'){
$response.find('p').append('Server failed. Send later!');
}
}
// Scroll to bottom of the form to show respond message
var bottomPosition = $form.offset().top + $form.outerHeight() - $(window).height();
if($(document).scrollTop() < bottomPosition) {
$('html, body').animate({
scrollTop : bottomPosition
});
}
if(!$('#contact_form_responce').css('display') == 'block') {
$response.show(450);
}
});
e.preventDefault();
});
}
})();
and this is my contact-send.php that saves the message in my database.
require_once "../includes/database.php";
$cname=$_POST['name'];
$cemail=$_POST['email'];
$cmessage=$_POST['message'];
$date=date("Y-m-d");
$sql = "INSERT INTO messages (sendername,senderemail,message,datesent) VALUES (:name,:email,:message,:date)";
$qry = $db->prepare($sql);
$qry->execute(array(':name'=>$cname,':email'=>$cemail,':message'=>$cmessage,':date'=>$date));
I think your issue is here:
$.post("php/contact-send.php", data, function(response) {
response = $.parseJSON(response);
//--^--------------------------------------missing '$'
$(".wrong-data").removeClass("wrong-data");
$response.find('img').remove();
//----^------------------------------------used the '$' for other codes
try to put a $ here and see if this solves the issue:
$response = $.parseJSON(response);
and if you are getting some ajax errors plz mention it.
Related
I am trying to learn web applications, here I have my client side using HTML and server is PHP based.
I have signup from on my client side, which when filled and click submit button is sent to PHP page using jQuery AJAX.
So, after the form data is sent or POST to PHP page using AJAX, a couple of validations happen like checking username and email, if the validations succeed it should send back a JSON object to my HTML page "SUCCESS", if validation fails "Error".
So, the problem is when I submit the form it is redirecting me to the PHP page instead of displaying the JSON response back on my html.
I was trying to solve this since last week and I filtered stack overflow, youtube and many other sites for a solution, which didn't go well.
Here is the code
PHP:
<?php include ( "./inc/connect.inc.php" );
header("Content-type: application/javascript");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET");
session_start();
if (isset($_SESSION['user_login'])) {
$user = $_SESSION["user_login"];
}
else
{
$user = "";
}
?>
<?php
$registration = #$_POST['signup-submit'];
$fname = #$_POST['fname'];
$lname = #$_POST['lname'];
$uname = #$_POST['uname'];
$email = #$_POST['email'];
$email_repeat = #$_POST['email_repeat'];
$password = #$_POST['password'];
$ucheck_array = array('Username Takne');
$echeck_array = array('Email already used');
$siginup_sucess_array = array('Sucess');
//Sign-Up form validation
if ($registration) {
$usernamecheck = mysql_query("SELECT * FROM users WHERE username='$uname' ");
$usernamecount = mysql_num_rows($usernamecheck);
$emailcheck = mysql_query("SELECT * FROM users WHERE email='$email' ");
$emailcount = mysql_num_rows($emailcheck);
if ($usernamecount == 0 && $emailcount == 0) {
$squery = mysql_query("INSERT INTO users VALUES ('','$uname','$fname','$lname','$dob','$location','$email','$password','$date','0','','','','','','no')" );
echo json_encode($siginup_sucess_array);
}
else {
if ($usernamecount == 1) {
echo json_encode($ucheck_array);
}
else if ($emailcount == 1) {
echo json_encode($echeck_array);
}
}
}
HTML Form:
<form id="register-form" class="animated fadeInRight" action="http://localhost/Exercises/AJAX/df.php" method="post" role="form" style="display: none;">
<div class="form-group">
<input type="text" name="fname" id="fname" placeholder="First Name" value="" autofocus>
</div>
<div class="form-group">
<input type="text" name="lname" id="lname" tabindex="1" class="form-control" placeholder="Last Name" value="">
</div>
<div class="form-group">
<input type="text" name="uname" id="uname" tabindex="1" class="form-control" placeholder="User Name" value="">
</div>
<div class="form-group">
<input type="text" name="dob" id="dob" placeholder="D-O-B" value="">
</div>
<div class="form-group">
<input type="text" name="location" id="location" tabindex="1" class="form-control" placeholder="Location" value="">
</div>
<div class="form-group">
<input type="email" name="email" id="email" placeholder="Email" value="">
</div>
<div class="form-group">
<input type="email" name="email_repeat" id="email_repeat" placeholder="Confirm Email" value="">
</div>
<div class="form-group">
<input type="text" name="password" id="password" tabindex="1" class="form-control" placeholder="Password" value="">
</div>
<div class="form-group dob">
<input type="text" name="date" id="date" placeholder="Date" value="">
</div>
<p class="index_p">By creating the account you accept all the <span style="color: #4CAF50; font-weight: bold; text-decoration: underline;">Terms & Conditions.</span></p>
<div class="form-group">
<div class="row">
<div id="btn_signin" class="col-sm-6 col-sm-offset-3">
<input type="submit" name="signup-submit" id="signup-submit" value="SIGN UP">
</div>
</div>
</div>
</form>
<div id="signup-test"></div> //PHP response to be displayed here
JS:
$("#signup-submit").click( function() {
$.post( $("#register-form").attr("action"),
$("#register-form :input").serializeArray(),
function(signup_data){
$("#signup-test").html(signup_data);
});
clearInput();
});
$("#register-form").submit( function() {
return false;
});
function clearInput() {
$("#register-form :input").each( function() {
$(this).val('');
});
}
To be clear I tried e.preventDefault, return false and many other scripts,
and my PHP and HTML are not in the same folder or directory.
Thanks.
Try using a more flexible jQuery ajax. I use this version if ajax because I can change it to get and post very easily. I have tested this method and it works with your form:
<script>
function clearInput() {
$("#register-form :input").each( function() {
$(this).val('');
});
}
$(document).ready(function() {
$("#register-form").submit(function(e) {
//console.log($(this).attr("action"));
$.ajax({
url: $(this).attr("action"),
type: 'post',
data: $(this).serialize(),
success: function(response)
{
// console.log(response);
$("#signin-test").html(response);
clearInput();
},
error: function(response)
{
console.log(response);
}
});
e.preventDefault();
});
});
</script>
This may be because you are handling your form based on the behavior of a button. You should be listening for the onSubmit event of the form and preventing that from firing.
$("#register-form").submit( function( e ) {
e.preventDefault();
$.post( $("#register-form").attr("action"),
$("#register-form :input").serializeArray(),
function(signup_data){
$("#signup-test").html(signup_data);
});
clearInput();
});
I solved it with the following script, hope it would help someone.
The problem with all the scripts which I tried is, they don't have XMLHttpRequest permission to POST data and get the data back from PHP(server side in my case).
So, XMLHttpRequest is a must for Ajax to Get or Post data "CROSS_DOMAIN".
Script :
function signup(){
var firstname = document.getElementById("firstname").value;
var lastname = document.getElementById("lastname").value;
var uname = document.getElementById("uname").value;
var email = document.getElementById("email").value;
var email_repeat = document.getElementById("email_repeat").value;
var password = document.getElementById("password").value;
if (fname == "") {
document.getElementById("fname").style.background = "rgba(244,67,54,0.45)";
document.getElementById("fnamestatus").innerHTML = "<p style='width: 30px; color: rgba(255, 62, 48, 0.9); font-size: 14px; font-weight: bold; margin-top:5px; margin-left: -40px; margin-bottom: 0px;'>2-25</p>";
}
else if (email != email_repeat){
document.getElementById("email").style.background = "rgba(244,67,54,0.45)";
document.getElementById("email_repeat").style.background = "rgba(244,67,54,0.45)";
alert("Your email fields do not match");
}
else {
var signup_ajax = new XMLHttpRequest();
signup_ajax.open("POST", "URL which you want to post data", true);
signup_ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
signup_ajax.onreadystatechange = function () {
if (signup_ajax.readyState == 4 && signup_ajax.status == 200) {
if (signup_ajax.responseText = "Success"){
alert("Account created");
}
else if (signup_ajax.responseText = "Try again.") {
window.scrollTo(0,0);
alert("Try again.");
}
}
}
signup_ajax.send("fname=" +fname+ "&lname=" +lname+ "&uname=" +uname+ "&email=" +email+ "&email_repeat=" +email_repeat+ "&password=" +password );
}
}
PHP(I'm just posting the basic php, you can always add as may validations as you need) :
if(isset($_POST["uname"])) {
$fname = #$_POST['firstname'];
$lname = #$_POST['lastname'];
$uname = #$_POST['uname'];
$email = #$_POST['email'];
$email_repeat = #$_POST['email_repeat'];
$password = #$_POST['password'];
//Sign-Up form validation
if($_POST) {
$squery = mysql_query("INSERT INTO users VALUES ('','$uname','$fname','$lname','$email','$password')" );
echo 'Sucess';
}
else
echo 'Try again.';
}
Only change what I did to my HTML Form is :
<input type="button" name="signup-submit" id="signup-submit" class="form-control btn btn-signup" onclick="signup()" tabindex="4" value="SIGN UP">
I've coded a contact form. If the mail() succeed, i would like to call my jquery popup.
How can I do this?
jQuery(function($) {
var popup_zustand = false;
$(".kontakt_oeffnen").submit(function() {
if(popup_zustand == false) {
$("#kontakt").fadeIn("normal");
$("#hintergrund").css("opacity", "0.7");
$("#hintergrund").fadeIn("normal");
popup_zustand = true;
}
return false;
});
});
if(mail($address, $e_subject, $msg))
{
//?????
} else
{
echo 'ERROR!';
}/**/
I only want to show the popup if mail function succeed.
Both didn't work for me... sry .. maybe i'm too stupid.
here is my complete code:
file: popup.js
jQuery(function($) {
var popup_zustand = false;
$(".kontakt_oeffnen").submit(function() {
if(popup_zustand == false) {
$("#kontakt").fadeIn("normal");
$("#hintergrund").css("opacity", "0.7");
$("#hintergrund").fadeIn("normal");
popup_zustand = true;
}
return false;
});
$(".schliessen").click(function() {
if(popup_zustand == true) {
$("#faq").fadeOut("normal");
$("#kontakt").fadeOut("normal");
$("#imprint").fadeOut("normal");
$("#hintergrund").fadeOut("normal");
popup_zustand = false;
}
});
});
file: contact.php
<?php>
if(mail($address, $e_subject, $msg))
{
//?????
} else
{
echo 'ERROR!';
}
?>
file: contact_inc.php
<form method="post" action="classes/contact.php" name="contactform" id="contactform" autocomplete="on">
<input name="name" type="text" id="input_text" required="required" size="24" maxlength="30"/>
<input name="email" type="email" id="input_text" pattern="^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)#([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$" required="required" size="24" maxlength="30">
<input name="phone" type="tel" id="input_text" size="24" />
<input name="company" type="text" id="input_text" placeholder="Firma..." size="24" maxlength="30">
<textarea style="height:100%" name="comments" cols="30" rows="10" id="input_text" spellcheck="true" required="required"></textarea>
<input type="submit" id="SubmitButton" value="Absenden" />
</form>
if I add to my button classes="kontakt_oeffnen" it will always popup ... without sending the email.
But I should only popup if the email would be sent correctly.
Can't I just call the jquery function from php (where the questions marks are...)
i would change the source a lil bit
HTML
<form>
<input name="name" type="text" id="input_text" required="required" size="24" maxlength="30" />
<input name="email" type="email" id="input_text" pattern="^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)#([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$" required="required" size="24" maxlength="30" />
<input name="phone" type="tel" id="input_text" size="24" />
<input name="company" type="text" id="input_text" placeholder="Firma..." size="24" maxlength="30" />
<textarea style="height:100%" name="comments" cols="30" rows="10" id="input_text" spellcheck="true" required="required"></textarea>
<input type="submit" id="SubmitButton" value="Absenden" />
</form>
jQuery
$(document).ready(function () {
$('#SubmitButton').on('click', function () {
var formData = $('form').serializeArray();
var fData = Array();
var postActive = false; // only because i dont have the contact.php (denie error)
$(formData).each(function(){
//console.log(this.name + ":" + this.value);
fData[this.name] = this.value;
});
if(postActive)
{
//now submit data to php file
$.post('classes/contact.php', {
data: fData // deal with info in phpfile, $_POST['data']['name'] or
// $_POST['data']['email'] .. return your mail result with a echo.
// lets say echo 1; for true or echo 0 for false
// because true and false in php is not the same as in js
}).done(function (response) {
//response contains 1 (mail was send!)
// by the way... you have a function befor/complete/error for handeling results...
// check out jquery.com
alert(response);
/* CANT find this in your "ALL MY SOURCE" post :)
if (response === false) {
$("#kontakt").fadeIn("normal");
$("#hintergrund").css("opacity", "0.7");
$("#hintergrund").fadeIn("normal");
popup_zustand = true;
}
*/
});
}
console.log(fData); // open console to browse the array
});
});
PHP File (classes/contact.php)
<?php
//some source
// Data from Form is available like next row
$recipient = $_POST['data']['email'];
$name = $_POST['data']['name'];
....
$result = 0;
if(mail($rescipient, ... ))
$result = 1;
echo $result;
?>
of course you can work with JSON for better usage :)
in this way everything is clean, you have your HTML, your PHP and your jQuery source separated :)
PS: Check out the FIDDLE
You can try to mix it like this:
<?php
if(mail($address, $e_subject, $msg)) {
?>
<script>
jQuery(function($) {
var popup_zustand = false;
$(".kontakt_oeffnen").submit(function() {
if(popup_zustand == false) {
$("#kontakt").fadeIn("normal");
$("#hintergrund").css("opacity", "0.7");
$("#hintergrund").fadeIn("normal");
popup_zustand = true;
}
return false;
});
});
</script>
<?
} else {
echo 'ERROR!';
}/**
?>
I have a jQuery Ajax form that looks like this:
<form method="post" action="contact.php" class="contact-form">
<div class="contact-empty">
<input type="text" name="name" id="name" placeholder="Name *" class="txt-name" />
<input type="text" name="email" id="contact-email" placeholder="Email Address *" class="txt-email" />
<textarea rows="4" name="message" cols="60" id="message" placeholder="Message *" class="txt-message"></textarea>
<span class="btn-contact-container">
<button id="contact-submit" class="btn-contact">Submit</button>
<img src="images/loading.gif" alt="Loading..." width="62" height="62" id="contact-loading">
</span>
<span class="contact-error-field"></span>
</div>
<div class="contact-message"></div>
</form>
Here's my js that sends it:
$(document).ready(function () {
$('#contact-submit').click(function () {
$('.contact-error-field').hide();
var nameVal = $('input[name=name]').val();
var emailReg = /^([a-z0-9_\.-]+)#([\da-z\.-]+)\.([a-z\.]{2,6})$/;
var emailVal = $('#contact-email').val();
var messageVal = $('textarea[name=message]').val();
//validate
if (nameVal == '' || nameVal == 'Name *') {
$('.contact-error-field').html('Your name is required.').fadeIn();
return false;
}
if (emailVal == "" || emailVal == "Email Address *") {
$('.contact-error-field').html('Your email address is required.').fadeIn();
return false;
}
else if (!emailReg.test(emailVal)) {
$('.contact-error-field').html('Invalid email address.').fadeIn();
return false;
}
if (messageVal == '' || messageVal == 'Message *') {
$('.contact-error-field').html('Please provide a message.').fadeIn();
return false;
}
var data_string = $('.contact-form').serialize();
$('.btn-contact').hide();
$('#contact-loading').fadeIn();
$('.contact-error-field').fadeOut();
$.ajax({
type: "POST",
url: "contact.php",
data: data_string,
//success
success: function (data) {
$('.btn-contact-container').hide();
$('.contact-message').html('<i class="fa fa-check contact-success"></i>Your message has been sent.').fadeIn();
},
error: function (data) {
$('.btn-contact-container').hide();
$('.contact-message').html('<i class="fa fa-times contact-error"></i>Something went wrong, please try again later.').fadeIn();
}
}) //end ajax call
return false;
});
});
I have a subscribe form that uses the same code with just an email input and that submits fine on an iphone.
The contact form, however, gets stuck at 'Invalid email address.' when trying to submit from an iPhone even though the email you enter is correct. It works on desktop.
I've tried changing the button to a type="submit" input. Didn't change anything.
UPDATE: My regex was wrong, I replaced it with the following and it worked:
var emailReg = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/igm;
Instead of using click() to submit your form, use submit():
Just change the top of your javascript code so it looks like this:
$(document).ready(function () {
$('form.contact-form').submit(function (e) {
e.preventDefault(); // <-- prevents normal submit behavior
And change your button to type=submit
<button type="submit" id="contact-submit" class="btn-contact">Submit</button>
I've searched through the StackOverFlow but didn't found what I was looking for so I'm posting what I want to ask you.
I'm a new comer to the world of PHP any how I've started to write a script which will get data and display on a WAP interface that part is ok my issue is in the part I'm writing for the data insert page or the Admin page. I've got every thing working but I love to know how to use AJAX to display a message with out going to the particular processing page.
The Process Page,
<?php
include ('connect.php');
$data = ("SELECT * FROM poiinfo");
$poiName = $_REQUEST['Name'];
$poiDes = $_REQUEST['Descrip'];
$poiCon = $_REQUEST['ConInfo'];
/*$poiImg = $_REQUEST['Image']; */
$dbData = "INSERT INTO poiinfo(`Name`, `Des.`, `Contact`) VALUES ('$poiName','$poiDes','$poiCon')";
$putData = mysql_query($dbData);
if ($putData){
echo "Data inserted";
}else {
echo "Not Done";
}
?>
Can I know how to use AJAX to get an message.
I've used the code examples that you guys gave me but I'm still not getting the job done please can you help me to find what I'm doing wrong.
My Form,
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#save_data").click(function(){
var name = document.getElementById("Name");
var desc = document.getElementById("Descrip");
var con = document.getElementById("ConInfo");
var dataString = 'Name='+name'&Descrip='+desc'&ConInfo='con;
$.ajax({
type:'POST',
data:dataString,
url:'addpoipro.php',
success:function(data){
if(data="Data inserted") {
alert("Insertion Success");
} else {
alert("Not Inserted");
}
}
});
});
});
</script>
<title>AddPOI</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" name="form1" id="form1">
<p>
<label for="poiid">ID :</label>
<input type="text" name="poiid" id="poiid" readonly="readonly" style="width:70px;" value="<?php echo $tId; ?>" />
</p>
<p>
<label for="Name">POI Name :</label>
<input type="text" name="Name" id="Name" />
</p>
<p>
<label for="Descrip" style="alignment-adjust:middle">POI Description :</label>
<textarea name="Descrip" id="Descrip" cols="45" rows="5"></textarea>
</p>
<p>
<label for="ConInfo">Contact Infomation :</label>
<textarea name="ConInfo" id="ConInfo" cols="45" rows="5"></textarea>
</p>
<p>
<label for="Img">POI Image :</label>
<!--<input type="file" name="Image" id="Image" /> -->
</p>
<p> </p>
<p>
<div align="center">
<input type="button" name="Submit" id="save_data" value="Submit" style="width:100px;" />
<input type="reset" name="reset" id="reset" value="Rest Data" style="width:100px;" />
</div>
</p>
</form>
</body>
</html>
Above4 is my form and the process.php is before that please help me thank you.
Example using jQuery's $.ajax:
$.ajax({
url: "process.php",
type: "POST",
data : { Name : 'John', Descrip : 'some description..', ConInfo : 'some info...' },
success : function(data){
if(data == "Data inserted")
{
console.log("Success!");
}
else
{
console.log("fail!");
}
}
});
Here is another solution without using jquery.
index.html
<head>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<!-- reply from process.php is shown in this div -->
<div id=message></div>
<!-- click to send data -->
click here
</body>
</html>
test.js
function sendData(Name,description,info) {
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer Browsers
try
{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function()
{
var ajaxDisplay = document.getElementById('message');
if(ajaxRequest.readyState == 4)
{ ajaxDisplay.innerHTML = ajaxRequest.responseText;}
else { document.getElementById('message').innerHTML="<span style=\"color:green;\">Loading..</span>"; }
}
var url="process.php?name="+Name+"&Descrip="+description+"&ConInfo="+info;
ajaxRequest.open("POST", url, true);
ajaxRequest.send(null);
}
You can do it like this also.
You HTML
<label>Name</labe><input type="text" id="name" name="full_name" value="" />
<label>Address</labe><input type="text" id="addr" name="addr" value="" />
<input type="button" name="save" id="save_data" value="Save" />
in the head section after adding jQuery do something like this
<script>
$(document).ready(function(){
$("#save_data").click(function(){
var name = $("#name").val();
var addr = $("#addr").val();
var dataString = 'name='+name'&address='+address;
$.ajax({
type:'POST',
data:dataString,
url:'process.php',
success:function(data){
if(data="inserted") {
alert("Insertion Success");
} else {
alert("Not Inserted");
}
}
});
});
});
</script>
"process.php page"
$name = $_POST['name'];
$address = $_POST['address'];
// DO YOUR INSERT QUERY
$insert_query = mysql_query("INSERT QUERY GOES HERE");
if(// CHECK FOR AFFECTED ROWS) {
echo "inserted";
} else {
echo "not";
}
Hello im trying to implement an ajax invitation script which will let the user to invite his/her friends to that event. I use the mostly same javascript in the other parts of the website and they work perfect, but in this case, it doesn't work, i'm sure that the problem persists because of the javascript part, because as i said, i use the nearly exact script and it works perfect, when i post the data, it doesn't send the email, my mail function works good ( in other pages i use the same without ajax and it works ) but i think the javascript part can't post the data in this case.
By the way there is not any problem with getting the values in the hidden parts.
Hope you can help.
the javascript part :
<script type=\"text/javascript\">
$(document).ready(function() {
$('.error').hide(); //Hide error messages
$('#MainResult').hide(); //we will hide this right now
$(\"#button\").click(function() { //User clicks on Submit button
var js_name = $(\"#name\").val();
var js_message = $(\"#message\").val();
var js_username = $(\"#username\").val();
var js_useremail = $(\"#useremail\").val();
var js_eventname = $(\"#eventname\").val();
if(js_name==\"\"){
$(\"#nameLb .error\").show(); // If Field is empty, we'll just show error text inside <span> tag.
return false;}
if( js_message==\"\"){
$(\"#messageLb .error\").show(); // If Field is empty, we'll just show error text inside <span> tag.
return false;}
var myData = 'postName='+ js_name + '&postMessage=' + js_message + '&username=' + js_username + '&useremail=' + js_useremail + '&eventname=' + js_eventname;
jQuery.ajax({
type: \"POST\",
url: \"invite.php\",
dataType:\"html\",
data:myData,
success:function(response){
$(\"#MainResult\").html('<fieldset class=\"response\">'+response+'</fieldset>');
$(\"#MainResult\").slideDown(\"slow\"); //show Result
$(\"#MainContent\").hide(); //hide form div slowly
},
error:function (xhr, ajaxOptions, thrownError){
$(\"#ErrResults\").html(thrownError);
}
});
return false;
});
$(\"#gobacknow\").live(\"click\", function() {
$(\"#MainResult\").hide(); //show Result
$(\"#MainContent\").slideDown(\"slow\"); //hide form div slowly
//clear all fields to empty state
$(\"#name\").val('');$(\"#message\").val('');
});
$(\"#OpenContact\").live(\"click\", function() {
$(\"#form-wapper\").toggle(\"slow\");
});
});
</script>
the html part:
<div id="form-wapper">
<div id="form-inner">
<div id="ErrResults"><!-- retrive Error Here --></div>
<div id="MainResult"><!-- retrive response Here --></div>
<div id="MainContent">
<fieldset>
<form id="MyContactForm" name="MyContactForm" method="post" action="">
<label for="name" id="nameLb">Email : <span class="error" style="font-size:10px; color:red;">Error.</span></label>
<input type="text" name="name" id="name" />
<label for="message" name="messageLb" id="messageLb">Message : <span class="error" style="font-size:10px; color:red;">Error.</span></label><textarea style="resize:vertical;" name="message" id="message" ></textarea>
<input type="hidden" name="username" id="username" value="<?php echo get_username($userid); ?>">
<input type="hidden" name="useremail" id="useremail" value="<?php echo get_email($userid); ?>">
<input type="hidden" name="eventname" id="eventname" value="<?php echo $eventname; ?>">
<br><button id="button">Send</button>
</form>
</fieldset>
</div>
<div style="clear:both;"></div>
</div>
invite php file :
$postName = filter_var($_POST["postName"], FILTER_SANITIZE_STRING);
$postMessage = filter_var($_POST["postMessage"], FILTER_SANITIZE_STRING);
$username = filter_var($_POST["username"], FILTER_SANITIZE_STRING);
$useremail = filter_var($_POST["useremail"], FILTER_SANITIZE_STRING);
$eventname= filter_var($_POST["eventname"], FILTER_SANITIZE_STRING);
invite($useremail, $postMessage , $username, $eventname, $postName); // this is a functipon that i use, it works in other cases, but not working in here
Rather than trying to debug that javascript, here is a much much easier / cleaner way to do this for the javascript AJAX post:
$.post('invite.php',$('#MyContactForm').serialize(),function(data){
if(data.success){
// all your on success stuff here
alert('success!');
}else{
// show error messages
alert(data.e);
}
},'json');
For your PHP part, echo a JSON response array, eg:
$data['success']=false;
$data['e']='Some error';
echo json_encode($data);