I have this piece of code.
It's a input for a newsletter.
<form id="newsletter-form" name="newsletter-form" method="post" action="/newsletter">
<div class="form-group">
<label for="exampleInputEmail1"><span>Cadastre-se em nossa newsletter</span></label>
<input type="email" class="form-control" id="newsletter-email" name="newsletter-email" placeholder="e-mail" value="">
</div>
<button class="btn btn-secondary btn-block" type="button"><i class="fas fa-paper-plane fa-fw mr-1"></i>Cadastrar</button>
</form>
Quite simple!
And I have this JS:
$(function()
{
var form = $('#newsletter-form');
// ----------
$(form).submit(function(form_response)
{
form_response.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response)
{
$('#newsletter-email').removeClass('is-invalid');
$('#newsletter-email').addClass('is-valid');
$('#newsletter-email').val(response);
})
.fail(function(data)
{
$('#newsletter-email').removeClass('is-valid');
$('#newsletter-email').addClass('is-invalid');
if (data.responseText !== '')
{
$('#newsletter-email').val(data.responseText);
}
else
{
$('#newsletter-email').val('Ocorreu um erro!');
}
});
});
});
My PHP check if email is valid, if already is inserted, etc, etc.
The PHP returns codes and echos correctly(I use it on other parts of my website)
The thing is:this form is not even triggering the JS to run the PHP.
It should run the PHP and add a is-valid or is-invalid class on the inpute and show the feedback as value or placeholder.
Any ideas why it's not working?
Just to add it as answer your button type was button not submit so eaither use input type submit or change button type to submit :D
This is your original code. var form = $('#newsletter-form');
Since you have put the form tag into a variable, you don't need to use $. Change $(form) into form. The code will look like this.
form.submit( /* some code */ );
or if you don't want to store it into variable, you can directly call the function from jquery.
$('#newsletter-form').submit( /* some code */ );
Related
I am creating a form that need to be submit using jQuery. Below is my code -
<script src="js/app.js" type="text/javascript"></script>
<form method="post" class="needs-validation" id="new-item" action="admin-add-inventory2.php">
<div class="mb-3">
<label>Item Name</label>
<input type="text" class="form-control" id="itemname" name="itemname" placeholder="Item name" required>
<span id='inmessage'>
</div>
<div class="mb-3">
<label>Description
<span class="text-muted">(Optional)</span>
</label>
<input type="text" class="form-control" id="description" name="description" placeholder="description...">
<span id='dmessage'>
</div>
<hr class="mb-4">
<input type="submit" value="Add To Inventory" name="submit" id="submit" class="btn btn-primary btn-lg btn-block error-w3l-btn">
</form>
<div id="form-messages"></div>
Code for app.js --
$(function() {
// Get the form.
var form = $('#new-item');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// 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.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#itemname').val('');
$('#description').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured, please try again.');
}
});
});
});
But when pressing the submit button, app.js is not getting executed. Its directly going to action="admin-add-inventory2.php" of form tag.
Kindly point me the logic i m missing.
Its not taking the question in stackoverflow due to more code and less text, so i am adding extra text to submit. Pls ignore the below text.
But when pressing the submit button, app.js is not getting executed. Its directly going to action="admin-add-inventory2.php" of form tag.
Kindly point me the logic i m missing.
But when pressing the submit button, app.js is not getting executed. Its directly going to action="admin-add-inventory2.php" of form tag.
Kindly point me the logic i m missing.
Please replace button type from submit to button.
Eg: <input type="button" value="Add To Inventory" name="submit" id="submit" class="btn btn-primary btn-lg btn-block error-w3l-btn">
Also replace $(form).submit(function(e) { with $("#submit").click(function(e) { if you want to call the AJAX code in your JS file on click of the button.
How to update multiple data using AJAX ?
Example :
TableA
id : 1, 2
name : Jack, John
It's only working with id 1, when I am trying to edit name for id 2 it's not working.
I have try with this code but failed.
HTML/PHP :
...
while($row=mysqli_fetch_array($query)){
echo'
<form class="btn-group">
<input type="text" class="form-control" name="id_user" id="id_user" data-user="'.$row['id'].'" value="'.$row['id'].'">
<input type="text" class="form-control" name="id_status" id="id_status" data-status="'.$row['id'].'" value="'.$row['id'].'">
<button type="submit" id="likestatus" class="btn btn-primary btn-outline btn-xs"><i class="fas fa-thumbs-up"></i></button>
</form>
';
}
AJAX :
$(document).ready(function(){
$("#likestatus").click(function(){
var id_user=$("#id_user").data("user");
var id_status=$("#id_status").data("status");
$.ajax({
url:'status/like-status.php',
method:'POST',
data:{
id_user:id_user,
id_status:id_status
},
success:function(response){
alert(response);
}
});
});
});
The problem with your code is that ids should be unique, but in the loop you create elements with same id.
Use this in the event handler to find the siblings of the button that has been clicked - closest returns the parent of type form.
$(document).ready(function(){
$(".btn-primary").click(function(){
var $form = $(this).closest('form');
var id_user=$form.find('[name="id_user"]').data("user");
var id_status=$form.find('[name="id_status"]').data("status");
$.ajax({
url:'status/like-status.php',
method:'POST',
data:{
id_user:id_user,
id_status:id_status
},
success:function(response){
alert(response);
}
});
});
});
You might want to use your own class instead of .btn-primary because this affects all buttons on the page.
Judging from the incomplete PHP, it appears as if you're not assigning to $ruser within your loop. This would mean you're always posting the same id to like-status.php.
PS: Would've posted as comment, but I can't.
Make your ID unique so make them dynamic
<?php
$counter = 0;
while($row=mysqli_fetch_array($query)){
$counter++;
echo'
<form class="btn-group">
<input type="text" class="form-control" id="userid_$counter" data-user="'.$ruser['id'].'" value="'.$ruser['id'].'">
<input type="text" class="form-control" name="id_status" id="status_$counter" data-status="'.$rtimeline['id'].'" value="'.$rtimeline['id'].'">
<button type="submit" id="likestatus_$counter" class="btn btn-primary btn-outline btn-xs"><i class="fas fa-thumbs-up"></i></button>
</form>
';
}
?>
Then
<script type="text/javascript">
$(document).ready(function(){
$('[id^="likestatus_"]').on('click',function(){
var index = $(this).attr('id').split("_")[1];
var id_user=$("#user_"+index).data("user");
var id_status=$("#status_"+index).data("status");
$.ajax({
url:'status/like-status.php',
method:'POST',
data:{
id_user:id_user,
id_status:id_status
},
success:function(response){
alert(response);
}
});
});
});
You're using the id's multiple times. Thus your query for var id_user=$("#id_user").data("user"); always finds the first input field on the page. You should avoid using the same id multiple times on one page (see this Question).
You may subscribe to the jQuery submit event of the form and then search for the input fields within that form, to properly extract the id_user and status_user values. For that you have to add an appropriate event listener to the <form> element. To find the form I would recommend adding a css-class like like-status-form.
$(document).ready(function(){
// We're attaching a submit-event listener to every element with the css class "like-status-form"
$(".like-status-form").submit(function(event){
// Form get's submitted
// Prevent that the Browser reloads the page
event.preventDefault();
// Extract the user id and status from the form element (=== $(this))
var id_user = $(this).find('[name="id_user"]').data('user');
var id_status = $(this).find('[name="id_status"]').data('status');
// TODO Perform AJAX Call here
});
});
To detect the form elements one can use the jQuery Attribute Equals Selector.
Find a working example at https://jsfiddle.net/07yzf8k1/
I am trying to post data through my website via ajax, however for some reason it seems to echo the success message but does not get the mobile field data. it's just blank. When i inspect with firebug, it gives the response, but the POST tab is empty.
My controller contains the following :
function submit()
{
//set validation rule
// get post data
$emailid = $this->input->post('mobile');
// write your database insert code here
echo "<div class='alert'>Thanks for Subscribing! Please stay tuned to get awesome tips...</div> here is $emailid";
}
And my view contains :
<label>Mobile</label>
<input type="number" name="mobile" id="mobile" class=" form-control" />
<button type ="submit" id="submit" name="submit" class="btn btn-info btn-block" /> NEXT </button>
The JS
<script type="text/javascript">
$("#submit").click(function(e) {
e.preventDefault();
var mobile = $("mobile").val();
$.ajax({
url: "https://cheddarplatform.com/complete/submit",
method: "POST",
data: {mobile: mobile},
success: function(data) {
$("#message").html(data);
},
error: function() {
alert("Please enter valid email id!");
}
});
});
</script>
$("mobile") is not a proper selector, as you do not have a HTML element of that type anywhere. Probably you want to use $("#mobile") and have a look at your browser's network tab to find this error easier the next time
I have my first PHP page having search form:
<form action="#" class="form-inline" id="form_srch">
<input type="text" id="toSearch" name="toSearch" placeholder="Enter Application Number" class="form-control" style="width:250px" required >
<button type="button" class="btn btn-primary" onclick="search()">
<span class="glyphicon glyphicon-search" aria-hidden="true"></span>
</button>
<i><b><p style="display:none;color:red" id="result">** Empty Value</p></b></i>
</form>
<div id="ajax"></div>
and a javascript function
<script>
function liveCheck() {
$("#result").show();
}
function search() {
var inp = $("#toSearch").val();
if(jQuery.trim(inp).length > 0)
{
jQuery.ajax({
url: "load_search_prereg.php",
data:{ to : inp },
type: "POST",
success:function(data){
$("#ajax").load('load_search_prereg.php');
//alert(data);
},
error:function (){}
});
}
else{
liveCheck();
}
}
</script>
And i have my second PHP page named load_search_prereg.php to process the POSTed input and the code is
<?php
require '../backend/_classes.php';
$x = new DB();
$id = $_POST['to'];
$sql=$x->select(1,'*','tblregistration','app_number',"'$id'");
$fetch = $sql->fetchObject();
var_dump($fetch);
The problem is when i clicked the search button in my first PHP page, It displays no array of posted data while im using the $("#ajax").load('load_search_prereg.php'); method in my javascript. But when i use alert(data);, it returns the expected result. Does the problem occur in $("#ajax").load('load_search_prereg.php'); method ? Help pls.
Not:
$("#ajax").load('load_search_prereg.php');
But:
$("#ajax").html(data);
I've assumed you just want to write this data into div
edit:
instead of var_dump($fetch); you must return your data a JSON object, eg:
$fetch = $sql->fetchObject();
echo json_encode($fetch);
Then you can do in js what you want
It should be method:"POST" instead of type: "POST".
By default method is set to GET.
So I have this problem.
I have the following form on my webpage:
<form>
<textarea rows="3" id="pasteText"> </textarea>
<button class="btn btn-success btn-block" type="submit" id="paster" onclick="captureText();">Paste!</button>
And I have a JavaScript method to capture the text in the textarea here:
function captureText() {
var value = $("#pasteText").val();
//var sent = "../../lib/_add.php?data="+value;
$.post('../../lib/_add.php', {data: value});
}
I'm trying to send the value inside the textarea to the data in PHP (the add.php adds the data variable to my database). What's the best way to go about it? Everything I've tried so far hasn't worked.
Thanks!
You don't need jQuery $.post to submit the form. A simple HTML form would do.
<form action="../../lib/_add.php" method="post">
<textarea rows="3" name="data" id="pasteText"></textarea>
<input class="btn btn-success btn-block" id="paster" type="submit" value="Paste!" />
</form>
You are using input type "Submit". So you have to return false from your function if you want to continue uisng ajax to submit form. In this case your javascript would look like:
function captureText() {
var value = $("#pasteText").val();
//var sent = "../../lib/_add.php?data="+value;
$.post('../../lib/_add.php', {data: value});
return fasle;
}
Otherwise a simple form works fine.
Enjoy!.
function captureText() {
var value = $("#pasteText").val();
//var sent = "../../lib/_add.php?data="+value;
$.post('../../lib/_add.php', {data: value})
.done(function(data) {
alert("Data Loaded: " + data);
// add some result confirmation code from php
});
alert("data received");
}
check jquery path and php file path