Not posting jQuery form - javascript

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.

Related

Post on native php (without framework) Into Code Igniter using AJAX

I'm trying to post data on my HTML code to CI with Ajax. But I got no response?
Here is my JS Code
$(document).ready(function(){
$("#simpan").click(function(){
nama_pelanggan = $("#nama_pelanggan").val();
telp = $("#telp").val();
jQuery.ajax({
type: "POST",
url: "http://192.168.100.100/booking_dev/booking/addBookingViaWeb/",
dataType: 'json',
data : {
"nama_pelanggan":nama_pelanggan,
"telp":telp,
},
success: function(res) {
if (res){
alert(msg);
}
}
});
});
});
And here is my form
<form>
Nama Pelanggan <br>
<input type="text" name="nama_pelanggan" id="nama_pelanggan"><br>
Telepon<br>
<input type="text" name="telp" id="telp"><br>
<input type="button" name="simpan" id="submit" value="Simpan">
</form>
and here is my contoller function code
public function addBookingViaWeb(){
$data = array(
'nama_pelanggan' => $this->input->post('nama_pelanggan'),
'telp'=>$this->input->post('telp')
);
echo json_encode($data);
}
Here is my post param
But I got no response
any idea?
add method in from if you use post then
<form method="post" action ="" >
Try using JQuery form serialize() to declare which data you want to post. It automatically put your form input into ajax data. Example :
first set ID to your form tag
<form id="form">
then
$.ajax({
type:'POST',
url : 'http://192.168.100.100/booking_dev/booking/addBookingViaWeb/',
data:$('#form').serialize(),
dataType:'JSON',
success:function(data){
console.log(data);
}
});
First problem I see is in your ajax submission code. Change
$("#simpan").click(function(){
to
$("#submit").click(function(event){
Notice that I added the event parameter. You now need to prevent the default submission behavior. On the first line of your click method add
event.preventDefault();
Now I'm assuming that your url endpoint http://192.168.100.100/booking_dev/booking/addBookingViaWeb/ can handle POST requests. Usually this is done with something like PHP or Ruby on Rails. If I was doing this in PHP I would write something like the following:
<?php
$arg1 = $_POST["nama_pelanggan"];
$arg2 = $_POST["telp"];
// do something with the arguments
$response = array("a" => $a, "b" => $b);
echo json_encode($response);
?>
I personally don't know anything about handling POST requests with js (as a backend) but what I've given you should get the data over there correctly.
I got solution for my problem from my friend xD
just add header("Access-Control-Allow-Origin: *"); on controller function
Thank you for helping answer my problem.

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

Ajax request fail - retrieve user id from server

I have form that has one text input field and a button. On submit form, I take the value from the text field user and make an ajax call to ajax.php to then have the server return the userID. The server is indeed returning a value as shown in the console. But I am not sure why the ajax call is failing on each request after submitting the form. What can I correct or change to have a success?
index.php
$('form').submit(function(e) {
var searchUser = $('input[name="user"]').val();
var getUser = $.ajax({
type: "GET",
url: "ajax.php",
data: {user: searchUser},
dataType:'text'
});
getUser.done(function( data ) {
alert(data);
});
getUser.fail(function( jqXHR, textStatus, data ) {
alert( "Request failed: " + textStatus );
});
});
<form id="search" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="GET">
<label for="user"> Username:</label><input type="text" name="user" id="user" value="<?php echo $user ?>"><br>
<button type="submit" id="search">Search</button>
</form>
ajax.php
if(!empty($_GET['user'])){
$user = $_GET['user'];
echo getInstaID($user); // this prints a numeric value like 2057821
}
Perhaps the data is being returned as json or jsonp? You have specified dataType: 'text'. If the return datatype is different it will error out. If you are using a fairly recent version (I think 2.0 or better) leaving out dataType or specifying dataType:"auto" will allow the call to succeed. Then you can debug to figure out how to handle the response.
You might try adding a success function like the following:
$('form').submit(function(e) {
var searchUser = $('input[name="user"]').val();
$.ajax({
type: "GET",
url: "ajax.php",
data: {user: searchUser},
success:function(data){//begin success function
//do something with the data returned from ajax.php file
alert(data);
}//end success function
});

How do I use AJAX to print out data inside a div?

I have two files. One file is named index.php and another file is named process.php.
I have a form that submits to process.php in index.php:
<form class="form" action="process.php" method="POST" name="checkaddress" id="checkaddress">
<table>
<tr class="element">
<td><label>Address</label></td>
<td class="input"><input type="text" name="address" /></td>
</tr>
</table>
<input type="submit" id="submit" value="Submit"/>
</form>
<div class="done"></div>
I also have a process in process.php to echo some data based off of the input. How would I be able to use AJAX to submit the form without leaving the page?
Is it something like:
$.ajax({
url: "process.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
$('.done').fadeIn('slow');
}
});
What page would I put the above code on if it was right?
Also, how do I change the above code to say what the process.php outputted? For example, if I echo "Hello" on process.php, how do I make it say it in the done div?
I have seen many responses regarding AJAX, but they all rely on data that is pre-made like APIs. I need to do a database query and fetch the data dependent on the address entered and print the data out.
You need to collect the data in the form so that you can submit them to the process page, and you need to run your code when submitting the form (and cancel the default form submission)
$('#checkaddress').on('submit', function(e){
// get formdata in a variable that is passed to the ajax request
var dataToPassToAjax = $(this).serialize();
$.ajax({
url: "process.php",
type: "GET",
data: dataToPassToAjax,
cache: false,
success: function (resultHtml) {
// add the returned data to the .done element
$('.done').html( resultHtml ).fadeIn('slow');
}
});
// cancel the default form submit
return false;
});
[update]
If you want to modify the data before submitting them, you will have to manually create the parameters to pass to the ajax
$('#checkaddress').on('submit', function(e){
// get formdata in a variable that is passed to the ajax request
var dataToPassToAjax = {};
var address = $('input[name="address"]', this).val();
// alter address here
address = 'something else';
dataToPassToAjax.address = address;
$.ajax({
url: "process.php",
type: "GET",
data: dataToPassToAjax,
cache: false,
success: function (resultHtml ) {
// add the returned data to the .done element
$('.done').html(resultHtml ).fadeIn('slow');
}
});
// cancel the default form submit
return false;
});
You could use the jQuery form plugin: http://jquery.malsup.com/form/
Let me know if you want example code.

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