Why isnt jquery setting my display css value? - javascript

There is my script and the function:
<script>
function post()
{
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var message = document.getElementById("message").value;
var sub = document.getElementById("sub").value;
if(name && email && message && sub)
{
$.ajax
({
type: 'post',
url: 'email.php',
data:
{
user_name:name,
user_email:email,
user_message:message,
user_sub:sub
},
success: function (response)
{
}
});
}
return false;
}
$(document).ready(function(){
$(document).ajaxStart(function(){
$("#mailalert").css("display", "");
});
});
</script>
And there is what should it change:
<div class="mailalert" id="mailalert" style="display: none">
<strong>Thank you for your letter.</strong>
</div>
Why it isnt chaning the display value to " "? It sends the email successfully, so it runs well.

You seem to have omitted part of the code which may contain the actual error. I've tested the following code and it works as expected.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
</head>
<body>
<form id="mail_form" action="email.php">
Name:<br>
<input type="text" id="name" name="name">
<br>
Email:<br>
<input type="text" id="email" name="email">
<br>
Message:<br>
<textarea rows="3" id="message" name="message"></textarea>
<br>
<br><br>
<input type="submit" value="Submit">
</form>
<div class="mailalert" id="mailalert" style="display: none">
<strong>Thank you for your letter.</strong>
</div>
<script>
$("#mail_form").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var message = document.getElementById("message").value;
if(name && email && message) {
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function (data) {
// alert(data); // show response from the php script.
// I'd put $("#mailalert").css("display", ""); here, otherwise it doesn't make sense to display a thank you msg.
}
});
}
});
$(document).ready(function(){
$(document).ajaxStart(function(){
console.log("I'm here")
$("#mailalert").css("display", "");
});
});
</script>
</body>
</html>
Tip:
I'd move $("#mailalert").css("display", ""); to the ajax success function instead.

From the jquery docs
These methods register handlers to be called when certain events, such as initialization or completion, take place for any Ajax request on the page. The global events are fired on each Ajax request if the global property in jQuery.ajaxSetup() is true, which it is by default. Note: Global events are never fired for cross-domain script or JSONP requests, regardless of the value of global.
so in your ajax setup to enable global events, just add global: true. This should solve your problem.
...
$.ajax
({
type: 'post',
url: 'email.php',
global: true,
data:
{
user_name:name,
user_email:email,
user_message:message,
user_sub:sub
},
success: function (response)
{
}
});
...

Related

How to send textbox value to server using ajax?

I have an HTML form which contains a username textbox and a submit button.
When a user inputs a name in the username textbox, I want to take that value and send it over to the server so I can check whether the username has already been taken by another user or not.
Here is my code for creating the form:
<!DOCTYPE html>
<html>
<head>
<script src="JquerySock.js"></script>
<meta charset="utf-8" name="viewport" content="width=device-width, initial- scale=1">
<script>
function Usernameerrorfunc(field, errordiv, Notallowcharserror_SPN){
}
</script>
</head>
<body>
<div id="Registeration_Div" class="Registeration_Div">
<form class="Registration_Form" id="Registration_Form" action="../postr" method="POST">
<div id="Registeration_Username_DIV" class="Registeration_Username_DIV">
<input type="text" id="Registeration_Username_box" class="Registeration_Username_box"
placeholder="" name="UserName" maxlength="30" onblur="Usernameerrorfunc(this, 'Usernameerror_spn', 'Usernamenowallow_spn');" onclick="textboxfocus(this)"/>
</div>
<div class="Registration_Submit_Div">
<input type="submit" value="Submit" id="SumbitForm_btn" class="SumbitForm_btn" name="Submit_btn"/>
</div>
</form>
</div>
</body>
</html>
You could use the $.ajax method in jQuery:
function postUsernameToServer() {
var username = $("#Registeration_Username_box").val();
$.ajax({
url: "http://YourServerUrl",
type: "POST",
data: { username: username },
success: function() {
alert('Successfully connected to the server');
},
error: function() {
alert('Something went wrong');
}
});
}
To invoke this using a button click (From my comment) you could do the following:
<button id="checkUsername">Check username</button>
$("#checkUsername").on("click", function() {
postUsernameToServer();
});
Ensure that you have the jQuery library imported to use the function.
If you did not want to use the jQuery and rather native JavaScript you can use the XMLHttpRequest.
Try this it will work :
Use jQuery.ajax()
Code :
function submitFormData() {
var name = document.getElementById("Registeration_Username_box").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'username=' + name;
if (username == '') {
alert("Please Enter the Username");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "checkUsername.php",
data: dataString,
cache: false,
success: function(data) {
alert(data);
},
error: function(err) {
alert(err);
}
});
}
return false;
}
I am giving example in php for checking the username. You can use any language accordingly.
checkUsername.php :
<?php
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("dbname", $connection); // Selecting Database
//Fetching Values from URL
$username=$_POST['username'];
//Select query
$query = 'select * from user_table WHERE name = "'.$username.'";
$query_result = mysql_query($query);
$res = mysql_fetch_assoc($query_result);
do
{
echo json_encode($res);
}while($res = mysql_fetch_assoc($query_result));
}
mysql_close($connection); // Connection Closed
?>

Redirect from client side using html and ajax or js

I have a login page basically connecting to a location, and do a simple post call. I want to redirect the page to somewhere else if a user clicks submit and if post returns 200 or success. If not, return fail.
What would be the simplest way to do it? I am looking into client side redirect.
<html>
<head>
<title>Login</title>
</head>
<body>
<form action="/1.1.1.1:80/login" method="POST">
<p>Username: <input type="text" name="username" /><p>
<p>Password: <input type="password" name="password" /><p>
<p><input type="submit" value="Log In" /></p>
{% module xsrf_form_html() %}
</form>
</body>
</html>
UPDATE:
<html>
<head>
<title>Please Log In</title>
<script src="/Users/src/downloads/app/jquery-2.1.4.min.js" type="text/javascript"></script>
</head>
<body>
<form action="https://1.1.1.1:80/login" method="POST">
#Tried as well, but doesn't redirect <form action="https://google.com" method="POST">
<input class="form-control" type="text" required name="username" placeholder="username">
<input class="form-control" type="password" required name="password" placeholder="Password">
<input class="form-control" type="hidden" required name="eauth" value="pam">
<p><input type="submit" value="Log In" /></p>
{% module xsrf_form_html() %}
</form>
</body>
</html>
<script type="text/javascript">
$('form').submit(function(){
$.ajax({
type: "Post",
url: $('form').attr('action'),
success: function (response) {
window.location = 'http://www.google.com';
//error handling
}
});
//return false so the form does not submit again
return false;
});
</script>
you can post your form by jquery(ajax) and when result back decide what you want to do.
this link should help you
// Variable to hold request
var request;
// Bind to the submit event of our form
$("#foo").submit(function(event){
// Abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// Let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// Serialize the data in the form
var serializedData = $form.serialize();
// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// Fire off the request to /form.php
request = $.ajax({
url: "/form.php",
type: "post",
data: serializedData
});
// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// Log a message to the console
console.log("Hooray, it worked!");
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// Reenable the inputs
$inputs.prop("disabled", false);
});
// Prevent default posting of form
event.preventDefault();
});
include jQuery and Try to use this according your code input
<script type="text/javascript">
$(document).ready(function(){
$('form').submit(function(){
$.ajax({
url: 'your-php-file.php',
dataType: 'html',
success: function(response) {
window.location.href = response;
}
});
});
});
</script>
Try something like this:
Make sure you have downloaded jquery.js file, put it in your directory somewhere, and put this in the head tag
<script src="path to your jquery file" type="text/javascript"></script>
Put this at the end of your html:
<script type="text/javascript">
$('form').submit(function(){
$.ajax({
type: "Post",
url: $('form').attr('action'),
success: function (result) {
if(result.Code == 200) //change this to your status code return
window.location = 'http://www.google.com';
else
//error handling
}
});
//return false so the form does not submit again
return false;
});
</script>
This should capture the form's submit event and instead post it via ajax which will allow you to handle the response however you want.

How to pass on a form through Ajax, and PHP

I'm new to this, I just want it to work with simple code then i'll add onto it. But it's not working in the sense that i don't get an echo. I just want to submit a form and have it not refresh the page.
here is my form
<form >
<input type="text" id="name" >
<input type="submit" value="s" onclick="return chl()" >
</form>
here is my js
<script>
function chl(){
var name= document.getElementByID('name').value;
var dataString='name' + name;
$.ajax({
type:"post",
url:"hi.php",
data:dataString,
cache:false,
success: function(html){
alert ("success");
}
});
return false;
}
</script>
and here is my php
<?php
$name=$_POST ['name'];
echo "response".$name;
?>
The datastring should be formed like a querystring; you've missed the = between the key and the value:
var dataString = 'name=' + name;
That being said, you can improve your code. Firstly you should attach the event to the submit of the form, and use event.preventDefault() to stop the normal form submission. Also, you can use serialize() to generate an object containing the forms' values to pass across in the AJAX request. The response from your PHP code will be retuned in the parameter sent to the success handler, so you need to do something with it there. Lastly, you should attach your events in JS, not HTML attributes, for a better separation of concerns. Try this:
<form method="hi.php">
<input type="text" id="name" />
<input type="submit" value="s" />
</form>
$('form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "post",
url: this.action,
data: $(this).serialize(),
cache: false,
success: function(html){
alert(html); // = 'response: name = [VALUE]'
}
});
});
$name = $_POST['name'];
echo "response: name = ".$name;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<!--form method="hi.php"--> <!-- Remove this from your code and method is post or get you can't use hi.php as method -->
<input type="text" id="name" />
<input type="submit" id="click" value="s" /> <!-- Give id to your button -->
<!--/form-->
<script type="text/javascript" src="js/jquery.js"></script> <!-- You need to use jquery -->
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#click').on('click', function(event) {
event.preventDefault();
/* Act on the event */
var name=$('#name').val();
$.ajax({
url: 'hi.php',
type: 'POST',
data: {name: name}
})
.done(function(data) {
alert(data); // You can alert that data
console.log(data); //or you view this data on console Ctrl+shift+I
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
});
</script>
</body>
</html>
<!-- Your php page hi.php -->
<?php
echo $_POST['nmae'];
// or just say hi
echo 'hi';
?>
Form
<form name="test" id="test">
<input type="text" id="name" >
<input type="submit" value="s" >
</form>
Script
<script>
$("#test").submit(function(e){
e.preventDefault();
var name= document.getElementByID('name').value;
$.ajax({
type:"post",
url:"hi.php",
data:{"name":name},
cache:false,
success: function(html){
alert (html);
}
});
return false;
}
</script>
You can also try with -
var dataString = $('form').serialize();
By this you can get rid of generating the datastring if you have a number of input fields.
change ajax function like and send data as shown below and your php and js function must be in different pages
function chl(){
var name= document.getElementByID('name').value;
$.ajax({
type:"post",
url:"hi.php",
data:{name:name},
success: function(html){
alert ("success");
}
});
return false;
}
<form method="POST" action="server.php">
<input type="text" name="name" id="myName" >
<input type="submit" value="s" onclick="chl(); return false;" >
</form>
<script>
function chl()
{
var nameElement = document.getElementById("myName");
//Creates formData object and sends it to PHP script
var formData = new FormData();
//name equals to input element name attribute value
formData.append(nameElement.name, nameElement.value);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
alert(xmlHttp.responseText);
}
}
xmlHttp.open("POST", "server.php");
xmlHttp.send(formData);
}
</script>
<?php
$name = $_POST['name'];
echo $name;
?>

sending by post php ajax

Good morning, I want to send to an external site to my two variables by post are username and password and the page I create a cache in the browser when I go to another url already be logged in code what I do is check for through PHP if the data is correct or not, if they are correct returned if, but returns no, if they are correct what I want to do is force the form to send the submit the url, the problem is that everything works fine to the point the submit the form no longer do anything, can you help me?
Thank You
My code:
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#submit").click(function () {
var user = $("#user").val();
var pass = $("#pass").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'user=' + user + '&pass=' + pass;
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "index.php",
data: dataString,
cache: false,
success: function (result) {
if (result == 'si') {
$("form").attr('action', 'http://xzc.tv/login');
$("form").submit();
//window.open('http://xzc.tv');
alert('entro if');
return true;
} else {
alert('entro else');
}
}
});
return false;
});
});
</script>
</head>
<body>
<form action="" method="post" id="formoid">
<div><label>Usuario:</label><input name="user" placeholder="Usuario" type="text" id="user"></div>
<div><label>Contraseña:</label><input name="pass" placeholder="Contraseña" type="text" id="pass"></div>
<div><input name="enviar" type="submit" value="Enviar" id="submit"></div>
<div><input name="btnPass" type="submit" value="¿Olvidaste tu contraseña?"></div>
</form>
</body>
Just declare the event parameter in the click handler, and then do event.preventDefault(). Doing so, the default submit action is ignored and your code will be executed instead:
$(document).ready(function () {
$("#submit").click(function (e) {
e.preventDefault();
var user = $("#user").val();
var pass = $("#pass").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'user=' + user + '&pass=' + pass;
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "index.php",
data: dataString,
cache: false,
success: function (result) {
if (result == 'si') {
$("form").attr('action', 'http://xzc.tv/login');
$("form").submit();
//window.open('http://xzc.tv');
alert('entro if');
return true;
} else {
alert('entro else');
}
}
});
return false;
});
});
checkout the result whether its returning "si" if its correct
try
changing code
from
$("form").attr('action', 'http://xzc.tv/login');
$("form").submit();
to
$("#formoid").attr('action', 'http://xzc.tv/login');
$("#form").submit();
try using id of form
To submit try the following
$("form#formoid").submit();
$("form#formoid")[0].submit();
$("form#formoid").submit(function(e) {});

Jquery ajax() function won't load PHP script

I'm trying to create a simple login with PHP and MySQL and I'm using the AJAX() jquery function to load the PHP script.
All that I want to do is to load a new web page (for example java2s.com) when the script finds the user in my database.
Problem is that the script won't work at all.
This is the HTML with the Jquery:
EDIT: This is the fixed code thanks to all those who commented, which sadly still doesn't work.
<!DOCTYPE HTML>
<html>
<head>
<title> Login </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script language="JavaScript">
function change()
{
document.location.href="http://www.java2s.com";
}
$(document).ready(
$("#loginForm").click(function() {
var jsonlogin=new Object();
jsonlogin.username=$('#username').val();
jsonlogin.password=$('#password').val();
var sendstr = JSON.stringify(jsonlogin);
$.ajax({
type: 'POST',
url: 'login.php',
async: false,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: sendstr,
success:function(response){
if (response['result']=="login successful")
{
change();
}
}
});
})
)
</script>
</head>
<body>
<h1> INSERT USERNAME AND PASSWORD</h1>
<input type="text" id="username" name="username"> USERNAME <br>
<input type="password" id="password" name="password"> PASSWORD <br>
<input type="submit" id="loginForm" class="button positive">
</body>
</html>
The PHP script is very simple:
<?php
$data = file_get_contents('php://input');
$result = json_decode($data);
$con=mysqli_connect("localhost","****","*****","*******");
$str="SELECT ID FROM users WHERE username='".$result->username."' AND password='".$result->password."';";
$exists = mysqli_query($con,$str);
if (mysqli_num_rows($exists) ==1)
{
$arr = array('result'=>"login successful");
$ris=json_encode($arr);
echo $ris;
}
else
{
$arr= array('result'=>"login error");
$ris=json_encode($arr);
echo $ris;
}
mysqli_close($con)
?>
When I load the page and press the submit button nothing will happen.
Anyone can help?
Thank you very much in advance
try something like this
$("#loginForm").click(function() {
var jsonlogin=new Object();
jsonlogin.username=$('#username').val();
jsonlogin.password=$('#password').val();
$.ajax({
type: 'POST',
url: 'login.php',
async: false,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: jsonlogin,
success:function(response){
if (response['result']=="login successful")
{
change();
}
}
});
})
EDITED CODE
you have not implemented DOM ready method correctly
$(document).ready(function(){
// code goes here
});
Maybe because all the php is commented out?
Also in your success function should look like this:
success: function(response){
dosomethingwithrespones(response);
}
The data in the $.ajax denotes what you send.
why are you using function ajaxJson()... try to remove it and if you really want to use it then modify your button code like this and remove $("#loginForm").click(function() { } from jquery...
<input type="submit" id="loginForm" class="button positive" onclick="ajaxJson()">
and change <script type="text/javascript"> instead of <script language="javascript">.. this identifier is not standard, this attribute has been deprecated(outdated by newer constructs) in favor of type.
first way
function ajaxJson()
{
//your code goes here without triggering **click** event..
}
<input type="submit" id="loginForm" class="button positive" onclick="ajaxJson()">
second way
$("#loginForm").click(function()
{
//your code goes here...
}
<input type="submit" id="loginForm" class="button positive">
keep everything outside $(document).ready function...
hope it may help you
You have missed ending { and } for ready function.try below code.
<!DOCTYPE HTML>
<html>
<head>
<title> Login </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script language="JavaScript">
function change()
{
document.location.href="http://www.java2s.com";
}
$(document).ready(function () {
$("#loginForm").click(function() {
alert("hi");
var jsonlogin=new Object();
jsonlogin.username=$('#username').val();
jsonlogin.password=$('#password').val();
var sendstr = JSON.stringify(jsonlogin);
$.ajax({
type: 'POST',
url: 'login.php',
async: false,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: sendstr,
success:function(response){
if (response['result']=="login successful")
{
change();
}
}
});
});
});
</script>
</head>
<body>
<h1> INSERT USERNAME AND PASSWORD</h1>
<input type="text" id="username" name="username"> USERNAME <br>
<input type="password" id="password" name="password"> PASSWORD <br>
<input type="button" id="loginForm" class="button positive">
</body>
</html>
try this query in login.php,
$str="SELECT ID FROM users WHERE username='".$result->username."' AND password='".$result->password."' ";
Jquery:
$(document).ready(function(){
$("#loginForm").click(function() {
var jsonlogin=new Object();
jsonlogin.username=$('#username').val();
jsonlogin.password=$('#password').val();
var sendstr = JSON.stringify(jsonlogin);
$.ajax({
type: 'POST',
url: 'login.php',
async: false,
dataType: 'json',
data: sendstr,
success:function(response){
if (response.result=="login successful")
{
change();
}else{
alert(response.result);
return false;
}
}
});
});
});

Categories

Resources