Can't get AJAX and PHP working - javascript

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

Related

Not posting jQuery form

I'm trying to post a form via Ajax, and I came across jQuery's POST, which sounds like the propper tool to use. I tried using the following html form:
<form id="my_form" action="http://localhost:4567/pedidos/guardar" method="POST">
Name:<br>
<input type="text" name="person_name"><br>
Amount:<br>
<input type="text" name="amount">
<br>
<input type="submit" value="Submit" id="submit_form">
</form>
<script type="text/javascript">
$('#submit_form').click( function() {
$.post( 'http://localhost:4567/pedidos/guardar', $('#my_form').serialize(), function(data) {
// ... do something with response from server
alert( "Data saved: " + data );
},
'json' // I expect a JSON response
);
});
</script>
This form was built based on this SO answer
I'm expecting to POST the form to /pedidos/guardar. On the server side, to test that the form is properly posted, I created a really small Sinatra script:
require 'sinatra'
require 'json'
not_found do
status 404
"This page could not be found"
end
get '/' do
"Hello World!"
end
get '/pedidos' do
{ :person_name => "#{params[:person_name]}" }.to_json
end
post '/pedidos/guardar' do
#{}"I got #{params[:person_name]}."
{ :person_name => "#{params[:person_name]}" }.to_json
end
When using my form, I'm getting {"person_name":"Juan"}, which is the expected response from Sinatra. But I'm not getting any alert window, it's like no Ajax is being used at all.
What am I missing in my form to make it work with Ajax? Do I need the action and method="POST" there?
Thanks in advance
You are sending your data throw ajax: $.post is a shorthand to $.ajax, but as the documentation explains it, you have to get a reference to the submit event and stop the default action.
$('#submit_form').click( function( event ) {
// Stop form from submitting normally
event.preventDefault();
Try replacing the script with this
$('#submit_form').click( function(){
$.ajax({
url: 'http://localhost:4567/pedidos/guardar',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify($('#my_form').serialize()),
success: function(data){
alert( "Data saved: " + data );
}
});
});
setting the contentType is for the response data type.

AJax not calling php file correctly, html forms

UPDATE:
This is the error:
412 (Precondition Failed)
I am trying to call a php script from ajax, I currently have the below ajax, which when the button in the form (also below) is clicked will call a php script passing it the form data, which will then be submitted to the database.
However, it is not working; and what's more I am just getting a blank error back, so I do not even know what is going wrong.
Could someon please point me in the right direction?
Thanks.
HTML form:
<form name="report-form" id="report-form" action="" method="POST">
<textarea id="reason-box" type="text" name="reason-box" cols="40" rows="5" maxlength="160" onkeypress=""></textarea>
<input id="reportedID" name="reportedID" type="text" />
<!--<input id="report-submit" value="" name="submit" type="submit" onclick="submitReport()"/> -->
<button id="report-submit" name="submit" onclick="submitReport()"></button>
</form>
AJax call:
function submitReport()
{
var ID=$('#reportedID').val();
var reason=$('#reason-box').val();
var formData = "ID="+ID+"&reason="+reason;
alert(formData);
//This code will run when the user submits a report.
$.ajax(
{
url: 'submit_report.php',
type: "POST",
data: formData,
success: function(data)
{
alert("Report Submitted!");
},
error: function(xhr,err)
{
alert(err.message);
alert("responseText: "+ xhr.responseText);
}
});
}
Now I have already tested the php script, and that works fine, the problem started when I added the ajax call so I know it is something to do with the ajax not the php.
This should correct the problem with submitting:
Your jQuery Ajax call won't succeed because the POST data isn't supplied in the correct format.
If the ajax should succeed the form is also posted resulting in a 405 error.
<button id="report-submit" name="submit" onclick="submitReport(event)"></button>
function submitReport(event)
{
event.preventDefault();
....... // your code
}
Now the default action of your form will be prevented (resulting in a 405 error). And only the ajax request is submitted.
In the button element we pass the event object on to the function. We use event.preventDefault() to make sure the button doesn't run it's default action, which is submitting the form.
You could also prevent this by deleting the form element as a wrapper, but maybe you want to use other features (like validation) on the form.
Form data in a jQuery ajax request needs to be an object called data:
var formData = {"ID" : ID, "reason" : reason};
jQuery will reform this to a correct query string for the submit.
I would do it like this:
<form name="report-form" id="report-form" action="" method="POST">
<textarea id="reason-box" type="text" name="reason-box" cols="40" rows="5" maxlength="160"></textarea>
<input id="reportedID" name="reportedID" type="text" />
<button id="report-submit" type="submit" name="submit" value="submit"></button>
</form>
<script type="text/javascript">
jQuery("document").ready(function(){
var $ = jQuery
$("form").submit(function(){
var data = "";
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
url: "submit_report.php",
data: data,
success: function(data)
{
alert("Report Submitted!");
},
error: function(xhr,err)
{
alert(err.message);
alert("responseText: "+ xhr.responseText);
}
});
return false;
});
});
</script>
and then use $reason=$_POST['reason-box']; and $ID=$_POST['reportedID']; inside your PHP script
this is optional to choose the form for submitting data or you can do it without the HTML form this is what i do
<textarea id="reasonbox" type="text" name="reason-box" cols="40" rows="5" maxlength="160" onkeypress=""></textarea>
<input id="reportedID" name="reportedID" type="text" />
<button id="report-submit" ></button>
and the using folloing javascript and jquery style
<script type="text/javascript">
$(function() {
$("#report-submit").click(function(){
try
{
$.post("your php page address goes here like /mypage.php",
{
//in this area you put the data that is going to server like line below
'reasonbox':$("#reason-box").val().trim(),
'reportedID':$("#reportedID").val().trim()
}, function(data){
data=data.trim();
//this is data is sent back from server you can send back data that you want
//like message or json array
});
}
catch(ex)
{
alert(ex);
}
});
});
</script>
I hope it helps

Why this ajax call is not working?

$(document).ready(function(){
$('.clickthetext').click(function(){
$.post("submit.php", $("#formbox").serialize(), function(response) {
$('#content').html(response);
});
return false;
});
});
My target to pass content from the form and edit the data and show response at current page.
.clickthetext button content:
<div class="clickthetext">Click here to see the result</div>
content inside id #formbox:
Part of the form inside this id. rest of the form is out side this id will be processed later. only content/input inside of id "formbox" will be processed.
Whatever response we will get, we will show inside of "#content" id.
What i am doing wrong here?
----edit----
i didn't add anything on submit.php
only to show response, i wrote there:
<?php
echo 'somthing blah blah blah something';
?>
Maybe there is a problem with the result of submit.php
You can try calling
$(document).ready(function(){
$('.clickthetext').click(function(){
$.ajax({
type: "POST",
url: "submit.php",
data: $("#formbox").serialize(),
success: function(response) { $('#content').html(response); },
error: function(jqXHR, textStatus, errorThrown) { console.log(textStatus, errorThrown); },
dataType: dataType
});
return false;
});
});
instead and get more detail of the result of the ajax call.
Here's the API for the ajax object in jQuery
Recreating your set up,
JS/HTML
<form action="" id="formbox">
<input type="text" name="firstName" value="First Name">
</form>
<button class="clickthetext">Button</button>
<div id="content"></div>
<script>
jQuery(document).ready(function ($) {
$('.clickthetext').click(function() {
$.post("submit.php", $("#formbox").serialize(), function (response) {
$('#content').html(response);
})
})
});
</script>
PHP: submit.php
<?php echo 'this is the response'; ?>
Everything works perfectly.
Debugging tips:
1) Most likely - Check your javascript console for any errors. You probably have errors elsewhere in the page.
2) Ensure you're accessing the HTML page with the javascript via localhost, not a filepath
3) Unlikely, but check your PHP log.

JQuery sends empty values

I dont get it... I reviewed my code hundred times and I dont get the error...
I am actually testing a bit with JQuery and AJAX and made a simple form with a textarea to submit. Without AJAX it works fine, but with, it sends always an empty value of my textarea...
The Javascript Code:
$(document).ready(function(e) {
$("#formPost input").attr("disabled", false);
$("#formPost input:submit").click(function() {
$.ajax({
type: 'POST',
url: 'post.php',
dataType: 'json',
data: $('#formPost').serialize(),
beforeSend: function(XMLHttpRequest) {
$("#formPost input").attr("disabled", true);
$("#formPost .ajaxloader").show();
},
success: function(data) {
var message = $("#flashMessage");
message.text(data.msg);
if(data.error) {
message.addClass("fail");
}
else {
message.addClass("success");
}
message.show();
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#formPost .ajaxloader').hide();
$('#flashMessage').removeClass().
addClass('fail').text('There was an error.').show();
},
complete: function(XMLHttpRequest) {
$("#formPost input").attr("disabled", false);
$("#formPost .ajaxloader").hide();
}
});
return false;
});
});
The HTML:
<div>
<h1>Add new post</h1>
<div id="flashMessage"></div>
<form id="formPost" method="post" action="post.php">
<textarea id="post" name="post"></textarea>
<input type="submit" value="Save" />
<div class="ajaxloader">
<img src="ajax-loader.gif" />
</div>
<div class="clear"></div>
</form>
</div>
I use Firebug and look under "Network" -> "XHR" -> "Post" and under Source he shows post=
So where is the value gone?
Your problem is related with CKEditor (as you said in the comment), because WYSIWYG editors replace the appearance of textarea and update value on form submit. So you have to use built-in functions of CKEditor for updating textarea's value manually as you are using Ajax. I can't help you specifically with CKEditor but this thread may help: CKEditor, AJAX Save .
You are disabling the form elements in the beforeSend method, but JQuery's serialize will ignore those disabled elements. Try removing that first to test. This SO question has some ways to get around it.

AJAX Mailchimp signup form integration

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.

Categories