pass values from textbox to url in javascript - javascript

How can i pass values from textbox to a url on click of a button using javascript? I have a login page. when i input a username and password in a textbox, the url should take the values and give the response. How can i do it?
http://url.php?id=login&email=<email>&password=<password>
This url gives response as {"status":0,"msg":"Email is Wrong!"} and when i put my id and pwd in url
http://url.php?id=login&email=abc#gmail.com&password=abc
url give response as
{"status":1,"msg":"Session is active","session_id":"p246igeaadcdui7hb0o2677c53","user_id":"13"}
Thanks in advance..
function A() {
$.getJSON('http:url.php?id=login&email=&password=', function (data) {
alert(data.status);
alert(data.msg);
});
}
function B() {
$.getJSON('url.php?id=login&email=&password=', function (data) {
alert(data.user_id);
document.getElementById("login").innerHTML;
});
}
Username :
Password :
This is what i am working on

Plain javascript:
var email = document.getElementById("email").value;
var password = document.getElementById("password ").value;
var url = "http://url.php?id=login&email="+encodeURIComponent(email)+"&password="+encodeURIComponent(password);
window.location.href = url;
jQuery:
var email = $("#email").val();
var password = $("#password").val();
var url = "http://url.php?id=login&email="+encodeURIComponent(email)+"&password="+encodeURIComponent(password);
window.location.href = url;
Note that for my example to work, the email and the password input fields must have the id set to email and password respectively.

ajax version:
//same as satoshi version
var myUrl = "http://url.php?id=login&email="+encodeURIComponent(email)+"& password="+encodeURIComponent(password);
$.ajax({
url : myUrl,
dataType : 'json',
success : function(data){
alert( data.status ? ("logged in " + data.msg) : ("error: " + data.msg));
},
error : function(jqXHR, textStatus, errorThrown){
alert('error ' + errorThrown);
}
});

Related

How to store the username in the URL while working on Ajax calls

I am new to front-end and was trying to create a Login page which had username and password to login. I wanted to store the Logged-In username in the URL, so had to use the PUT method in the AJAX call. But my login is always failing as I am unable to pass the correct username attribute in the URL, Please see the below code to refer:
Again how to pass the {username} in the URL, you can see the below URL in ajax call where I have this username attribute.
jQuery:
$("#login-user").validate({
submitHandler: userLogin
});
function userLogin() {
var data = $("#login-user").serialize();
if (userName != '' && password != '')
{
$.ajax({
url: 'http://www.website.com/database/tableusers/{username}/login',
type: 'PUT',
data: data,
success: function(data) {
if (data == 0) {
result.html('<span class="error">Incorrect username or password</span>')
} else if (data == 1) {
window.location = "tothepage.html";
} else {
$("#error").fadeIn(1000, function() {
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> ' + data + ' !</div>');
});
}
}
});
}
}
You haven't defined either userName or password. data is correct, though.
Also, it might be right for your backend code, but you probably would have to use POST (type).
So, you're missing this:
function userLogin() {
var data = $("#login-user").serialize();
var userName=$("#userNameInputID").val();
var password=$("#passwordInputID").val();
if (userName != '' && password != '')
{
$.ajax({
url: 'http://www.website.com/database/tableusers/'+userName+'/login', //just concatenate userName here (case sensitive)
type: 'PUT',
data: data,
....
Keep the username as a variable.
var url = 'http://www.website.com/database/tableusers/'+username+'/login';
Build the URL first and store it in a variable, then use the variable in the AJAX call.
For instance:
var userUrl = 'http://www.website.com/database/tableusers/' + userName + '/login';
$.ajax({
url: userUrl,
type: 'PUT',
data: data,
success: function(data) {
You just need to access the username and password variables from your data object and define them as vars
function userLogin() {
var data = $("#login-user").serialize();
var username = data.username;
var password = data.password;
if (username != '' && password != '')
...
Also, you can inject the variable for username into the URL by adding it with the + string operator
url: 'http://www.website.com/database/tableusers/' + username + '/login';

Ajax not working well

I'm trying to submit a form using Ajax , but it doesn't work here is my Ajax :
$(document).ready(function(){
$("#submit").click(function(event){
var ad1 = $("#ad1").val();
var ad2 = $("ad2").val();
var city = $("city").val();
var state = $("state").val();
var zip = $("zip").val();
var country = $("country").val();
var mm = $("mm").val();
var dd = $("dd").val();
var yy = $("yy").val();
var lname = $("lname").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name1='+ name + '&ad11='+ ad1 + '&ad21='+ ad2 + '&city1='+ city + '&state1='+ state + '&zip1='+ zip + '&country1='+ country + '&mm1='+ mm + '&yy1='+ yy + '&dd1='+ dd + '&lname1=';
if(name=='')
{
alert("");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
and it's not giving any result just giving data in header
the result is like :
I copied the javascript to the form page it's now working ,but the ajax is returning a blank alert while it should be "Form Submitted Succesfully"
I guess that it's an error of inclusion of the file , but i'm using the right directories.
here is action.php :
<?php
$con = mysqli_connect("server","user","pass","db");
$name=$_POST['name1'];
$ad1=$_POST['ad11'];
$ad2=$_POST['ad21'];
$city=$_POST['city1'];
$state=$_POST['state1'];
$zip=$_POST['zip1'];
$country=$_POST['country1'];
$mm=$_POST['mm1'];
$dd=$_POST['dd1'];
$yy=$_POST['yy1'];
$dob=$dd."/".$mm."/".$yy;
$mm=$_POST['mm1'];
$name=$_POST['name1'];
$lname=$_POST['lname1'];
$r2=rand(10000,90000);
$query = mysqli_query($con,"insert into users values('$r2','$name','$lname','$ad1','$ad2','$city','$state','$zip','$country','$dob')");
mysqli_close($con);
echo "Form Submitted Succesfully";
?>
This name variable is not have defined in ajax file var dataString = 'name1='+ name + so name would be an empty string
=> if(name=='')
{
alert("");
} executed. Please add string into alert and check again :)

How to pass a variable to HTML page from JS code , after ajax success?

Consider the ajax request :
var idNumber = $("#Field_1").val();
var servletUrl = "someURL"; // some url goes here
$.ajax({
url: servletUrl,
type: 'POST',
cache: false,
data: { },
success: function(data){
alert(data);
window.location = "./replyToYou.html";
}
, error: function(jqXHR, textStatus, err){
alert('text status '+textStatus+', err '+err + " " + JSON.stringify(jqXHR));
}
});
How can I pass , on success idNumber to replyToYou.html , and how can I grab it in replyToYou.html ?
Much appreciated
you have to different solution:
1- first is using queryString:
success: function(data){
alert(data);
window.location = "./replyToYou.html?idNumber=" + idNumber;
}
then read it from querystring using this function (I use it as a querystring helper which is originally created in this POST):
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
getParameterByName("idNumber");
2- the other option is using localStorage:
success: function(data){
alert(data);
localStorage.setItem("idNumber",idNumber);
window.location = "./replyToYou.html";
}
and get it at the other page like:
localStorage.getItem("idNumber")
edit code js in success section :
success: function(data){
alert(data);
window.location.href = "./replyToYou.html?idNumber=" + idNumber;
}

Display the JSON response

How to display the JSON response in jsp page through ajax...
function doAjaxPost() {
var name = $('#name').val();
var password = $('#password').val();
var gender = $('#gender').val();
var aboutYou = $('#aboutYou').val();
$.ajax({
type: "POST",
url: "add.htm",
data: "name=" + name + "&password=" + password + "&gender=" + gender + "&aboutYou=" + aboutYou,
success: function(response){
alert('name : '+response);
},
error: function(e){
alert('Error: ' + e);
}
});
Here in this alert('name : '+response); I get the response ,but i want to display on this jsp page.. This is form data which i have to display...plz help..thanks in advance
You need to parse the json data using json parser and then populate tables..!
var resultData = JSON.parse(response);
//resultDate will ve json object in the form of JS objects
resultData.membervalues (or arrays)
Hmm... I don't understand your problem. What do you want to display and where? Create a on your page where you want and replace your alert with:
$('#myResponce').html(responce);
is this what you want?

How to add a variable to URL of $.ajax({ url : " "});

I want the user to be able to change a part of the URL address to their post code. I have a text box and button which I am hoping will submit the value to the URL.
jQuery:
jQuery(document).ready(function($) {
$.ajax({
url : "http://SomeAddress.com/" + PostCode + ".json",
dataType : "jsonp",
success : function(parsed_json) {
HTML:
<input type="text" id="GetPostCode" />
<button id="SetPostCode">Set This Post Code</button>
jQuery:
$("#SetPostCode").click(function() {
var PostCode = document.getElementById("GetPostCode").value;
$("#GetPostCode").val(" ");
return false;
});
I understand that the line
$.ajax({
url : "http://api.wunderground.com/api/2508132ae0c7601a/geolookup/conditions/q/UK/" + PostCode + ".json",
does not work that way, but I didn't know what else to do. Could someone please show me what I need to do in order for this to work?
jQuery(document).ready(function($) {
var PostCode=1;
$.ajax({ url : "http://SomeAddress.com/"+PostCode +".json",
dataType : "jsonp"
//.... more stuff
});
$("#SetPostCode").click(function() {
PostCode = document.getElementById("GetPostCode").value;
$("#GetPostCode").val(" ");
return false;
});
});
Above would work as PostCode is now global to the jQuery and can be accessed anywhere

Categories

Resources