I want it to only "reload" into the #searchuserc. I have searched so much information but I can't solve the problem.
$(document).ready(function() {
$("#onlineusers").load("online.php");
$("#searchuserc").show();
setInterval(function() {
$("#onlineusers").load("online.php");
}, 5000);
$(".search").click(function() {
$("#onlineusers").hide();
e.preventDefault(); // Prevent Default Submission
$.ajax({
url: 'searchuser.php',
type: 'POST',
data: $(this).serialize(), // it will serialize the form data
dataType: 'html'
})
.done(function(data) {
$('#searchuserc').fadeOut('slow', function() {
$('#searchuserc').fadeIn('slow').html(data);
});
})
.fail(function() {
alert('Ajax Submit Failed ...');
});
});
});
this is my HTML file
<form method="POST">
<input type="text" id="searchuser" name="searchuser" placeholder="Sök efter en användare..." />
<input type="submit" class="search" name="searchbtn" value="Sök" />
</form>
<div id="searchuserc">
</div>
Instead of
$(".search").click(function() {
...
use
$(".search").closest("form").submit(function(e) {
...
Code inside the handler can stay the same.
Related
I have a form on my front-end and when the submit button is clicked I want to send the details to my get-emp.php file without page reload.
The code looks like this:
index.html
<form class="form-emp-details hide" action="">
<div class="form-group">
<label for="">First name:</label>
<input type="text" class="form-control input-emp-firstname" name="input_emp_firstname">
</div>
<div class="form-group">
<label for="">Last name:</label>
<input type="text" class="form-control input-emp-lastname" name="input_emp_lastname">
</div>
<div class="form-group">
<label></label>
<button type="submit" class="btn btn-default btn-submit-1" name="submit_emp_details">Save</button>
</div>
</form>
custom.js
$(".form-emp-details").("submit", function(e) {
var input_first_name = $(".input-emp-firstname").val();
$.ajax({
type: "POST",
url: "get-emp.php",
data: {
input_emp_firstname:input_first_name,
},
success: function(data) {
console.log(data)
},
error: function(xhr,status,error) {
console.log(error);
}
});
});
get-emp.php
if(isset($_POST['submit_emp_details'])) {
$firstname = $_POST['input_emp_firstname'];
echo $firstname;
}
I want to display the submitted form data on get-emp.php file but it seems that I am not able to detect the submitted button and echo the form data on.
My goal is to capture all form data with a single request variable or identifier $_POST['submit_emp_details']
Any help is greatly appreciated. Thanks
$("#MyformId").submit(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(),
success: function(data)
{
// success..
}
});
});
You passing the POST data of firstname and lastname by:
input_emp_firstname
input_emp_lastname
so, you need to change the $_POST['submit_emp_details'] to $_POST['input_emp_firstname'] on file get-emp.php to
<?php
if(isset($_POST['input_emp_firstname'])) {
$firstname = $_POST['input_emp_firstname'];
echo $firstname;
}
Edit 2:
$.ajax({
type: "POST",
url: "get-emp.php",
cache: false,
data: {
submit_emp_details: {
input_emp_firstname:input_first_name,
input_emp_lastname:input_last_name
}
},
success: function(data) {
console.log(data)
},
error: function(xhr,status,error) {
console.log(error);
}
});
In ASP.NET MVC Project, i want button to not make submit if the result come from AJAX code is false.
But the it always make submit.
That is the code:
#using (Html.BeginForm("Add", "Category", FormMethod.Post))
{
<input name="CategoryID" id="myCategoryId" type="text" value="0" />
<input name="CategoryName" id="myCategoryNameId" type="text" value="" />
<input class="btn btn-primary" id="myid" type="submit" value="Add" />
}
and that is Javascript code:
$('#myid').on('click', function(event) {
var data = {};
data.CategoryName = $("#myCategoryNameId").val();
data.CategoryID = $("#myCategoryId").val();
$.ajax({
type: 'POST',
data: JSON.stringify(data),
url: '/Category/ValidateCategoryName',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (!result) {
event.preventDefault();
}
}
});
});
I'd replace the submit button input element with a button element so that clicking the button will trigger the onclick event without submitting the form. Then when you get the ajax response you can conditionally use jQuery to submit the form. This might require some tinkering to get the form from the onclick but it'll prevent you from submitting the form too early like I suspect your problem is.
#using (Html.BeginForm("Add", "Category", FormMethod.Post))
{
<input name="CategoryID" id="myCategoryId" type="text" value="0" />
<input name="CategoryName" id="myCategoryNameId" type="text" value="" />
<button class="btn btn-primary" id="myid">Add</button>
}
and
$('#myid').on('click', function(event) {
var data = {
CategoryName: $("#myCategoryNameId").val(),
CategoryID: $("#myCategoryId").val()
};
$.ajax({
type: 'POST',
data: JSON.stringify(data),
url: '/Category/ValidateCategoryName',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result) {
$('#myid').closest('form').submit();
}
}
});
});
To elaborate on my comment above. change
<input class="btn btn-primary" id="myid" type="submit" value="Add" />
to
<input class="btn btn-primary" id="myid" type="button" value="Add" />
And in your success function, change
if (!result) {
event.preventDefault();
}
to
if (result) {
$('#myid').closest("form").submit();
}
This way you will only submit the form when result is true, it the ajax call fails or result is false then the form won't be submitted.
DISCLAIMER: The code above may not work, but i hope you get the generel idea.
What I know from a very long time is the Form default redirect action will not wait until ajax returned its result .. So you can use a boolean variable to control that .. see the next code
$(document).ready(function(){
var DefaultFormAction = false; //set the default form action to false
$('form').on('submit' , function(e){
var $this = $(this);
if(DefaultFormAction == false){ // when the default action is false
e.preventDefault(); // prevent the default redirect
setTimeout(function(){ // I use setTimeout here for testing .. Use the next code in your ajax success
DefaultFormAction = true; // return default action to true
$this.submit(); // then submit the form again
} ,10000);
console.log('This result when default is false you will go to the default form action after 10second');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input name="CategoryID" id="myCategoryId" type="text" value="0" />
<input name="CategoryName" id="myCategoryNameId" type="text" value="" />
<input class="btn btn-primary" id="myid" type="submit" value="Add" />
</form>
To test the Form default redirect action will not wait until ajax returned its result you can use e.preventDefault() inside the setTimeout and even you make a time is 1ms without $this.submit() it will still use the default redirect
$(document).ready(function(){
var DefaultFormAction = false; //set the default form action to false
$('form').on('submit' , function(e){
var $this = $(this);
if(DefaultFormAction == false){ // when the default action is false
setTimeout(function(){ // I use setTimeout here for testing .. Use the next code in your ajax success
e.preventDefault(); // prevent the default redirect
} , 1);
console.log('This result when default is false you will go to the default form action after 10second');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input name="CategoryID" id="myCategoryId" type="text" value="0" />
<input name="CategoryName" id="myCategoryNameId" type="text" value="" />
<input class="btn btn-primary" id="myid" type="submit" value="Add" />
</form>
Cleanest way to do so:
$(document).on('submit','form' function(event) {
event.preventDefault();
event.stopImmediatePropagation();
$this = $(this);
var data = {};
data.CategoryName = $("#myCategoryNameId").val();
data.CategoryID = $("#myCategoryId").val();
$.ajax({
type: 'POST',
data: JSON.stringify(data),
url: '/Category/ValidateCategoryName',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result) {
$this.submit();
}
}
});
});
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;
});
});
I was making Wikipedia viewer, and I implemented Wikipedia title search ajax calls were working fine until I added forms tag around input & button tag.
<form class="pure-form">
<input type="text" id="txtff" class="pure-input-rounded" placeholder="Search for...">
<button type="submit" class="pure-button"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></button>
</form>
My ajax code is:
$("button").click(function() {
var url = "https://en.wikipedia.org/w/api.php?action=query&format=json&list=allpages&aplimit=5&apfrom=Albert";
$.ajax({
url: url,
jsonp: "callback",
dataType: "jsonp",
success: function(resp){
console.log(JSON.stringify(resp));
},
error: function(err){
console.log("ERR")
}
});
});
I was doing all this on codepen: http://codepen.io/theami_mj/pen/KMKPvZ
Use type='button', type='submit' will submit the form and page will be unloaded.
$("button").click(function() {
var url = "https://en.wikipedia.org/w/api.php?action=query&format=json&list=allpages&aplimit=5&apfrom=Albert";
$.ajax({
url: url,
jsonp: "callback",
dataType: "jsonp",
success: function(resp) {
console.log(JSON.stringify(resp));
},
error: function(err) {
console.log("ERR")
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form class="pure-form">
<input type="text" id="txtff" class="pure-input-rounded" placeholder="Search for...">
<button type="button" class="pure-button"><span class="glyphicon glyphicon-search" aria-hidden="true"></span>Go!
</button>
</form>
I feel the problem was with form submission with submit button type added. Just add one line of code i.e. e.preventDefault() to prevent default action of your button which is submitting the form, so that it would not submit the form
$("button").click(function(e) {
e.preventDefault()
var url = "https://en.wikipedia.org/w/api.php?action=query&format=json&list=allpages&aplimit=5&apfrom=Manoj";
$.ajax({
url: url,
jsonp: "callback",
dataType: "jsonp",
success: function(resp) {
console.log(JSON.stringify(resp));
},
error: function(err) {
console.log("ERR")
}
});
});
UPDATED FIDDLE
You should attach you click handler / AJAX call to the form's onsubmit event handler:
<form class="pure-form" onsubmit="myAjaxCall">
<input type="text" id="txtff" class="pure-input-rounded" placeholder="Search for...">
<button type="submit" class="pure-button"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></button>
</form>
This would be your script (just created a function called myAjaxCall instead of attaching a click event handler).
myAjaxCall = function() {
var url = "https://en.wikipedia.org/w/api.php?action=query&format=json&list=allpages&aplimit=5&apfrom=Albert";
$.ajax({
url: url,
jsonp: "callback",
dataType: "jsonp",
success: function(resp){
console.log(JSON.stringify(resp));
},
error: function(err){
console.log("ERR")
}
});
}
http://www.w3schools.com/jsref/event_onsubmit.asp
This is normal behavior. button with type submit will send the form. Try to just replace type="submit" with type="button".
You should get rid of the form, or you should add
$("form").on("submit", function(e){
e.preventDefault();
return false;
});
To your JS code, to prevent the default behaviour of the form.
Alternatively, you could move all the logic from your button click event here, too:
$("form").on("submit", function(e){
e.preventDefault();
// your AJAX call here
return false;
});
Hello everyone I am newbie in java-script so i hope you can help me with my issue. So I have the form, it look something like this:
<form method="post">
Field1: <input type="text" name="field1"><br>
Field2: <input type="text" name="field2"><br>
<input type="submit" value="Submit">
</form>
I need to take data from the form and make xml request, the xml request should look like this
<root>
<header section>
<section>data</section>
</header section>
<data section>
<field1>data</field2>
<field2>data</field2>
</data section>
</root>
After that i have to display xml response on the page.
I made xml request
<script>
$('.button').click( function() {
$(".results").append("<ul></ul>");
$.ajax({
type: "GET",
dataType: 'xml',
url: 'response.xml',
success: function(xml) {
$(xml).find('root').each(function(){
var sField1 = $(this).find('field1').text();
var sField2 = $(this).find('field2').text();
$("<li></li>").html(sTitle + ", " + sPublisher).appendTo(".results ul");
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
});
</script>
But I don't know how to take data from the form and make request. Can you help me with it? Thanks a lot.
// You can use jQuery to build XML document:
function buildXmlFromForm(form) {
var xml = $('<XMLDocument />');
xml.append (
$('<header-section />').append(
$('<section />').text('data')
)
).append (
$('<data-section />').append(
$('<field1 />').text(form.find("input[name='field1']").val())
).append(
$('<field2 />').text(form.find("input[name='field2']").val())
)
);
return xml.html();
}
// you should use POST or PUT method (not GET) to post xml-data to server side
$( "#form1" ).submit(function(event) {
event.preventDefault();
$("#results").append("<ul></ul>");
var xmlString = buildXmlFromForm($(this));
$("#xmlSrc").val(xmlString);
$.ajax({
type: "POST",
dataType: 'xml',
url: 'response.xml',
data: xmlString,
success: function(respData) {
$("<li></li>").html("ok: "+respData).appendTo("#results ul");
console.log(respData);
},
error: function(errorData) {
$("<li></li>").html("error: "+errorData.statusText).appendTo("#results ul");
console.log(errorData);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="form1">
Field1: <input type="text" name="field1" value="***v1***"><br/>
Field2: <input type="text" name="field2" value="***v2***"><br/><br/>
<input type="submit" value="Submit">
</form>
<hr/>
<textarea id="xmlSrc" cols="70" rows="5"></textarea>
<div id="results"/>
Try this:
serialize will return formData of current form
You must have unique identifier for your form to be used as querySelector
$('#myForm').on('submit', function(e) {
e.preventDefault();
var formData = $(this).serialize();
$(".results").append("<ul></ul>");
$.ajax({
type: "GET",
dataType: 'xml',
url: 'response.xml',
data: formData,
success: function(xml) {
$(xml).find('root').each(function() {
var sField1 = $(this).find('field1').text();
var sField2 = $(this).find('field2').text();
$("<li></li>").html(sTitle + ", " + sPublisher).appendTo(".results ul");
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="myForm">
Field1:
<input type="text" name="field1">
<br>Field2:
<input type="text" name="field2">
<br>
<input type="submit" value="Submit">
</form>