AJAX Mailchimp signup form integration - javascript

Is there any way to integrate mailchimp simple (one email input) with AJAX, so there is no page refresh and no redirection to default mailchimp page.
This solution doesn't work jQuery Ajax POST not working with MailChimp
Thanks

You don't need an API key, all you have to do is plop the standard mailchimp generated form into your code ( customize the look as needed ) and in the forms "action" attribute change post?u= to post-json?u= and then at the end of the forms action append &c=? to get around any cross domain issue. Also it's important to note that when you submit the form you must use GET rather than POST.
Your form tag will look something like this by default:
<form action="http://xxxxx.us#.list-manage1.com/subscribe/post?u=xxxxx&id=xxxx" method="post" ... >
change it to look something like this
<form action="http://xxxxx.us#.list-manage1.com/subscribe/post-json?u=xxxxx&id=xxxx&c=?" method="get" ... >
Mail Chimp will return a json object containing 2 values: 'result' - this will indicate if the request was successful or not ( I've only ever seen 2 values, "error" and "success" ) and 'msg' - a message describing the result.
I submit my forms with this bit of jQuery:
$(document).ready( function () {
// I only have one form on the page but you can be more specific if need be.
var $form = $('form');
if ( $form.length > 0 ) {
$('form input[type="submit"]').bind('click', function ( event ) {
if ( event ) event.preventDefault();
// validate_input() is a validation function I wrote, you'll have to substitute this with your own.
if ( validate_input($form) ) { register($form); }
});
}
});
function register($form) {
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'json',
contentType: "application/json; charset=utf-8",
error : function(err) { alert("Could not connect to the registration server. Please try again later."); },
success : function(data) {
if (data.result != "success") {
// Something went wrong, do something to notify the user. maybe alert(data.msg);
} else {
// It worked, carry on...
}
}
});
}

Based on gbinflames' answer, I kept the POST and URL, so that the form would continue to work for those with JS off.
<form class="myform" action="http://XXXXXXXXXlist-manage2.com/subscribe/post" method="POST">
<input type="hidden" name="u" value="XXXXXXXXXXXXXXXX">
<input type="hidden" name="id" value="XXXXXXXXX">
<input class="input" type="text" value="" name="MERGE1" placeholder="First Name" required>
<input type="submit" value="Send" name="submit" id="mc-embedded-subscribe">
</form>
Then, using jQuery's .submit() changed the type, and URL to handle JSON repsonses.
$('.myform').submit(function(e) {
var $this = $(this);
$.ajax({
type: "GET", // GET & url for json slightly different
url: "http://XXXXXXXX.list-manage2.com/subscribe/post-json?c=?",
data: $this.serialize(),
dataType : 'json',
contentType: "application/json; charset=utf-8",
error : function(err) { alert("Could not connect to the registration server."); },
success : function(data) {
if (data.result != "success") {
// Something went wrong, parse data.msg string and display message
} else {
// It worked, so hide form and display thank-you message.
}
}
});
return false;
});

You should use the server-side code in order to secure your MailChimp account.
The following is an updated version of this answer which uses PHP:
The PHP files are "secured" on the server where the user never sees them yet the jQuery can still access & use.
1) Download the PHP 5 jQuery example here...
http://apidocs.mailchimp.com/downloads/mcapi-simple-subscribe-jquery.zip
If you only have PHP 4, simply download version 1.2 of the MCAPI and replace the corresponding MCAPI.class.php file above.
http://apidocs.mailchimp.com/downloads/mailchimp-api-class-1-2.zip
2) Follow the directions in the Readme file by adding your API key and List ID to the store-address.php file at the proper locations.
3) You may also want to gather your users' name and/or other information. You have to add an array to the store-address.php file using the corresponding Merge Variables.
Here is what my store-address.php file looks like where I also gather the first name, last name, and email type:
<?php
function storeAddress(){
require_once('MCAPI.class.php'); // same directory as store-address.php
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('123456789-us2');
$merge_vars = Array(
'EMAIL' => $_GET['email'],
'FNAME' => $_GET['fname'],
'LNAME' => $_GET['lname']
);
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "123456a";
if($api->listSubscribe($list_id, $_GET['email'], $merge_vars , $_GET['emailtype']) === true) {
// It worked!
return 'Success! Check your inbox or spam folder for a message containing a confirmation link.';
}else{
// An error ocurred, return error message
return '<b>Error:</b> ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>
4) Create your HTML/CSS/jQuery form. It is not required to be on a PHP page.
Here is something like what my index.html file looks like:
<form id="signup" action="index.html" method="get">
<input type="hidden" name="ajax" value="true" />
First Name: <input type="text" name="fname" id="fname" />
Last Name: <input type="text" name="lname" id="lname" />
email Address (required): <input type="email" name="email" id="email" />
HTML: <input type="radio" name="emailtype" value="html" checked="checked" />
Text: <input type="radio" name="emailtype" value="text" />
<input type="submit" id="SendButton" name="submit" value="Submit" />
</form>
<div id="message"></div>
<script src="jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#signup').submit(function() {
$("#message").html("<span class='error'>Adding your email address...</span>");
$.ajax({
url: 'inc/store-address.php', // proper url to your "store-address.php" file
data: $('#signup').serialize(),
success: function(msg) {
$('#message').html(msg);
}
});
return false;
});
});
</script>
Required pieces...
index.html constructed as above or similar. With jQuery, the appearance and options are endless.
store-address.php file downloaded as part of PHP examples on Mailchimp site and modified with your API KEY and LIST ID. You need to add your other optional fields to the array.
MCAPI.class.php file downloaded from Mailchimp site (version 1.3 for PHP 5 or version 1.2 for PHP 4). Place it in the same directory as your store-address.php or you must update the url path within store-address.php so it can find it.

For anyone looking for a solution on a modern stack:
import jsonp from 'jsonp';
import queryString from 'query-string';
// formData being an object with your form data like:
// { EMAIL: 'emailofyouruser#gmail.com' }
jsonp(`//YOURMAILCHIMP.us10.list-manage.com/subscribe/post-json?u=YOURMAILCHIMPU&${queryString.stringify(formData)}`, { param: 'c' }, (err, data) => {
console.log(err);
console.log(data);
});

Based on gbinflames' answer, this is what worked for me:
Generate a simple mailchimp list sign up form , copy the action URL and method (post) to your custom form. Also rename your form field names to all capital ( name='EMAIL' as in original mailchimp code, EMAIL,FNAME,LNAME,... ), then use this:
$form=$('#your-subscribe-form'); // use any lookup method at your convenience
$.ajax({
type: $form.attr('method'),
url: $form.attr('action').replace('/post?', '/post-json?').concat('&c=?'),
data: $form.serialize(),
timeout: 5000, // Set timeout value, 5 seconds
cache : false,
dataType : 'jsonp',
contentType: "application/json; charset=utf-8",
error : function(err) { // put user friendly connection error message },
success : function(data) {
if (data.result != "success") {
// mailchimp returned error, check data.msg
} else {
// It worked, carry on...
}
}

As for this date (February 2017), it seems that mailchimp has integrated something similar to what gbinflames suggests into their own javascript generated form.
You don't need any further intervention now as mailchimp will convert the form to an ajax submitted one when javascript is enabled.
All you need to do now is just paste the generated form from the embed menu into your html page and NOT modify or add any other code.
This simply works. Thanks MailChimp!

Use jquery.ajaxchimp plugin to achieve that. It's dead easy!
<form method="post" action="YOUR_SUBSCRIBE_URL_HERE">
<input type="text" name="EMAIL" placeholder="e-mail address" />
<input type="submit" name="subscribe" value="subscribe!" />
<p class="result"></p>
</form>
JavaScript:
$(function() {
$('form').ajaxChimp({
callback: function(response) {
$('form .result').text(response.msg);
}
});
})

This Github code works perfectly for me. This has a detailed explanation of how to use it. I use it on my WP site. Here is the link -
https://gist.github.com/DmitriyRF/34f659dbbc02637cf7465e2efdd37ef5

In the other hand, there is some packages in AngularJS which are helpful (in AJAX WEB):
https://github.com/cgarnier/angular-mailchimp-subscribe

I wasn't able to get this working with fetch so had to combine a few answers here using GET and parsing form inputs into the query string for the URL. It also wasn't necessary for the name of the input to be EMAIL but I guess it makes it more legible and doesn't break the code (in this simple case. Play around if you have other form fields).
Here's my code;
<form action="https://me.usxx.list-manage.com/subscribe/post-json?" id="signup" method="GET">
<input type="hidden" name="u" value="xxxxxxxxxxxxxxxxxx"/>
<input type="hidden" name="id" value="xxxxxxxxx"/>
<input type="hidden" name="c" value="?"/>
<input name="EMAIL" type="text" />
</form>
// Form submission handler
const formData = new FormData(signup);
fetch(signup.action + new URLSearchParams(formData).toString(), {
mode: 'no-cors',
method: signup.method,
})
.then((res) => {
// Success
})
.catch((e) => {
// Error
})
You could make it no-js friendly with...
<form action="https://me.usxx.list-manage.com/subscribe/post" id="signup">
fetch(signup.action + '-json?' + new URLSearchParams(formData).toString(), {
And just to save those who fumbled around as I did needlessly, you must create a signup form for an Audience within Mailchimp and by visiting that page you can get your u value and id as well as the action. Maybe this was just me but I thought that wasn't explicitly clear.

Related

Stop submitting if innerHTML value is equal to specified value

I'm designing a web page which checks if an email specified is available is database. If it is available, then i must stop submitting the form.
I used ajax for live checking of email and update the response as a span message. If i click submit button, even though the email is already available in the db, the form is submitted and getting redirected to another page. Please do help me get out of this. Thanks in advance.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
function checkemail() {
var email=document.getElementById( "UserEmail" ).value;
if(email) {
$.ajax({
type: 'post',
url: 'check.php',
data: {
user_email:email,
},
success: function (response) {
$( '#email_status' ).html(response);
}
});
}
}
function validateForm(){
var a=document.getElementById("email_status").innerHTML;
var b="Email Already Exist";
if(a==b)
alert('Yes');
else
alert('No');
}
</script>
</head>
<body>
<form method="POST" action="insertdata.php" onsubmit="return validateForm();">
<input type="text" name="useremail" id="UserEmail" onkeyup="checkemail();">
<span id="email_status"></span><br>
<input type="submit" name="submit_form" value="Submit">
</form>
Expected result when i give an email which is already in db:
Yes.
Actual result:
No
You code has design problems.
1.The biggest one is that you are make an ajax call request while user is typing, that will probably cause you big overhead.
2. the same design is causing the validation not working properly.
Allow me to make a proposal.
<form method="POST" action="insertdata.php" id="form" onsubmit="return false;">
<input type="text" name="useremail" id="UserEmail" >
<span id="email_status"></span><br>
<input type="submit" name="submit_form" value="Submit" onClick="checkemail();">
</form>
in this approach i have removed the keyup event form the input and have added the function checkemail() on button click.
var emails = [];
function checkemail() {
var email = document.getElementById('UserEmail').value;
if (email) {
if (!emails.includes(email)) {
$.ajax({
type: 'post',
url: 'check.php',
data: {
user_email: email,
},
success: function (response) {
$('#email_status').html(response);
if (response == 'Email Already Exist') {
console.log("email "+email+" is a spam")
emails.push(email);
} else {
document.getElementById('form').setAttribute('onsubmit', 'return true;');
document.getElementById('form').submit;
}
}
});
}else{
console.log("email "+email+" is a spam")
}
}
}
In this design approach code does
1.on button click executes checkemail function
2.checkemail function checks the emails array if contains the email from the text input, if the email is in the array then a log is written in console, if not then an ajax requset is done.
3.if the email is in the db then an other log is made, else the form is submitted.
This approach provides the ability of keeping every email that the user will possible write. I also suggest your ajax script instead of returning a text message to return a code maybe 0 or 1, that way comparison is safer.
Last but not least, although i don't know where you intend to use that code please keep in mind that a bot will probably bypass this java script code and hit directly your server side script. So you should think of a server side check also.
If you need more help or clarifications don't hesitate to ask.

Can't get AJAX and PHP working

So here is the scenario:
I have HTML, JS, and PHP Files. Within the PHP File is an associative array of default values to fill out various form elements on the HTML file. I am attempting to use AJAX to take the files from the PHP Files, and put them in the corresponding form elements. However nothing is working.....
Below is the code for the corresponding files. Any help figuring this out is greatly appreciated :)
HTML
<html>
<body>
<h1>Form Validation</h1>
<form id="PersonForm">
Name: <input type="text" id="name" name="name"> <br>
Postal Code: <input type="text" id="postal" name="postal"> <br>
Phone Number: <input type="text" id="phone" name="phone"> <br>
Address: <input type="text" id="address" name="address"> <br>
<input type="submit">
</form>
Refresh
<a id="InsertDefault" href="">Insert Default Data</a>
<br>
<ul id="errors"></ul>
<p id="success"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
PHP
<?php
// Return JSON default data if requested
if ($_REQUEST['act'] == 'default')
{
$defaultData = array('name' => "Jane",
'postal' => "L5B4G6",
'phone' => "9055751212",
'address' => "135 Fennel Street");
echo json_encode($defaultData);
}
?>
JAVASCRIPT
$(document).ready(function()
{
$("#InsertDefault").click(function()
{
// make an AJAX call here, and place results into the form
$.post('backend.phps',
{ act: 'default' },
function(data) {
for (var key in data) {
document.getElementById(key).value = data[key] }
},
'json');
// prevents link click default behaviour
return false;
});
});
As a side note, I always have trouble with web development stuff because I have no idea how to properly debug what I am doing. If anyone has any tips on what are some useful tricks/tools to use for debugging web code, I'd be more than happy to get some input on that too.
Thanks for your time.
For ajax code request use:
$("#InsertDefault").click(function(){
$.ajax({
type: "POST",
url: "backend.phps",
data: "act=default&name=test&phone=test", //Something like this
success: funtion(msg){
console.log(msg);
},
beforeSend:function(dd){
console.log(dd)
}
});
});
and in your backend.php file
if ($_REQUEST['act'] == 'default'){
//echo $_REQUEST['name'];
}
And for simple debugging use browsers' console, right click on the page and click Inspect Element. (Simple)
You can also install Firebug extension on Mozilla Firefox and then right click on the page and click on inspect Element with firebug. after this click on the Console tab there.
These are the basic and simple debugging for simple ajax request.
Per the newest Ajax documentation your ajax should include the Success and Failure callbacks where you can handle the response being sent from your PHP.
This should work with you existing PHP file.
Ajax
$(document).ready(function () {
//look for some kind of click below
$(document).on('click', '#InsertDefault', function (event) {
$.ajax({
url: "/backend.phps",
type: 'POST',
cache: false,
data: {act: 'default'},
dataType: 'json',
success: function (output, text, error)
{
for (var key in output.defaultData) {
document.getElementById(key).value = data[key]
}
},
error: function (jqXHR, textStatus, errorThrown)
{
//Error handling for potential issues.
alert(textStatus + errorThrown + jqXHR);
}
})
})
preventDefault(event);
});

Extracting data from HTML form with inputs with JavaScript or AJAX and then passing it on to PHP

I have an issue I can't seem to solve, I have a form with a bunch of text-fields but I need to extract their information through AJAX or just through a simple JavaScript function. I need this data to be extracted, string by string into an array which should then be passed to PHP. If understood this correctly, AJAX can be used with JQuery or JavaScript, now I'm not sure I understand JQuery very well. Anyway I've been searching google for good examples, and I really can't find anything good.
<form class="registration" method="POST">
<ul class="registration">
<li><label>Nombre de Usuario:</label></li>
<li><input type="text" name="username" title="Nombre de Usuario"/></li>
<li><label>Contraseña:</label></li>
<li><input type="text" name="password" title="Contraseña"/></li>
<li><label>Correo Electrónico:</label></li>
<li><input type="text" name="email" title="Correo Electrónico"/></li>
<li><label>Nombre:</label></li>
<li><input type="text" name="name" title="Nombre"/></li>
<li><label>Primer Apellido:</label></li>
<li><input type="text" name="first last name" title="Primer Apellido"/></li>
<li><label>Segundo Apellido:</label></li>
<li><input type="text" name="second last name" title="Segundo Apellido"/></li>
<li><input type="submit" name="create user" title="Crear Usuario" value="Crear Usuario"></input></li>
</ul>
</form>
This is my form, some of the values are in Spanish, the website I'm supposed to make has to be in that language. If I understood things right, I should call the function I want with an "OnClick" through my submit input button. This is the first time I've done web development, and understanding CSS and HTML was difficult for me. I was wondering if someone could help me out with an example or something. I'm basically using MVC to organize this, with HTML and JavaScript as the View, PHP as the control and Oracle SQL as the model. I'm using PHP precisely for that reason, I need to connect to the database, and send the information through PHP.
I'm not looking for anyone to fix my thing or anything of the sort, all I need is an example and small explanation if possible.
You need to figure out $.ajax function. It easy to implement, and posting the values into your php file, then from there you can processing inserting data into database. Here is sample of code :
$('input[type=submit]').on('click',function(e)
{
e.preventDefault();
var my_username = $('input[name=username]').val();
.....
..... more here
$.ajax({
type : 'POST', //<--- GET or POST
url : 'url_of_insert_process.php',
data : {
username: my_username,
.....
..... more here
}
success : function(data){
// Here you can populate the view whatever you want
// like showing message success
}
});
});
That is the illustration sending the data. You also can use $("form" ).serialize(); to fetch all the form element value using the name that you provided on each html form element. So many sources out there that you can put into your table.
Please try
$(document).ready(function(){
$('input[type="submit"]').click(function(e){
e.preventDefault();
$.ajax({
url: "YOUR_URL",
type: 'POST',
data:$("form#registration").serialize(),
success: function( response ) {
console.log(response);
}
});
});
});
//jsfile.js
//THIS METHOD RETURN THE name : value PAIR FROM
//A SPECIFIED FORM ID OR FORM IN THE CURRENT SPHERE
function formHandler(formID="") {
try {
if (formID === "") {
//PICK UP THE FORM IN THE CURRENT SPHERE
formElms document.querySelectorAll("input,select,textarea");
} else if(formID !== "") {
//PICK UP THE NAMED FORM
var formsElms = document.querySelectorAll("form");
formsElms.forEach(function(formElm) {
if (formElm.id === formID) {
formElms = document.querySelectorAll("#"+formID+" input, #"+formID+" select, #"+formID+" textarea");
}
});
}
if (formElms) {
var retObjs = new Array();
if (formElms) {
formElms.forEach(function(param) {
retObjs.push({name : param.name, value: param.value});
});
}
}
return retObjs;
} catch (e) {
console.log(e);
}
}
serverSideHandler(inda={}) {
try {
indata = inda;
complUrl = "url.php";
$.ajax({
method: "POST",
url: complUrl,
data: indata
})
.done(function(retData) {
serverResponseHandler(retData);//Function To Callback
});
} catch(ev) {
console.log(ev);
}
}
//url.php
<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: text/json');
ini_set('memory_limit','1024M');
if (!empty($_POST)) {
//Extract your form Inputs as follow
$name = doSomeValidation($_POST['name']);
//Do DB connections
//Do your CRUD
//DO OTHER ACTIONS
}

Popuating form fields from MySQL using AJAX and Jquery

I followed a tutorial to adapt the code. Here I am trying trying to auto-populate my form fields with AJAX when an 'ID' value is provided. I am new to Jquery and can't get to work this code.
Edit 1 : While testing the code, Jquery isn't preventing the form to submit and sending the AJAX request.
HTML form
<form id="form-ajax" action="form-ajax.php">
<label>ID:</label><input type="text" name="ID" /><br />
<label>Name:</label><input type="text" name="Name" /><br />
<label>Address:</label><input type="text" name="Address" /><br />
<label>Phone:</label><input type="text" name="Phone" /><br />
<label>Email:</label><input type="email" name="Email" /><br />
<input type="submit" value="fill from db" />
</form>
I tried changing Jquery code but still I couldn't get it to work. I think Jquery is creating a problem here. But I am unable to find the error or buggy code. Please it would be be very helpful if you put me in right direction.
Edit 2 : I tried using
return false;
instead of
event.preventDefault();
to prevent the form from submitting but still it isn't working. Any idea what I am doing wrong here ?
Jquery
jQuery(function($) {
// hook the submit action on the form
$("#form-ajax").submit(function(event) {
// stop the form submitting
event.preventDefault();
// grab the ID and send AJAX request if not (empty / only whitespace)
var IDval = this.elements.ID.value;
if (/\S/.test(IDval)) {
// using the ajax() method directly
$.ajax({
type : "GET",
url : ajax.php,
cache : false,
dataType : "json",
data : { ID : IDval },
success : process_response,
error: function(xhr) { alert("AJAX request failed: " + xhr.status); }
});
}
else {
alert("No ID supplied");
}
};
function process_response(response) {
var frm = $("#form-ajax");
var i;
console.dir(response); // for debug
for (i in response) {
frm.find('[name="' + i + '"]').val(response[i]);
}
}
});
Ajax.php
if (isset($_GET['action'])) {
if ($_GET['action'] == 'fetch') {
// tell the browser what's coming
header('Content-type: application/json');
// open database connection
$db = new PDO('mysql:dbname=test;host:localhost;', 'xyz', 'xyz');
// use prepared statements!
$query = $db->prepare('select * from form_ajax where ID = ?');
$query->execute(array($_GET['ID']));
$row = $query->fetch(PDO::FETCH_OBJ);
// send the data encoded as JSON
echo json_encode($row);
exit;
}
}
I don't see where you're parsing your json response into a javascript object (hash). This jQuery method should help. It also looks like you're not posting your form using jquery, but rather trying to make a get request. To properly submit the form using jquery, use something like this:
$.post( "form-ajax.php", $( "#form-ajax" ).serialize() );
Also, have you tried adding id attributes to your form elements?
<input type="text" id="name" name="name"/>
It would be easier to later reach them with
var element = $('#'+element_id);
If this is not a solution, can you post the json that is coming back from your request?
Replace the submit input with button:
<button type="button" id="submit">
Note the type="button".
It's mandatory to prevent form submition
Javascript:
$(document).ready(function() {
$("#submit").on("click", function(e) {
$.ajax({type:"get",
url: "ajax.php",
data: $("#form-ajax").serialize(),
dataType: "json",
success: process_response,
error: function(xhr) { alert("AJAX request failed: " + xhr.status); }
});
});
});

javascript return from php no updating anything

Hard to explain in the title...
So i have a form which is validated via javascript and an ajax request is sent to a php page which if succesful inputs the data and sets the database response.
However, on the ajax call getting the correct repsonse it doesnt carry out what i wish it to...
I What i want to happen is when the php returns a success JSON return, the .commentsdiv is reloaded.
This doesnt work however. But the comments are added into the database.
here is the code
part of commentsbox div and form:
<div class="commentsbox">
<form class="addcomment" action="process/addcomment.php" method="post">
<input type="hidden" class="postid" name="postid" value="'.$postID.'">
<input type="hidden" class="usernameuser" name="usernameuser" value="'.$usernameuser.'">
<input type="hidden" class="userid" name="userid" value="'.$userid.'">
<input type="text" name="addpostcomment" class="addpostcomment" placeholder="Add Comment..." />
<input type="submit" id="addcommentbutton" value="Post" />
<br />
<br />
</form>
</div>
Here is the javascript:
The viewbuild.php url is dynamic depending on what post is viewed. Do i need it to be like viewbuild.php?id=1 etc? Because that doesnt work niether.
// JavaScript - Edit Post
$(document).ready(function(){
$(".addcomment").submit(function(){
var $targetForm = $(this);
$targetForm.find(".error").remove();
$targetForm.find(".success").remove();
// If there is anything wrong with
// validation we set the check to false
var check = true;
// Get the value of the blog update post
var $comment = $targetForm.find('.addpostcomment'),
newcomment = $comment.val();
// Validation
if (newcomment == '') {
check = false;
$comment.after('<br><br><br><div class="error">Text Is Required</div>');
}
// ... goes after Validation
$.ajax({
type: "POST",
url: "process/addcomment.php",
data: $targetForm.serialize(),
dataType: "json",
success: function(response){
if (response.databaseSuccess) {
$('.commentsbox').load('viewbuild.php');
}
else {
$ckEditor.after('<div class="error">Something went wrong!</div>');
}
}
});
return false;
});
});
Here is part end of php:
$return['databaseSuccess'] = $dbSuccess;
echo json_encode($return);
Any help is most appreciated! :)
Make sure your php response is setting the proper headers. You need to set the content type as "application/json" for JQuery to call the success function. Try adding debugging to the error or complete callbacks when you call the jquery ajax function.
well , why am i thinking that you should check what value the obj returns ..
i mean ..
if(response.databaseSuccess == ??! ) { ... }
Or why don't you just check for the length of the retruned string.
if(response.databaseSuccess.length > 3){ alert('ok');}
One advise bro, if you are returning JUST one parameter .. use e string .. not JSON .. ;)
so, in php you would have :
echo $databaseSuccess;
And in JS .. the IF wil be more simple :
if(response == "ok"){ alert('ok');}
Get it ?
Hope i've helped.

Categories