AJAX call on a javascript function doesn't work - javascript

This is actually the first time I'm using ajax so honestly I don't know a single thing. Tried to read articles about ajax but no luck. What I'm trying to do here is quite simple really I just want to try to figure out how ajax works and what I should do to make it work. I wanted it so that when I try to click the login button and go to my php and display "login success" it works when the textboxes are empty it displays fields are empty but the ajax doesn't seem to work
Here is what I've done so far this is my index.php A.K.A login page
<!DOCTYPE html>
<html>
<head>
<title>O-Chat</title>
<link rel="stylesheet" type="text/css" href="index.css">
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="script101.js"></script>
</head>
<body>
<div class="content">
<div class="features">
<div><br><br><br><br><br><br><br><br><br><br>FEATURES HERE</div>
</div>
<div class="loginpart">
<div class="banner"><br><br><br>BANNER HERE</div>
<div class="login" id="divlogin">
<div class="login-header">Login</div>
<form name="loginform" class="login">
<input class="login" type="text" name="pUname" id="jUname" maxlength="35" placeholder="Username"/><br>
<input class="login" type="Password" name="pPass" id="jPass" maxlength="40" placeholder="Password"/><br>
<span class="error" id="jloginerror"></span>
<div class="button" id="login"" onclick="validate();">
</div>
</form>
<div class="login-footer" onclick="location.href='register.php'">Not yet a member?<br>Register Now! Click Here!</div>
</div>
</div>
</div>
<div class="footer">
<div class="footer-container">
Home |
About O-Chat |
Contact Us
<div style="float: right;">Copyright © 2000 - 2017 O-Chat Unlimited (071813-S) All Rights Reserved</div>
</div>
</div>
</body>
</html>
Here is my javascript file script101.js
function validate() {
var uname = $("#jUname").val();
var pass = $("#jPass").val();
var data = "&uname=" + uname + "&pass=" + pass;
if(!uname.match(/\S/) || !pass.match(/\S/)) {
document.getElementById("divlogin").style.height = '275px';
document.getElementById("jloginerror").innerHTML = "Some fields are empty!";
}
else
{
document.getElementById("jloginerror").innerHTML = "";
document.getElementById("divlogin").style.height = '250px';
$.ajax({
type: "post",
url: "login.php",
data: data,
sucess:function(data){
$("#jloginerror").text(data);
}
});
}
}
<?php
echo "very successful";
?>

Remove $ from the function declaration $function validate(). You can not use $ here.
You can use it like either
$(function(){
....
});
OR
if you wants to keep name of your function then just remove $ before the function, simply use it as:
function validate(){
....
}
and on ajax , you can use
$.ajax({
method: "post",
url: "login.php",
data: data;
sucess:function(data){
$("#jloginerror").text(data);
}
});
So your full code should be like as follows:
function validate() {
var uname = $("#jUname").val();
var pass = $("#jPass").val();
var data = "&uname=" + uname + "&pass=" + pass;
if(!uname.match(/\S/) || !pass.match(/\S/)) {
document.getElementById("divlogin").style.height = '275px';
document.getElementById("jloginerror").innerHTML = "Some fields are empty!";
}
else
{
document.getElementById("jloginerror").innerHTML = "";
$.ajax({
type: "post",
url: "login.php",
data: data,
sucess:function(data){
$("#jloginerror").text(data);
}
});
}
}

Remove $ from the function keyword and Jquery works with element id or name var uname = $("#jUname").val(); var pass = $("#jPass").val(); and do not use ; for separating and you should use , $.ajax({}), use $.ajax({}) instead of ajax({}) because its Jquery function not javascript function.
function validate() {
var uname = $("#jUname").val();
var pass = $("#jPass").val();
var data = "&uname=" + uname + "&pass=" + pass;
if(!uname.match(/\S/) || !pass.match(/\S/)) {
document.getElementById("divlogin").style.height = '275px';
document.getElementById("jloginerror").innerHTML = "Some fields are empty!";
}
else
{
document.getElementById("jloginerror").innerHTML = "";
$.ajax({
type: "post",
url: "login.php",
data: data,
sucess:function(data){
$("#jloginerror").text(data);
}
});
}
}

Related

The response received in AJAX call is shown in another HTML page

I have ajax request call which sends an ID to the server, then the server sends a JSON response. I want to update the innerHTML of the pre tag using the value in that JSON Response.
Form HTML
<form id="AssociateForm" class="form form-inline" style="float:right" action="{% url 'Project:MyView' TR.id %}" method="POST" target="_blank">
<div class="form-group">
<input type="text" name="JIRA_ID" style="width:150px" placeholder="ID" class="form-control has-success" id="{{TR.id}}">
<button name="button" type="submit" id='Submit_{{TR.id}}' class="btn btn-primary">Associate</button>
</div>
</form>
AJAX
<script>
$("#AssociateForm").submit(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
var local_id = $('input[name=J_ID]').attr('id');
var formData = {
'J_ID' : $('input[name=J_ID]').val()
};
console.log(formData)
$.ajax({
url: url,
data: formData,
dataType: 'json',
success: function (datas) {
var data = JSON.parse(datas);
if(datas.status){
alert(datas);
//$('#Failure_'+local_id).innerHTML = data.category + ' issue: '+data.j_id +' ('+data.j_status+')'
}
},
error: function(jqXHR, textStatus){
alert("In error")
}
})
.done(function(data){
alert(data)
});
});
</script>
for some reason, the above code is not printing the console log as well.
But,
When the response comes, the success section is not triggered. Instead, the complete JSON string is printed on a different page.
JSON Response
{"category": "known", "j_id": "AU298", "j_status": "Confirmed"}
below is from View-Page-source
<html>
<head></head>
<body data-gr-c-s-loaded="true">
<pre style="word-wrap: break-word; white-space: pre-wrap;">
{"category": "known", "j_id": "AU298", "j_status": "Confirmed"}
</pre>
</body>
</html>
This is possibly because you are submitting a form, and after submitting it will open a new tab, as Form is submitted.
To resolve this, you can probably use the below code:
<form action="..." method="POST" target="_blank">
<input type="submit" id="btn-form-submit"/>
</form>
<script>
$('#btn-submit').click( function(){ $('#btn-form-submit').click(); } );
</script>
success: function (datas) {
if (datas.status) {
alert(datas);
$('pre#<ID>').html(datas.category + ' issue: ' + datas.j_id + ' (' + datas.j_status + ')');
}
}
This worked for me, I removed the form completely.
Code in-place of Form
<div class="form-group AssociateForm" style="float:right">
<input type="text" name="J_ID" style="width:150px;float:left" class="form-control has-success">
<button name="button" type="submit" id="{{TR.id}}" class="Associater btn btn-primary">Associate</button>
</div>
AJAX
<script>
$('.Associater').on('click', function () {
var local_id = $(this).attr('id');
var j_id = $(this).closest("div.AssociateForm").find('input[name=J_ID]').val();
if (j_id === "") {
alert("JID cannot be empty")
return false
}
var url = "{% url 'Project:View' 0 %}".replace('0', local_id);
var formData = {
'J_ID' : j_id,
'csrfmiddlewaretoken': '{{ csrf_token }}'
};
console.log(local_id);
console.log(j_id);
console.log(url);
console.log(formData);
$.ajax({
type: 'POST',
url: url,
data: formData,
dataType: 'json',
success: function (data) {
if (data.status) {
ele = 'Failure_'+local_id;
document.getElementById(ele).innerHTML = data.category + ' issue: '+data.j_id +' ('+data.j_status+')';
}
},
error: function (jqXHR, textStatus ) {
alert("For some reason im here");
}
});
});
</script>

Submit form using ajax and pass the value submitted to new page

i have form that need the previous value inserted....i'm using ajax,but the success: function(data) wont let me moved to the next page...
here is my code
HTML
<form>
<input type="text" name="id_1" id="id_1>
<input type="text" name="id_2" id="id_2>
<input type="text" name="id_3" id="id_3>
<button type="button" onclick="next();">
</form>
<div id="tabelna"></div>
JQuery
var id_1 = $('#id_1').val();
var id_2= $('#id_2').val();
var id_3= $('#id_3').val();
var datana = 'id_1='+id_1+'&id_2='+id_2+'&id_3='+id_3;
var urlna="<?=base_url()?>something/something/something";
$.ajax({
type: 'POST',
url: urlna,
data: datana,
beforeSend:function(data){
},
message:"<center>><h3>Loading Data. . .</h3></center>"
});
},
error: function(data) {
jAlert('Failed');
},
success: function(data) {
load();
}
})
return false;
}
function load()
{
$('#tabelna').load('<?=base_url()?>something/something/something') (This is my mistake)
}
CONTROLLER
function set_value()
{
extract($_POST);
$d['id1'] = $this-db->query('SELECT * FROM TBL1 where id='.$id_1);
$d['id2'] = $this-db->query('SELECT * FROM TBL2 where id='.$id_2);
$d['id3'] = $this-db->query('SELECT * FROM TBL3 where id='.$id_3);
$this->load->view('something/v_add',$d); (this is my mistake)
}
How can i pass the submitted value to the controller and shows new form ?
we can call controller function using window.location
function load()
{
window.location.href = "<?php echo site_url('controller_d/login/admin_link_delete_user');?>";
}

Textarea is not displaying the result

I have a textarea which will be in hidden state when the request comes to the page and once i select the value in the page i call a controller method which does manipilation and returns the response to the same page and in the ajax success method i try to print the response in the textarea
This is my gsp page
<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="main" />
<title>Json Compare</title>
<g:javascript plugin="jquery" library="jquery"
src="jquery/jquery-1.11.1.js" />
<script>
$(document).ready(function(){
$('.testMe').click(function(){
var URL="${createLink(controller:'jsonComparison',action:'compare')}";
alert(URL)
alert(firstText.value)
alert(secondText.value)
$.ajax({
url:URL,
data: {firstText:firstText.value,secondText:secondText.value},
success: function(data){
var retrievedValue = JSON.parse(data);
alert("Parsed Values are: "+retrievedValue)
alert("Values are: "+retrievedValue.status)
//alert("success: "+retrievedValue.result)
if (retrievedValue.status===true) {
alert("inside the success: "+retrievedValue.result)
alert("the parsed values 1st data"+data.firstText)
$("#result").css("display","block")
$("#result").val(data.firstText)
//notice .html since it is content of textArea
//$('.textarea').html(retrievedValue.result)
//document.getElementById("textarea").style.display = "block"
//document.getElementById("textarea").innerHTML = data.result
//$('#textarea').val(retrievedValue.result).show()
// $('.textarea').css("display","");
//$('#result').attr('style', 'display:block'); 
//$('#testdiv').show()
//$('.textarea').toggle();
// $('#testdiv').attr('style', 'display:block'); 
//$('#testdiv').removeAttr("style");
//document.getElementById("result").style.display = "none";
} else { /// if (data===false ) {
alert("Failure: "+retrievedValue.value1+" "+retrievedValue.value2)
//$('#result1').html(entry.value1).show()
// $('#result2').html(entry.value2).show()
}
}
});
});
});
//event.preventDefault();
</script>
</head>
<body>
<g:form>
<div>
<label>From Time</label>
<g:select name="firstText" from="${eventsList}" noSelection="['':'-Choose the From Date-']" />
<label>To Time</label>
<g:select name="secondText" from="${eventsList}" noSelection="['':'-Choose the To Date-']" />
<button class="testMe">Compare</button>
</div>
<br>
<textarea id="result" style="display: none"></textarea>
<%--<div id="textarea">
<label>Output</label><br>
<textArea id="result" name="myField" />
<textarea></textarea>
</div>
--%></g:form>
</body>
</html>
once the result is displayed immediately it disappears how to stop it. And also how to display the result different textarea based on the response from the controller. Initially the textarea should not be visible
Treat a textArea like a div
$('#textArea').html('content');
Unless you declare:
<g:textArea value="something" />
Which then behaves differently to a standard textArea if I recall correctly
Update:
$(document).ready(function(e){
$('.testMe').click(function(e){
e.preventDefault();
var URL="${createLink(controller:'jsonComparison',action:'compare')}";
alert(URL)
alert(firstText.value)
alert(secondText.value)
$.ajax({
url:URL,
data: {firstText:firstText.value,secondText:secondText.value},
success: function(data){
//alert("success"+data.value)
console.log(data);
$("#result").val(data).show()
}
});
});
});
try this.. hopefully it'll work.
$(document).ready(function() {
$('.testMe').click(function() {
var URL = "${createLink(controller:'jsonComparison',action:'compare')}";
var firstText = $('#firstText');
var secondText = $('#secondText');
alert(URL);
alert(firstText.val());
alert(secondText.val());
$.ajax({
url: URL,
data: {
firstText: firstText.val(),
secondText: secondText.val()
},
success: function(data) {
//alert("success"+data.value)
console.log(data);
$("#result").val(data);
$("#result").show();
}
});
});
});
And if you try to append the textarea element dynamically? For example:
$(document).ready(function(){
$('.testMe').click(function(){
// ... your code ...
// ajax part
$.ajax({
url:URL,
data: {firstText:firstText.value,secondText:secondText.value},
success: function(data){
var textarea_el = $('<textarea />', {
id: 'result',
text: data.value // or just data?
});
// change form_selector with the real selector!
$(<form_selector>).append(textarea_el);
}
});
});
});
<script>
$(document).ready(function(){
$('.testMe').click(function(){
var URL="${createLink(controller:'jsonComparison',action:'compare')}";
alert(URL)
alert(firstText.value)
alert(secondText.value)
$.ajax({
url:URL,
data: {firstText:firstText.value,secondText:secondText.value},
success: function(data){
//alert("success"+data.value)
console.log(data);
$("#result").css("display","block")
$("#result").val(data.firstText)
}
});
});
});
</script>
try above code
if it not ,try to alert(data.firstText) check the return value in alert .whether it is object or value

LogIn Page Using JQuery

Before 3 days the code was working fine. But now its not.
please point out my mistake as i am new to JQuery.
I debugged it, and found out that debugger is not entering inside success method of ajax. and not even going to CS file.
Code of Jquery-
<script type="text/javascript">
$(document).ready(function () {
$('#btnSubmit').click(function () {
alert('b');
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "admin.aspx/LogIn",
dataType: "json",
data: "{'name':'" + $('#txtfn').val() + "','password':'" +$('#txtln').val() + "'}",
success: function (data) {
alert(data);
var obj = data.d;
alert(obj);
alert(data.d);
if (obj == 'true') {
$('#txtfn').val('');
$('#txtln').val('');
alert("dasdsad");
window.location = "home.aspx";
alert("success");
}
else if (obj == 'false')
{ alert("errorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"); }
},
error: function (result) {
alert(data);
alert("aaaaaaafgdgfdfgsfgfhffghgfhgfhfghfghfhfghfhfghgfhgfhgfhgfhfghfghgfhgfhgf");
alert(result);
}
});
});
});
</script>
</head>
<body>
<div id="login">
<div id="triangle"></div>
<h1>Log in</h1>
<form id="f1" runat="server">
<input type="text" id="txtfn" placeholder="name" />
<input type="text" id="txtln" placeholder="Password" />
<input type="submit" id="btnSubmit" value="Log in" />
</form>
</div>
</body>
Code-
[WebMethod]
public static string LogIn(string name, string password)
{
string retMessage = string.Empty;
string constr = ConfigurationManager.ConnectionStrings["oltest_conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string Query = "select * from profile where name=#pname and password=#pwd";
using (SqlCommand cmd = new SqlCommand(Query, con))
{
cmd.Parameters.AddWithValue("#pname", name);
cmd.Parameters.AddWithValue("#pwd", password);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
//retMessage = "home.aspx";
retMessage = "true";
}
else
{
retMessage = "false";
}
}
return retMessage;
}
}
You just need to remove
alert('b');``
on your jquery code
try adding a
return false
at the end of the ajax call
Hi change your submit button to button.
<input type="button" id="btnSubmit" value="Log in" />
data: {name: $('#txtfn').val() ,password: $('#txtln').val()},
I updated my answer:
your ajax call is not executed because form is submitted, this code will prevent submission
$("#f1").submit(function (e) {e.preventDefault();})
place it before $('#btnSubmit').click(function () {
better way will be place your code inside
$("#f1").submit(function (e) {
e.preventDefault();
// here place content of $('#btnSubmit').click(function () {( )}
})
Please ensure JSON data /parameters accepted by your web method and it returning proper true/false without any exception/error.
You can do it by debugging in firebug and Visual Studio.

ajax call not getting executed in php

I m sending some checkbox which are selected,their value to next php page with ajax call.but in the above code i m not able to send it to ajax call
code is as below
<html>
<head>
<title>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
function get_check_value() {
var c_value = [];
$('input[name="services"]:checked').each(function () {
c_value.push(this.value);
});
return c_value.join(',');
}
$(document).ready(function(){
$('#btnSubmit').on('click', function () {
alert("hi");
//var os = $('#originState').val();
\ //var c = $('#commodity').val();
//var ds = $('#destState').val();
var ser = get_check_value();
//var queryString = "os=" + os;
var queryString = "&ser=" + ser;
alert("hi");
$.ajax({
//alert("ajax");
type: "POST",
url: "sortingajax.php",
data: "query=" + queryString,
success: function (b) {
// alert(a+' ok. '+b)
$('#results').html(b);
console.log(b);
}
});
});
});
</script>
<form name="searchForm">
<input type="checkbox" name="services" value="twic" />TWIC
<br/>
<input type="checkbox" name="services" value="enclosedTrucking" />Enclosed Trucking
<br/>
<input type="checkbox" name="services" value="flatBedTrucking" />Flat Bed Trucking
<br/>
<input type="submit" id="btnSubmit" value="Submit" />
</form>
<div id="results">
</div>
</body>
</html>
In above code.When i select checkboxes from page,and on click of submit.i want to pass them to next php page with ajax call.but its not going to next page and no response is coming back....
Please help guysss
ajaxphp page
<?php
include('connection.php');
$query=$_GET['query'];
echo $query;
$countsql='SELECT * FROM XML';
$countsql1=mysql_query($countsql);
$numrows = mysql_num_rows($countsql1);
$countArray2=array();
print($countsql);
while($row = mysql_fetch_array($countsql1)) {
// Append to the array
$countArray2[] = $row;
//echo $row['PID']."<BR />";
}
?>
<?php
foreach($countArray2 as $array)
{
?>
<div class="search">
hi
</div>
<?php $i++; } ?>
data: "query=" + queryString, is wrong because the "query=" + is a syntax error. It should be:
var queryString = "os="+os+"&ser="+ser;
and then
data : queryString,
Or you can format it like:
data : {
'ser' : ser,
'os' : os
}
Then there is the fact that your Ajax is using POST but you're trying to read the request with $_GET rather than $_POST or $_REQUEST in your PHP.
You can try with these two amends:
var data : "?ser=" + ser; // put '?' instead of '&'
Or more jQuery way:
data : { ser : ser },
And you are missing the dataType in your ajax:
dataType : 'html',
On the php side, as this is a post request, so you have to put this:
$query=$_POST['ser'];
Maybe you're forgetting to prevent the Submit button default behavior:
<script type="text/javascript">
function get_check_value() {
var c_value = [];
$('input[name="services"]:checked').each(function () {
c_value.push(this.value);
});
return c_value.join(',');
}
$(document).ready(function(){
$('#btnSubmit').on('click', function (evt) {
evt.preventDefault();
alert("hi");
//var os = $('#originState').val();
\ //var c = $('#commodity').val();
//var ds = $('#destState').val();
var ser = get_check_value();
//var queryString = "os=" + os;
var queryString = "&ser=" + ser;
alert("hi");
$.ajax({
//alert("ajax");
type: "POST",
url: "sortingajax.php",
data: "query=" + queryString,
success: function (b) {
// alert(a+' ok. '+b)
$('#results').html(b);
console.log(b);
}
});
});
});
</script>

Categories

Resources