No alert in success function - php

I am trying to insert value in database from jquery ajax and i want whenever data insertion is successfull, a result output comes true other wise "error:failed". My entry in database successfully updated, but when i alert(msg), its doesnt give me message.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<body>
<div class="wrapper">
<div id="main" style="padding:50px 0 0 0;">
<!-- Form -->
<form id="contact-form" method="post">
<h3>Paypal Payment Details</h3>
<div class="controls">
<label>
<span>TagId</span>
<input placeholder="Please enter TagId" id="tagid" type="text" tabindex="1" >
</label>
</div>
<div class="controls">
<label>
<span>Paypal Email: (required)</span>
<input placeholder="All Payment will be collected in this email address" id="email" type="email" tabindex="2">
</label>
</div>
<div class="controls">
<label>
<span>Amount</span>
<input placeholder="Amount you would like to charged in GBP" id="amount" type="tel" tabindex="3">
</label>
</div>
<div class="controls">
<div id="error_div"></div>
</div>
<div>
<button name="submit" type="submit" id="form-submit">Submit Detail</button>
</div>
</form>
<!-- /Form -->
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#form-submit').click(function()
{
var tagid = $("#tagid").val();
var email = $("#email").val();
var amount = $("#amount").val();
var param = 'tagid='+ tagid + '&email=' + email + '&amount=' + amount;
param = param + '&type=assign_amount';
locurl = 'dbentry.php';
$.ajax({
url: locurl,
type:'post',
data:param,
success:function(msg)
{
alert(msg);
}
});
});
});
dbentry.php
<?php
$vals = $_POST;
include 'dbconfig.php';
if($vals['type'] == "assign_amount")
{
$values = assign_amount();
echo json_encode(array('status' =>$values));
}
function assign_amount()
{
global $con;
global $vals;
$sql = "INSERT INTO `dynamic_url`(`tagid`,`email`,`amount`) VALUES('".$vals['tagid']."','".$vals['email']."','".$vals['amount']."')";
$result = mysql_query($sql,$con);
if($result){
if( mysql_affected_rows() > 0 ){
$status="success";
}
}else{
$status="failed";
}
return $status;
}
?>

Try to echo it like
if($result){
if( mysql_affected_rows() > 0 ){
$status="success";
}
} else {
$status="failed";
}
return $status;
And in your if statement code like
if($vals['type'] == "assign_amount")
{
$values = assign_amount();
echo $values;
}
For the ajax return purpose you better to echo or print rather than return it.

In order to see alert() message, you have to prevent default behaviour of clicked submit button:
$('#form-submit').click(function(e)
{
e.preventDefault();
//....
}
Otherwise, the FORM is submited and page is reloaded.

Display $status at last in php file instead of return statement
You will get it in alert
echo $status;

Can you try this,
var locurl = 'dbentry.php';
$.ajax({
url: locurl,
type:'post',
data:param,
dataType:'json',
success:function(msg)
{
alert(msg.status.sql);
}
});

Your code has a lot of flaws in it. For instance you are contatenating the string to create a data object. But if somebody would enter a & or = or any other special charactor in it, your form would fail.
Also you are binding on the click function on a button. While this works, it would be useless for people without javascript. This might not be an issue, but its easily prevented with some minor changes.
I would change the <button name="submit" to <input type="submit" and then bind jQuery to the form it self. Also add the action attribute to the form to include 'dbentry.php'
$(function(){
$('#contact-form').submit(function(){
var $form = $(this);
var data = $form.serialize();
var locurl = 'dbentry.php';
$.post(locurl,data, function(msg) {
alert(msg.status)
}, 'json');
return false; //prevent regular submit
});
});
Now to make it work PHP has to return JSON data.
<?php
header('Content-type: application/json');
//your code that includes
echo json_encode(array('status' =>$sql));
//also notice that your code only returns data on success. Nothing on false.
?>

Related

Ajax code not working even if it is (i think) correct

The function that this do is when the user clicked the button, it will execute the Ajax codes and then get the value of the input and send it to the PHP file and then send it back to the Ajax code to display the message from the MySQL table.
I tried changing my codes, changing div ids, changing syntax, clearing block of codes but none seems to work.
AJAX
<script>
$(document).ready(function() {
$("#snd").click(function() {
var msgg = $('input[name=message]').val();
$.ajax({
type: "POST",
url: 'automatedchat_func.php',
data: {newmsg: msgg},
success: function(data) {
$("#conversation").html(data);
}
});
});
});
</script>
HTML UPDATED
<div class="convo">
<div class="convo_field" id="conversation">
</div>
<div class="obj">
<div class="txtbox">
<form method="POST">
<input type="input" id="msg" name="message" placeholder="Type exact or related word(s) of your question"/>
</form>
</div>
<div class="but_send"><button id="snd" name="send">SEND</button></div>
</div>
</div>
PHP UPDATED
<?php
include 'database/connect.php';
session_start();
$sql = "SELECT * FROM ai WHERE keywords LIKE '%$_POST[message]%' OR '$_POST[message]%_' OR '$_POST[message]_'";
$result = $conn->query($sql);
if ($row = $result->fetch_assoc()) {
echo "Hi ". $_SESSION['name'] .".<br> " . $row['message'];
}
?>
Changes with suggestion(in comment):-
<div class="convo">
<div class="convo_field" id="conversation">
</div>
<div class="obj">
<div class="txtbox">
<input type="input" id="msg" name="message" placeholder="Type exact or related word(s) of your question"/>
</div><!-- form not requird -->
<div class="but_send"><button id="snd" name="send">SEND</button></div>
</div>
</div>
<!-- Add jquery library so that jquery code wiil work -->
<script>
$(document).ready(function() {
$("#snd").click(function() {
var msgg = $('#msg').val(); // id is given so use that, its more easy
$.ajax({
type: "POST",
url: 'automatedchat_func.php',
data: {newmsg: msgg},
success: function(data) {
$("#conversation").html(data);
}
});
});
});
</script>
automatedchat_func.php(must be in the same working directory where your above html file exist)
<?php
error_reporting(E_ALL);// check all type of error
ini_set('display_errors',1);// display all errors
include 'database/connect.php';
session_start();
$final_result='';//a variable
if(isset($_POST['newmsg']) && !empty($_POST['newmsg'])){// its newmsg not message
$message = $_POST['newmsg'];
$sql = "SELECT * FROM ai WHERE keywords LIKE '%$message%' OR '$message%' OR '$message'"; // check the change ere
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) { // while needed
$final_result .="Hi ". $_SESSION['name'] .".<br> " . $row['message']."<br>";
}
}else{
$final_result .="Hi please fill the input box first";
}
echo $final_result; // send final result as response to ajax
?>
Note:- your query is still vulnerable to SQL Injection. So read for prepared statements and use them

Won't run ajax if I change input type..?

I have a form for user to update their info using jquery + Ajax. Everything is working great so far, but WHen i change input type="email" to input type="text" in the fullname section of the form and click update. It got error??? It won't run the php file in ajax. I don't see any connection which causes this error? Anyone please sugguest why? But if I change input type in the fullname section back to "email". It works! This is so weird!
Here is my form:
<div id="changeuserinfo_result"></div>
<form role="form" method="post">
<div class="form-group">
<label>Fullname</label>
<input type="text" class="form-control" id="changename" name="changename" value="<?php echo $_SESSION['name'] ?>">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" id="changepass" name="changepass" value="<?php echo $_SESSION['pass'] ?>">
</div>
<button class="btn btn-default" id="changeuserinfo">Update</button>
</form>
Here is my jquery code:
$(document).ready(function(){
$('#changename').focus();
$('#changeuserinfo').click(function(){
var changename = $('#changename');
var changepass = $('#changepass');
var changeuserinfo_result = $('#changeuserinfo_result');
changeuserinfo_result.html('loading...');
if(changename.val() == ''){
changename.focus();
changeuserinfo_result.html('<span class="errorss"> * Empty fullname</span>');
return false;
}
else if(changepass.val() == ''){
changepass.focus();
changeuserinfo_result.html('<span class="errorss">* Empty password</span>');
return false;
}
else {
var UrlToPass = {changename:changename.val(),changepass:changepass.val()} ;
$.ajax({
type : 'POST',
cache: false,
data : UrlToPass,
url : 'changeuserinfo.php',
success: function(responseText){
if(responseText == 1){
$('#changeuserinfo_result').html('<span style="color:green"> Update OK</span>');
}
else{
$('#changeuserinfo_result').html('<span class="errorss"> Update fail. Try again</span>');
}
}
});
}
});
});
You have no closing tags on your inputs.
It should be <input type="text"... />
Also set the doctype of the page to HTML5.
<!DOCTYPE HTML>
....
</html>

newbie ajax (jquery) issue

I'm pretty strong with PHP, but javascript is totally new to me.
I need to add various ajax functionality to my projects, for example for form validation etc.
I've done some searching, watched some tutorials, and come up with a basic working example as follows:
index.php:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Ajax form test</title>
<style>
form input, form textarea {
display:block;
margin:1em;
}
form label {
display:inline;
}
form button {
padding:1em;
}
</style>
</head>
<body>
<h2>CONTACT FORM</h2>
<div id="form_content">
<form method="post" action="server.php" class="ajax">
<label for="name" value="name">name:</label>
<input type="text" name="name" placeholder="name" />
<label for="email" value="email">email:</label>
<input type="email" name="email" placeholder="email" />
<label for="message" value="message">message:</label>
<textarea name="message" placeholder="message"></textarea>
<input type="submit" value="send">
</form>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="main.js"></script>
</body>
</html>
main.js:
$('form.ajax').on('submit', function() {
console.log('trigger');
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax ({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
$('#form_content').load('server.php', data);
}
});
return false;
});
and finally, server.php:
<?php
if (isset($_POST) AND $_POST['name'] !='' AND $_POST['email'] !='' AND $_POST['message'] !='')
{
?>
<h4>Your data was submitted as follows</h4>
<br />name: <?=$_POST['name']?>
<br />email: <?=$_POST['email']?>
<br />message: <?=$_POST['message']?>
<?php
} else {
?>
<h3>please fill in all form data correctly:</h3>
<form method="post" action="server.php" class="ajax">
<label for="name" value="name">name:</label>
<input type="text" name="name" placeholder="name" />
<label for="email" value="email">email:</label>
<input type="email" name="email" placeholder="email" />
<label for="message" value="message">message:</label>
<textarea name="message" placeholder="message"></textarea>
<input type="submit" value="send">
</form>
<?php
}
This all works fine, in that if I enter all form data and click submit, the ajax magic happens and I get a confirmation of the data. Also if not all data is loaded, the form is re-presented on the page. The problem is that in such a case, continuing to fill out the form data and then submit it loads the server.php page instead of repeating the ajax call until the form data is valid..
I'm sure there's a better way to do this as it's my first attempt, but I haven't been able to find any solution by searching either here or on google, but that's probably mostly because I don't really know what to search for. how can I make the behaviour in the first instance repeatable until the form is submitted correctly ?
This happens because you are removing your form element during your load() call and overwrite it with a new version of the form. Therefore all attached event handlers will vanish along with it.
You will need to use a delegate on an element that does not change:
$('#form_content').on('submit', 'form.ajax', function() {...});
Explanation:
In the above example, you attach the event listener to the #form_content element. However, it only listens to events that bubble up from the form.ajax submit event. Now, if you replace the form with a new version, the existing handler is attached higher up in the chain (on an element that doesn't get replaced) and continues to listen to events from lower elements, no matter if they change or not... therefore it will continue to work.
Your primary problem is that you are validating the form on the PHP side, when you should really validate it on the client side - THEN, instead of returning an appropriate response and continuing processing on the client side, you are finishing processing on the PHP side. Steve's answer (above) applies to what you are seeing.
As to the approach you have taken, it might be better to not use a <form> construction at all, because with AJAX you often don't need to. In my opinion, <form> is an archaic structure, not often needed in the age of AJAX. Notice how you had to add return false following the AJAX block to abort the default form functionality -- to stop it from sending the user over to server.php? That should tell you something.
Here is another way to structure it:
HTML:
<body>
<h2>CONTACT FORM</h2>
<div id="form_content">
<label for="name" value="name">name:</label>
<input type="text" name="name" placeholder="name" />
<label for="email" value="email">email:</label>
<input type="email" name="email" placeholder="email" />
<label for="message" value="message">message:</label>
<textarea name="message" placeholder="message"></textarea>
<input type="button" id="mybutt" value="send">
</div>
<div id="responseDiv"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="main.js"></script>
</body>
JAVASCRIPT/JQUERY:
$(document).ready(function() {
//Next line's construction only necessary if button is injected HTML
//$(document).on('click', '#mybutt', function() {
//Otherwise, use this one:
$('#mybutt').click(function() {
console.log('trigger');
var valid = "yes";
var that = $(this),
url = "server.php",
type = "POST",
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
if (value=="") valid = "no";
data[name] = value;
});
if (valid == "yes") {
$.ajax ({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
$('#responseDiv').html(response);
/* OPTIONALLY, depending on what you make the PHP side echo out, something like:
if (response == "allgood") {
window.location.href = "http://www.google.com";
}else{
//this is how you would handle server-side validation
alert('Please complete all fields');
}
*/
}
}); //END AJAX
}else{
alert('Please complete all fields');
}
}); //END button.click
}); //END document.ready
PHP Side: server.php
<?php
if (isset($_POST) AND $_POST['name'] !='' AND $_POST['email'] !='' AND $_POST['message'] !='') {
$r = '';
$r .= "<h4>Your data was submitted as follows</h4>";
$r .= "<br />name: " . $_POST['name'];
$r .= "<br />name: " . $_POST['email'];
$r .= "<br />name: " . $_POST['message'];
} else {
$r = "Please complete all form fields";
}
echo $r;

Ajax Data Posting

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);

Required alert on wordpress form

The contact form it´s working, if you fill it all it sends the message. The problem if you don´t fill in the email box, the form doesn´t alert you about it, is there anyway that I can show a word or somekind of alert to the user?
this is my markup:
<div class="form">
<h2>ESCRIBENOS</h2>
<form method="post" action="process.php">
<div class="element">
<label>Nombre (obligatorio):</label><br/>
<input type="text" name="name" class="text" />
</div>
<div class="element">
<label>Email (obligatorio):</label><br/>
<input type="text" name="email" class="text" />
</div>
<div class="element">
<label>Telefono:</label><br/>
<input type="text" name="website" class="text" />
</div>
<div class="element">
<label>Mensaje:</label><br/>
<textarea name="comment" class="text textarea" /></textarea>
</div>
<div class="element">
<input type="submit" id="submit"/>
<div class="loading"></div>
</div>
</form>
</div>
And this is my script:
$(document).ready(function() {
//if submit button is clicked
$('#submit').click(function () {
//Get the data from all the fields
var name = $('input[name=name]');
var email = $('input[name=email]');
var website = $('input[name=website]');
var comment = $('textarea[name=comment]');
//Simple validation to make sure user entered something
//If error found, add hightlight class to the text field
if (name.val()=='') {
name.addClass('hightlight');
return false;
} else name.removeClass('hightlight');
if (email.val()=='') {
email.addClass('hightlight');
return false;
} else email.removeClass('hightlight');
if (comment.val()=='') {
comment.addClass('hightlight');
return false;
} else comment.removeClass('hightlight');
//organize the data properly
var data = 'name=' + name.val() + '&email=' + email.val() + '&website=' +
website.val() + '&comment=' + encodeURIComponent(comment.val());
//disabled all the text fields
$('.text').attr('disabled','true');
//show the loading sign
$('.loading').show();
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "../process.php",
//GET method is used
type: "GET",
//pass the data
data: data,
//Do not cache the page
cache: false,
//success
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
//hide the form
$('.form').fadeOut('slow');
//show the success message
$('.done').fadeIn('slow');
//if process.php returned 0/false (send mail failed)
} else alert('Sorry, unexpected error. Please try again later.');
}
});
//cancel the submit button default behaviours
return false;
});
});
Can someone help me out please?
Try this:
var name = $('input[name=name]');
var email = $('input[name=email]');
var website = $('input[name=website]');
var comment = $('textarea[name=comment]');
//Simple validation to make sure user entered something
//If error found, add hightlight class to the text field
$('input[type=text]').each(function(){
if($(this).val().length == 0){
$(this).addClass('hightlight');
alert('Empty input field')
return false;
}
});
.... rest of your code
Note: This does not work for textarea but I think you can figure that out yourself!
EDIT:
var valid = false;
$('input[type=text]').each(function(){
if($(this).val().length == 0){
$(this).addClass('hightlight');
alert('Empty input field')
valid = false;
}else{
valid = true;
}
});
if(valid == false) return;
console.log('All input fields are filled in..');
... rest of your code. You can remove al the if else statements for input fields. For checking the textarea you could give all fields the same class and do:
$('form.classofallelements').each(function(){

Categories