My form:
<form class="form-inline signup" action="php/signupForm.php" role="form" id="signupForm">
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Email address">
</div>
<div class="form-group">
<button type="submit" class="btn btn-theme ladda-button" data-style="expand-left">
<span class="ladda-label" id="notice">Get notified!</span>
</button>
</div>
</form>
the end of my php script
$response = array(
"status" => $status,
"message" => $message
);
echo json_encode($response);
My page is receiving data like:
{"status":0,"message":"This email is already on list!"}
using JS I need to parse that data and then update text within an element.
<span id="notice">Get notified!</span>
here's my script which doesn't work, after senging form data to my php script I get a white screen that shows the json strong
$(document).ready(function() {
$.ajax({
dataType: 'json',
$('#notice').text(data.message);
});
});
You have to handle the response in a callback.
$(document).ready(function() {
$('form').on('submit', function(e) {
e.preventDefault();
$.ajax({
data: $(this).serialize(),
url: $(this).attr('action'), // Or the path of the PHP file
dataType: 'json',
}).done(function(response) {
$('#notice').text(response.message);
});
});
});
See the related docs here
That ajax call is not well formed, missing success callback and url e.g:
$(document).ready(function () {
$.ajax({
url: '/the/url/where/your/data/comes/from/',
dataType: 'json',
success: function (data) {
$('#notice').text(data.message);
}
});
});
Your code as is, is just executing at page load and not on submission of a form. You need to attach an onsubmit event, prevent the default action of doing the form submit and do your ajax call in there. Also your ajax call itself was malformed
$("#yourFormID").submit(function(e){
e.preventDefault();
$.ajax({
url:"/urlToServerScript",
data:{} //any form data the script needs you should be put here,
dataType:"json" //type of response the server will output
}).then(function(data){
$('#notice').text(data.message);
});
});
Related
in my form code there is text input, checkbox input, file input type...etc,
everything working fine except the file input it's only taking one value ( multiple files upload isn't sending through ajax call ) how can i send arrays inside the serialize() function ?
Code :
<form action="#" id="postAdd" enctype="multipart/form-data">
<input accept=".png,.jpg,.jpeg" type="file" class="form-control-file d-none" id="file-upload" name="file[]" multiple required>
<input autocomplete="off" type="text" class="form-control bg-white" name="discName[]">
<button id="postAdbtn" class="btn btn-primary d-block mt-2">Submit</button>
</form> $(document).ready(function() {
$('#postAdbtn').click(function() {
var form = $('#postAdd').serialize();
$.ajax({
url: 'add-product-done.php',
method: "POST",
data: {
form: form
},
success: function(data) {
$('.fetchData').html(data);
}
})
});
});
one more thing, how can i get the files in PHP ?
and thanks
Can you try something like this?
var form = new FormData($("postAdd"));
$.ajax({
url: 'add-product-done.php',
data: form,
contentType: "multipart/form-data",
type: 'POST',
success: function(data){
console.log(data);
},
error: function(err){
console.error(err);
}
});
Can someone help a JS newbie?
Almost everything is working, results are returned, nothing opens new tabs, forms submit to MC database....however I cannot get the result html to post to the correct DIV. All results are being posted to the footer div.
I am guessing my selectors are not specific enough? But I do not have the knowledge on how to structure correctly.
2 forms on page using AJAX submit.
1 pop up form and 1 form in footer..... but all the result html is posting the the div in the footer.
I have adjusted the function register names as suggested (and updated the code below), but form result data is still going to the footer div
//JAVASCRIPT
// FOOTER FORM. waits for form to appear rather than appending straight to the form. Also helps if you have more than one type of form that you want to use this action on.
$(document).on('submit', '#footer-mc-embedded-subscribe-form', function(event) {
try {
//define argument as the current form especially if you have more than one
var $registerFooterFormbutton= jQuery(this);
// stop open of new tab
event.preventDefault();
// submit form via ajax
register($registerFooterFormbutton);
} catch(error){}
});
// POP UP FORM. waits for form to appear rather than appending straight to the form. Also helps if you have more than one type of form that you want to use this action on.
$(document).on('submit', '#pop-mc-embedded-subscribe-form', function(event) {
try {
//define argument as the current form especially if you have more than one
var $registerPopUpFormbutton= jQuery(this);
// stop open of new tab
event.preventDefault();
// submit form via ajax
register($registerPopUpFormbutton);
} catch(error){}
});
// POP UP FORM. post result to div
function register($registerPopUpForm) {
$('#pop-mc-embedded-subscribe-form').val('Sending...');
$.ajax({
type: 'GET',
url: 'https://websitename.us16.list-manage.com/subscribe/post-json?u=.....&c=?',
data: $registerPopUpForm.serialize(),
cache: false,
dataType: 'jsonp',
contentType: 'application/json; charset=utf-8',
error: function (err) { alert('Could not connect to the registration server. Please try again later.') },
success: function (data) {
$('#pop-mc-embedded-subscribe-form').val('pop-subscribe')
if (data.result === 'success') {
// Yeahhhh Success
console.log(data.msg)
$('#pop-mce-EMAIL').css('borderColor', '#ffffff')
$('#pop-subscribe-result').css('color', 'rgb(53, 114, 210)')
$("#pop-subscribe-result").html(data['msg']);
$('#pop-mce-EMAIL').val('')
} else {
// Something went wrong, do something to notify the user.
console.log(data.msg)
$('#pop-mce-EMAIL').css('borderColor', '#ff8282')
$('#pop-subscribe-result').css('color', '#ff8282')
$("#pop-subscribe-result").html(data['msg']);
}
}
})
};
// FOOTER FORM. post result to div
function register($registerFooterForm) {
$('#footer-mc-embedded-subscribe-form').val('Sending...');
$.ajax({
type: 'GET',
url: 'https://websitename.us16.list-manage.com/subscribe/post-json?u=.....&c=?',
data: $registerFooterForm.serialize(),
cache: false,
dataType: 'jsonp',
contentType: 'application/json; charset=utf-8',
error: function (err) { alert('Could not connect to the registration server. Please try again later.') },
success: function (data) {
$('#footer-mc-embedded-subscribe-form').val('footer.subscribe')
if (data.result === 'success') {
// Yeahhhh Success
console.log(data.msg)
$('#footer-mce-EMAIL').css('borderColor', '#ffffff')
$('#footer-subscribe-result').css('color', 'rgb(53, 114, 210)')
$("#footer-subscribe-result").html(data['msg']);
$('#footer-mce-EMAIL').val('')
} else {
// Something went wrong, do something to notify the user.
console.log(data.msg)
$('#footer-mce-EMAIL').css('borderColor', '#ff8282')
$('#footer-subscribe-result').css('color', '#ff8282')
$("#footer-subscribe-result").html(data['msg']);
}
}
})
};
<!--HTML POP UP FORM-->
<form
action="mailchimp url"
method="post"
name="pop-form"
id="pop-mc-embedded-subscribe-form"
class=""
target="_blank"
novalidate
>
<div class="form-group">
<input
type="email"
name="EMAIL"
class="form-control required"
placeholder="Enter your e-mail"
id="pop-mce-EMAIL"
/>
<input
type="submit"
value="SUBSCRIBE HERE"
name="pop-subscribe"
id="pop-mc-embedded-subscribe"
class="button"
/>
</div>
<div id="pop-subscribe-result"></div>
</form>
<!--FOOTER FORM HTML-->
<form
action="mailchimp url"
method="post"
id="footer-mc-embedded-subscribe-form"
name="footer-form"
class=""
target="_blank"
novalidate
>
<div class="mc-field-group">
<label for="mce-EMAIL"
>Email Address <span class="asterisk">*</span>
</label>
<input
type="email"
value=""
name="EMAIL"
class="form-control required email"
id="footer-mce-EMAIL"
placeholder="Email Address *"
/>
</div>
<div class="mc-field-group">
<label for="mce-FNAME">First Name </label>
<input
type="text"
value=""
name="FNAME"
class="form-control"
id="mce-FNAME"
placeholder="First Name"
/>
</div>
<div class="mc-field-group">
<label for="mce-LNAME">Last Name </label>
<input
type="text"
value=""
name="LNAME"
class="form-control"
id="mce-LNAME"
placeholder="Last Name"
/>
</div>
<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;" aria-hidden="true">
<input
type="text"
name="b_dc51fb25cd808abedc98e3ff2_ea4d259202"
tabindex="-1"
value=""
/>
</div>
<div class="footer-btn">
<input
type="submit"
value="Subscribe"
name="footer-subscribe"
id="mc-embedded-subscribe"
class="button"
/>
</div>
<div id="footer-subscribe-result"></div>
</form>
You have two functions with the same name "register" so when you press the submit button in either forms it runs in the register function in the footer since it has the same name as the one dedicated to the popup form
Use this code and your form will work as expected:
//JAVASCRIPT
// FOOTER FORM. waits for form to appear rather than appending straight to the form. Also helps if you have more than one type of form that you want to use this action on.
$(document).on('submit', '#footer-mc-embedded-subscribe-form', function(event) {
try {
//define argument as the current form especially if you have more than one
var $registerFooterFormbutton= jQuery(this);
// stop open of new tab
event.preventDefault();
// submit form via ajax
register1($registerFooterFormbutton);
} catch(error){}
});
// POP UP FORM. waits for form to appear rather than appending straight to the form. Also helps if you have more than one type of form that you want to use this action on.
$(document).on('submit', '#pop-mc-embedded-subscribe-form', function(event) {
try {
//define argument as the current form especially if you have more than one
var $registerPopUpFormbutton= jQuery(this);
// stop open of new tab
event.preventDefault();
// submit form via ajax
register($registerPopUpFormbutton);
} catch(error){}
});
// POP UP FORM. post result to div
function register($registerPopUpForm) {
$('#pop-mc-embedded-subscribe-form').val('Sending...');
$.ajax({
type: 'GET',
url: 'https://websitename.us16.list-manage.com/subscribe/post-json?u=.....&c=?',
data: $registerPopUpForm.serialize(),
cache: false,
dataType: 'jsonp',
contentType: 'application/json; charset=utf-8',
error: function (err) { alert('Could not connect to the registration server. Please try again later.') },
success: function (data) {
$('#pop-mc-embedded-subscribe-form').val('pop-subscribe')
if (data.result === 'success') {
// Yeahhhh Success
console.log(data.msg)
$('#pop-mce-EMAIL').css('borderColor', '#ffffff')
$('#pop-subscribe-result').css('color', 'rgb(53, 114, 210)')
$("#pop-subscribe-result").html(data['msg']);
$('#pop-mce-EMAIL').val('')
} else {
// Something went wrong, do something to notify the user.
console.log(data.msg)
$('#pop-mce-EMAIL').css('borderColor', '#ff8282')
$('#pop-subscribe-result').css('color', '#ff8282')
$("#pop-subscribe-result").html(data['msg']);
}
}
})
};
// FOOTER FORM. post result to div
function register1($registerFooterForm) {
$('#footer-mc-embedded-subscribe-form').val('Sending...');
$.ajax({
type: 'GET',
url: 'https://websitename.us16.list-manage.com/subscribe/post-json?u=.....&c=?',
data: $registerFooterForm.serialize(),
cache: false,
dataType: 'jsonp',
contentType: 'application/json; charset=utf-8',
error: function (err) { alert('Could not connect to the registration server. Please try again later.') },
success: function (data) {
$('#footer-mc-embedded-subscribe-form').val('footer.subscribe')
if (data.result === 'success') {
// Yeahhhh Success
console.log(data.msg)
$('#footer-mce-EMAIL').css('borderColor', '#ffffff')
$('#footer-subscribe-result').css('color', 'rgb(53, 114, 210)')
$("#footer-subscribe-result").html(data['msg']);
$('#footer-mce-EMAIL').val('')
} else {
// Something went wrong, do something to notify the user.
console.log(data.msg)
$('#footer-mce-EMAIL').css('borderColor', '#ff8282')
$('#footer-subscribe-result').css('color', '#ff8282')
$("#footer-subscribe-result").html(data['msg']);
}
}
})
};
You are defining the register() function two times with the same name. The second one overwrites the first and everytime you call the function with that name you call the second function. An easy solution is to change the name of the functions (i.e registerPopUpForm() , registerFooterForm() ) and use them accordingly.
I want to pass data from controller to jquery using json don't know where is the problem but fro the jquery code I think its working fine as I tested the success code but can't get back the result from controller
home.blade
<form role="form" name="form_address" id="form_address" action="" method="POST" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="text" id="postal_code" onFocus="geolocate()">
<input type="text" id="totaldistance" onFocus="geolocate()">
</form>
<button id="save_address">Save</button>
<script>
$("#save_address").click(function (e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
e.preventDefault();
var form = document.forms.namedItem("form_address");
var formData = new FormData(form);
$.ajax({
type: "get",
url: 'Get_distance',
contentType: false,
data: formData,
processData: false,
success: function(data) {
$('#totaldistance').val(data.distance);
}
});
});
web.php
Route::post('Get_distance','HomeController#getdistance');
controller
public function getdistance(Request $request)
{
$distance =$request->postal_code;
return Response::json(array(
'distance' => $distance,
));
}
Change your ajax type to POST, because your route type is POST, not GET.
Your defined route in web.php is a POST request, but your Ajax method is set to GET request. Change web.php to a GET request for it to work. Make sure to provide an error function to catch any errors from server side.
Or vice versa, change Ajax request to POST since you already added the csrf setup.
im trying to submit an ajax post in laravel but im having some problem regarding the form's csrf token. In my form, if the conditions i set in my ajax post url has been met the first time the form has been submitted. However if i submit the form and purposely failed the conditions i set in my ajax post url in the first try, If i submit the form again i get a token mismatch exception in my ajax error log. Do i need to refresh the csrf_token every ajax post?
Below is my code
JS
$(document).on('submit','.registration-form',function(e){
e.preventDefault();
var form = $(this);
var form_url = $(this).attr("action");
var form_values = $(this).serialize();
$.ajax({
url:form_url,
type:'POST',
data:form_values,
dataType: 'json',
async:false,
success: function(result){
console.log(result);
if(result['status']==true){
location.href = result['redirect'];
}
else{
form.find(".form-details").show().html(result['message']);
}
},
error: function(ts) {
console.log(ts.responseText)
}
});
});
HTML
<form action="{{ url('login') }}" method="POST" class="registration-form">
{{ csrf_field() }}
<input type="text" name="username" class="input" placeholder="Email">
<input type="password" name="password" class="input" placeholder="Password">
<button class="button is-redbox is-flat is-fullwidth">Login</button>
</form>
Are u sure that each time that is send in ajax?
data: {
"_token": "{{ csrf_token() }}",
}
$("#cform")[0].reset();
or in plain javascript:
document.getElementById("cform").reset();
public function regenerateToken(){
session()->regenerate();
return response()->json([
'msg'=>'success',
'token'=>csrf_token()
]);
}
$('#form').submit(funtion(event) {
event.preventDefault(event);
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: form.attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
if (response.msg === 'success') {
$('#token').val(response.token);
console.log($('#token').val());
}
}
$('input[type="text"],input[type="email"] ,textarea, select').val(''); $(this).trigger('reset');
});
I have a html file where users can input a value.
I wrote a script in PHP that checks if this value is present in the databse. If it's present it returns
{"active":true}
Now my goals is that when the user inputs their value and submit they will be redirected to a certain page if this active is true. If it's false they should see an error message.
So here's what I've tried with my AJAX call:
$("document").ready(function(){
$(".checkform").submit(function(e){
e.preventDefault();
$.ajax({
type: "GET",
dataType: "json",
url: "api/check.php",
data: data,
success: function(data) {
if(data.active=="true"){
alert("success");
location.href="where_you_want";
}else{
alert("failure");
}
}
});
return false;
});
});
Here is my HTML:
<form action="api/check.php" id="requestacallform" method="GET" name="requestacallform" class="formcheck">
<div class="form-group">
<div class="input-group">
<input id="#" type="text" class="form-control" placeholder="Jouw subdomein" name="name"/>
</div>
</div>
<input type="submit" value="Aanmelden" class="btn btn-blue" />
</form>
For some reason I get an error:
Uncaught ReferenceError: data is not defined
I am new to AJAX and I am not sure if what I am trying is correct.
Any help would be greatly appreciated!
Thanks in advance.
Can you try:
$(".aanmeldenmodal").submit(function(e){
e.preventDefault();
I am updating my answer in whole
<html>
<body>
<form action="api/check.php" id="requestacallform" method="GET" name="requestacallform" class="formcheck">
<div class="form-group">
<div class="input-group">
<input id="txt1" type="text" class="form-control" placeholder="Jouw subdomein" name="name"/>
</div>
</div>
<input type="submit" value="Aanmelden" class="btn btn-blue checkform" />
</form>
</body>
</html>
jQuery part is like
$("document").ready(function () {
$("body").on("click", ".checkform", function (e) {
e.preventDefault();
var request = $("#txt1").value;
$.ajax({
type: 'GET',
url: 'ajax.php',
data: {request: 'request'},
dataType: 'json',
success: function (data) {
if(data.active==true){
alert("success");
}else{
alert("failure");
}
}
});
});
});
ajax.php should be like this
if(isset($_GET['request'])){
//check for the text
echo json_encode($arr);
}
In api/check.php
You can pass data in json format
$json = json_encode($data);
retrun $json;
You can also not share any data so You can remove data from jQuery.
data:data
Your Jquery look like this:
$("document").ready(function(){
$(".checkform").submit(function(e){
e.preventDefault();
$.ajax({
type: "GET",
dataType: "json",
url: "api/check.php",
success: function(data) {
if(data.active=="true"){
alert("success");
location.href="where_you_want";
}else{
alert("failure");
}
}
});
return false;
});
});