Form input field not recognized in jquery - javascript

I have this search form to post using jQuery:
<form id="search-article-form" method="post">
<input type="hidden" name="token" value="LSN71T8CeWr">
<input id="searcharticle" type="text" placeholder="search..."
name="searcharticle">
</form>
jQuery snippet:
$(function () {
$('#searcharticle').keyup(function() {
var form = $('#search-article-form');
console.log('form:', form.serialize());
$.ajax({
type: "POST",
url: "/search/article/",
data: form.serialize(),
success: searchSuccess,
dataType: 'html'
});
});
});
function searchSuccess(data, textStatus, jqXHR) {
console.log('data:', data);
$('#search-results').html(data);
}
The problem is that the form does not seem to be serialized properly, so on keyup I see only this in the console:
form: token=LSN71T8CeWr
Also on the server side, the received post parameters is empty.
So wondering what is wrong here and how to fix it?

Works fine in the attached snippet
$(function () {
$('#searcharticle').keyup(function() {
var form = $('#search-article-form');
console.log('form:', form.serialize());
});
});
function searchSuccess(data, textStatus, jqXHR) {
console.log('data:', data);
$('#search-results').html(data);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="search-article-form" method="post">
<input type="hidden" name="token" value="LSN71T8CeWr">
<input id="searcharticle" type="text" placeholder="search..."
name="searcharticle">
</form>

Related

Ajax call and PHP form submission not working together?

I am facing an issue while sending the data through the PHP script, in Index.php there is a form with some field values and a JavaScript script included in the Index.php which posts an image after I submit the form in Index.php with help of ajax, but Image is not posting/sending through ajax, only form field submission works.
If I call only Ajax during the time of form submission that is working or if I submit the form value all alone working, but if I call together the image is not working.
Index.php
<form enctype="multipart/form-data" method="post" action="saveRecord.php">
<?php include ('imagecropinterface/index.html'); ?>
<div>
<input autocomplete="off" type="text" maxlength="90" placeholder="HeadLine" id="headline" name="headline" style="width:386px;">
</div>
<div class="mt-2">
<input autocomplete="off" type="text" maxlength="90" name="subtitle" placeholder="Sub Title" style="width:386px;">
</div>
<div>
<input id='jour' type='text' value="" class=''>
</div>
<div>
<textarea name="fullText" placeholder="Synopsis" style="width:386px;"></textarea>
</div>
<input class="btn btn-secondary" name="save" id="btnid" value="Save" type="submit">
</form>
index.html
const downloadAllBtn = document.getElementById("btnid");
downloadAllBtn.addEventListener("click", downloadAll);
function downloadAll() {
$.ajax({
type: "POST",
url: "/ap-beta2/saveRecord.php",
data: {
data: imagesBase64,
},
cache: false,
error: function (err, data) {
console.log("There was an error. Try again please!" + data, err);
},
success: function (data) {
console.log(data);
},
});
}
saveRecord.php
if (isset($_POST['save']) && isset($_POST['data'])) {
echo ($_POST[data]);
echo ($_POST['headline']);
echo ($_POST['subtitle']);
}
How can I submit the form so that form value and ajax call POST together to the PHP page?
As suggested by #ADyson I have updated Ajax script, unfortunately, no progress!!
In the form, I put the id saveform
<form enctype="multipart/form-data" id = "saveform" method="post" action="saveRecord.php">
function downloadAll() {
$("#saveform").click(function (e) {
$.ajax({
type: "POST",
url: "https://myimpact.in/ap-beta2/saveRecord.php",
data: {
data: imagesBase64,
},
cache: false,
error: function (err, data) {
console.log("There was an error. Try again please!" + data, err);
},
success: function (data) {
console.log(data);
},
});
e.preventDefault();
});
}

Stop page redirect after submitting the form with jQuery

I have a simple code, and I try to make a post without redirecting the page. So far my code looks like this:
$(function() {
$('#btn').on('click', '.document', function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/save',
data: {
html: '<p>Sucess</p>',
delay: 1
},
dataType: 'html',
success: function(data) {
console.log('success');
$('.document').append(data);
},
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form action="/save" method="post" autocomplete="off" id="theForm">
<button id="btn" type="submit" name="send">
Send
</button>
</form>
<span class="document"></span>
Can anybody try to help me with this? I don't know why my code doesn't work, I want to be able to POST without reloading and redirecting the page.
You're attaching a delegated event handler to a span with no content, and the primary selector isn't a parent of that span.
The correct approach would be to attach a submit event handler to the form element instead.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form action="/save" method="post" autocomplete="off" id="theForm">
<button id="btn" type="submit" name="send">Send</button>
</form>
<span class="document"></span>
jQuery($ => {
$('#theForm').on('submit', e => {
e.preventDefault();
$.ajax({
type: 'post',
url: '/save',
data: {
html: '<p>Sucess</p>',
delay: 1
},
dataType: 'html',
success: function(data) {
console.log('success');
$('.document').append(data);
}
});
});
});

Mailchimp via jQuery Ajax. Submits correctly but JSON response is returned as a separate page

I have the following form:
<form class="footer-newsletter-form" id="footer-newsletter" method="post" action="http://xxxxxx.us1.list-manage.com/subscribe/post-json?u=xxxxxxxxxxxxxxxxxxxxxxxxx&id=xxxxxxxxxx&c=?">
<input id="email" name="EMAIL" type="email" class="input-text required-entry validate-email footer__newsletter-field" value="{% if customer %}{{ customer.email }}{% endif %}" placeholder="{{ 'general.newsletter_form.email_placeholder' | t }}" aria-label="{{ 'general.newsletter_form.newsletter_email' | t }}">
<button type="submit" title="Subscribe" class="button button1 hover-white footer__newsletter-button">SUBSCRIBE</button>
<div id="subscribe-result"></div>
</form>
And the following jquery bit:
<script type="text/javascript">
$(document).ready(function () {
function register($form) {
jQuery.ajax({
type: "GET",
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'jsonp',
contentType: "application/json; charset=utf-8",
error : function(err) { console.log('error') },
success : function(data) {
if (data.result != "success") {
console.log('success');
} else {
console.log('not success');
//formSuccess();
}
}
});
}
jQuery(document).on('submit', '.footer-newsletter-form', function(event) {
try {
var $form = jQuery(this);
event.preventDefault();
register($form);
} catch(error){}
});
});
</script>
Which submits correctly. However, when I press the submit button what I expect to happen is that the page does not refresh and when I check the browser console I'll either see "success" or "not success". Instead what happens is I'm sent to a page that displays the following JSON message: ?({"result":"success","msg":"Almost finished... We need to confirm your email address. To complete the subscription process, please click the link in the email we just sent you."}).
So how do I take that success message (or error if there's an error) and have the page not only remain as is, but also capture the success message so I can display a "Success" alert? The success alert I know how to do. I just need help having the browser remain where it is and tell the difference between success and error.
P.S. I'm not sure if this is relevant but the platform is Shopify. I don't think Shopify does anything to prevent the submission from going through as it should or the response coming back so I don't think it is relevant.
The whole issue was the $(document).ready(function () {}); part. For some reason unbeknownst to me that causes the event.preventDefault(); method from running and the form submits regularly. If you remove the $(document).ready(function () {}); part it'll work as intended.
My final code for anyone looking in the future:
Form:
<form class="footer-newsletter-form" method="POST" id="footer-newsletter" action="https://xxxxxxxxxxxxx.us1.list-manage.com/subscribe/post-json?c=?">
<input type="hidden" name="u" value="xxxxxxxxxxxxxxxxxxxxxxxxxxx">
<input type="hidden" name="id" value="xxxxxxxxxx">
<input id="email" name="EMAIL" type="email" class="input-text required-entry validate-email footer__newsletter-field">
<button type="submit" title="Subscribe" class="button button1 hover-white footer__newsletter-button">SUBSCRIBE</button>
<div id="subscribe-result"></div>
</form>
And the JS:
<script>
function register($form) {
$.ajax({
type: "GET",
url: $form.attr('action'),
data: $form.serialize(),
cache: false,
dataType: 'json',
contentType: "application/json; charset=utf-8",
error: function (err) {
console.log('error')
},
success: function (data) {
if (data.result != "success") {
console.log('Error: ' + data.msg);
} else {
console.log("Success");
$($form).find("div#subscribe-result").html("<p class='success-message'>Almost finished... We need to confirm your email address. To complete the subscription process, please click the link in the email we just sent you!</p>");
setTimeout(function() { $($form).find("div#subscribe-result").hide(); }, 7000);
}
}
});
}
$(document).on('submit', '#footer-newsletter', function (event) {
try {
var $form = jQuery(this);
event.preventDefault();
register($form);
} catch (error) {}
});
</script>

AJAX function is not firing

Hello everyone I want to parse array to Codeigniter controller but my code is not working can you please tell me where is a mistake in this code. I am a new in jQuery I know it is a very basic mistake.
jQuery Code:
$("#add_state").click(function(){
var addstate = {
State: $.trim($('#statename').val()
}
$.ajax({
type: "POST",
url: "<?php echo base_url()?>/index.php/geo/add_state",
data: addstate,
success: function(response){
alert(response);
}
});
event.preventDefault();
});
HTML Code:
<form role="form">
<div class="form-group">
<label for="exampleInputEmail1">State Name</label>
<input type="text" name="State" class="form-control" id="statename" placeholder="Enter State Name">
</div>
<button type="submit" class="btn btn-info" id="add_state">Submit</button>
</form>
trim is not closed properly
it suppose to be like this
$("#add_state").click(function(){
var addstate = {
State: $.trim($('#statename').val())
}
$.ajax({
type: "POST",
url: "<?php echo base_url()?>/index.php/geo/add_state",
data: addstate,
success: function(response){
alert(response);
}
});
event.preventDefault();
});
Missing ) in State: $.trim($('#statename').val(). Change it to State: $.trim($('#statename').val()).
Use $(document).on('click', '#add_state', function() { instead$("#add_state").click(function(){. Because first solution will work, if you add script before dom element was created.
Check url, maybe it's incorrect.

No AJAX request

i can't see any AJAX request to the webservice.php ( i use firebug), but i don't know why!
HTML Code:
<form id="form_login" name="form_login" method="POST">
E-Mail: <input type="text" size="30" name="email" id="email"></br>
Passwort: <input type="text" size="30" name="password" id="password"></br>
DeviceID: <input type="text" size="30" name="deviceid" id="deviceid"></br>
<input type="submit" value="Login" name="submit_login" />
JS Code:
$(function () {
$('form_login').on('submit_login', function (e) {
$.ajax({
type: "GET",
url: "webservice.php?method=CheckUserLogin",
data: $('form_login').serialize(),
success: function (response) {
alert(response);
},
failure: function (response) {
alert(response);
}
});
e.preventDefault();
});
});
It doesn't work, but i really don't know why...
$('form_login').on('submit_login', function (e) {
should be:
$('#form_login').on('someevent','[name="submit_login"]', function (e) {
and
data: $('form_login').serialize(),
should be:
data: $('#form_login').serialize(),
# is used to select the element with id, and [] is used to select element with attribute.
$('form_login').on('submit_login', function (e) {
should be:
$('form_login').on('submit', function (e) {
because submit_login is not a valid parameter!

Categories

Resources