Integrating AJAX with mailchimp - ajax

I'm trying to integrate AJAX with a mailchimp form. I’ve followed another member’s answer but still cannot get it to work. Could you guys see what's wrong with my code?
Thank you.
Here is my code:
<form id="form">
<script>
$( "button" ).click(function() {
formData = {
u: "xxxxxxxxx",
id: "xxxxxxxxx"
};
$.ajax({
url: "http://xxxxxxxxxxxxxxxxxxxxxxx/post-json?",
type: "GET",
crossDomain: true,
contentType: 'application/json',
data: formData,
dataType: "json",
success: function(data) {
//action
},
error: function() {
//action
}
});
});
</script>
<fieldset>
<label for="email_input_id"><input placeholder=
"Type Your Email" type="email" /></label>
</fieldset><button type= "submit">Submit</button>

I finally got my code working.
<form id="form" action="https://xxxxx.com/subscribe/post-json?u=xxxxx&id=xxxx&c=?" method="GET">
<input type="hidden" name="u" value="xxxx">
<input type="hidden" name="id" value="xxxx">
<input type="EMAIL" autocapitalize="off" autocorrect="off"
name="MERGE0" id="MERGE0" size="25" value=""
placeholder="Type your email and press enter">
<p id="response"> </p>
</form>
<script>
$('#form').submit(function(e) {
var $this = $(this);
var paragraph = document.getElementById('response');
$.ajax({
type: "GET",
url: "https://xxx.com/subscribe/post-json?u=xx&id=xx&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") {
paragraph.innerHTML = data.msg;
} else {
paragraph.innerHTML = data.msg;
}
}
});
return false;
});
</script>

Related

Get value of submit button from Ajax call

The value of the submit buttons are always null in the Action.
What do I need to change to know which submit button has been clicked?
<form id="actionInvitation">
<div>
<ul>
<li>
#Model.TeamInviteBy
</li>
</ul>
</div>
<input type="submit" name="actionBtn" id="acceptBtn" value="Accept Invitation" />
<input type="submit" name="actionBtn" id="declineBtn" value="Decline Invitation" />
</form>
$('#actionInvitation').submit(function (e) {
e.preventDefault();
var formData = new FormData($('#actionInvitation')[0]);
$.ajax({
url: '#Url.Action("ActionInvitation", "Home")',
type: 'post',
cache: false,
processData: false,
contentType: false,
data: formData,
success: function (data) {
$("#invitationActionMessage").append('Invitation Accepted');
}
});
});
//Action
public async Task<IActionResult> ActionInvitation(UserViewModel userViewModel, string acceptBtn, string declineBtn)
Your formData will not contain the objects you need to pass.
You can change your code like below:
<form id="actionInvitation">
<div>
<ul>
<li>
#Model.TeamInviteBy
<input type="hidden" name="TeamInviteBy" value="#Model.TeamInviteBy">
</li>
</ul>
</div>
<input type="submit" name="actionBtn" onclick="Send(event,this)" value="Accept Invitation" />
<input type="submit" name="actionBtn" onclick="Send(event,this)" value="Decline Invitation" />
</form>
#section scripts{
<script>
function Send(ev,el) {
ev.preventDefault();
var data = $("input[name='TeamInviteBy']").val();
var value = $(el).val();
$.ajax({
url: '#Url.Action("ActionInvitation", "Home")',
type: 'post',
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data: { TeamInviteBy: data, actionBtn: value},
success: function (data) {
$("#invitationActionMessage").append('Invitation Accepted');
}
});
}
</script>
}
Action:
public async Task<IActionResult> ActionInvitation( UserViewModel userViewModel , string actionBtn)
{
if(actionBtn="Accept Invitation")
{
//...
}
else
{
}
}
Result:

AJAX - upload image with ajax without form on laravel

i try to make upload image with ajax without form, when i am sent data without the image, data successfully submitted to the database, but when i am adding an image, when i try to submit, no response at all,
this is my template code :
<input type="hidden" name="lesson_id" value="{{-- $lessons->id --}}">
<input type="hidden" name="parent_id" value="0"> -->
<div class="form-group">
<label>Komentar</label>
<textarea rows="8" cols="80" class="form-control" name="body" id="textbody0"></textarea>
</div>
<ul class="right">
<input type="file" name="image" id="image" />
<img id="myImg" src="#" />
<button type="button" class="btn btn-primary" onClick="doComment({{ $lessons->id }},0)" >Kirim</button>
and this is my script for submit data :
function doComment(lesson_id, parent_id) {
var body = $('#textbody'+parent_id).val();
var image = $('#image').prop('files')[0];
if (body == '') {
alert('Harap Isi Komentar !')
}else {
var postData =
{
"_token":"{{ csrf_token() }}",
"lesson_id": lesson_id,
"parent_id": parent_id,
"image": image,
"body": body
}
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="token"]').attr('value')
}
});
$.ajax({
type :'POST',
url :'{{ url("lessons/coments/doComment") }}',
dataType: 'json',
data : postData,
beforeSend: function(){
// Show image container
swal({
title: "Sedang mengirim Komentar",
text: "Mohon Tunggu sebentar",
imageUrl: "{{ asset('template/web/img/loading.gif') }}",
showConfirmButton: false,
allowOutsideClick: false
});
{{-- $("#loader").show(); --}}
},
success:function(data){
if (data.success == false) {
window.location.href = '{{ url("member/signin") }}';
}else if (data.success == true) {
$('#textbody'+parent_id).val('');
swal({
title: "Komentar anda sudah terkirim!",
showConfirmButton: true,
timer: 3000
});
getComments();
}
}
});
}
}
Can any one help me?
postData = new FormData();
if(!!file.type.match(/image.*/)){
postData.append("image", file);
$.ajax({
type : 'POST',
url : '{{ url("lessons/coments/doComment") }}',
data : postData,
dataType: 'json',
processData: false,
contentType: false,
success: function(data){
alert('success');
}
});
}else{
alert('Not a valid image!');
}

File Data is blank array in server side: Laravel 5.3

I am trying to post File using JQuery. Below is my code.
<script language="javascript">
$(document).ready(function() {
$('#frmUpdateProfile').on("submit", function(event) {
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
var data = {
"FileName" : event.target.FileName.files,
"_token" : "{!! csrf_token() !!}"
};
$.ajax({
url: '{{URL::route("UpdateProfile")}}',
method: "POST",
async: true,
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=utf-8",
success: function (msg) {
SuccessCallback(msg);
},
error: function (jqXHR) {
ErrorCallback(jqXHR);
}
});
});
});
</script>
I tried processData: false,. While debugging in Js, you can check that image is coming in the data. Below is the screenshot.
But when I print the request data in Laravel, it show blank array.
Html form is here
<form method="POST"
action="http://localhost:1234/AS6-Code/public/UpdateProfile"
accept-charset="UTF-8"
enctype="multipart/form-data"
id="frmUpdateProfile">
<input name="_token" type="hidden" value="26KWkWdNqe5iOFE8VRBf1dRnL5xKxwN25jg3tAFW">
<input type="hidden" name="_token" value="26KWkWdNqe5iOFE8VRBf1dRnL5xKxwN25jg3tAFW">
<input multiple="1" name="FileName" type="file">
<input class="btn btn-info" type="submit" value="Update">
</form>
Am I doing something wrong?
Try sending your request with FormData instead:
var data = new FormData($('#frmUpdateProfile')[0]);
Also set contentType to false:
contentType: false
Also Update
event.target.FileName.files
to
event.target.FileName.files[0]
event.target.FileName.files is a FileList object. I believe you need event.target.FileName.files[0] instead.

Second $.ajax call stuck the code

I have an ajax+jquery navigation system with $.ajax, and I`m trying to do a second call to $.ajax to send a contact form infos, but, when I add the second $.ajax all just stop working.
First Call -
function loadPage(url)
{
url=url.replace('#!','');
$('#loading').css('visibility','visible');
$.ajax({
type: "POST",
url: "loader.php",
data: 'page='+url,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#conteudo').html(msg);
$('#loading').css('visibility','hidden');
}
}
});
}
Second Call
$("#enviar").click(function() {
var str = $("form").serializeArray();
$.ajax({
type: "POST",
url: "update.php",
data: str,
success: function(mn) {
if(parseInt(mn)!=0)
{
$("#conteudo").html(mn);
$("#enviado").css('visibility','visible');
}
}
return false;
});
#EDIT
Very good! The first ajax is not stucking anymore, but this second is not working as expected.
This is intended to parse $_POST values to a php script and if ok just turn div visible..
How I`m doing that -
<form name="formcontato" id="form">
<fieldset>
<label>Seu nome</label>
<input type="text" name="nome" class="input-block-level">
<label>Email</label>
<input type="email" name="email" placeholder="seu#email.com" class="input-block-level">
<div class="form-actions">
<input type="button" name="enviar" value="Enviar" id="enviar" class="btn btn-baixar" />
</div>
</fieldset>
</form>
This is the form.
$("#enviar").click(function () {
var str = $("#form").serialize();
$.ajax({
type: "POST",
url: "update.php",
data: str,
success: function (mn) {
alert("Ok!");
if (parseInt(mn) != 0) {
$("#conteudo").html(mn);
$("#enviado").css('visibility', 'visible');
}
}
});
return false;
});
This is the js
if($_POST) {
$nome = trim($_POST['nome']);
echo $nome;
}
This is the update.php
In what you posted, the second function does not properly close the $.ajax() function with a }); so it would generate a parse error and none of the code in this block would be available.
Try this where the $.ajax() call is succesfully closed.
$("#enviar").click(function () {
var str = $("form").serializeArray();
$.ajax({
type: "POST",
url: "update.php",
data: str,
success: function (mn) {
if (parseInt(mn) != 0) {
$("#conteudo").html(mn);
$("#enviado").css('visibility', 'visible');
}
}
});
return false;
});
FYI, proper and consistent indentation is essential to spotting these issues.

Sending AJAX request before submitting the form

Problem: I'm trying to send ajax reguest, and then submit the form.
Aproaches:
1. I solved the problem by putting
success: function() {
document.myform.submit();
}
But i think it's not the most elegant solution. Can you explain me why it works only if i put document.myform.submit(); in success? Is there any other way to solve this problem?
<div class="buttons">
<div class="right">
<form name="myform" onsubmit="javascript: startAjax(); return false;" action="https://example.com/payment.php" method="get">
<input type="hidden" name="merchantId" value="<?php echo $merchantIdKZM; ?>">
<input type="submit" value="<?php echo $button_confirm; ?>" id="button-confirm2" class="button" name="PayKZM" />
</form>
</div>
</div>
<script type="text/javascript">
function startAjax() {
console.log("dafaaaa");
$.ajax({
type: 'get',
url: 'index.php?route=payment/bank_transfer/confirm',
async: 'false',
success: function() {
// location = '<?php echo $continue; ?>';
}
});
} // Calls ajaxComplete() when finished
function ajaxComplete()
{
console.log("dafa");
document.myform.submit();
}
</script>
success's function is called upon the get request receiving a valid response as #harsh pointed out. Thus it will occur after the get request. I believe something similar to the following would do as you request though I haven't tested it:
<script type="text/javascript">
$(function () {
$("#form").on('submit', function () {
var $form = $(this);
$.ajax({
type: 'GET',
url: 'index.php?route=payment/bank_transfer/confirm',
data: $form.serialize(),
async: 'false',
success: function () {
$.ajax({
type: 'GET',
url: 'https://example.com/payment.php',
data: $form.serialize(),
});
}
});
});
});
</script>

Resources