JQuery Ajax does not response to Node JS - javascript

I have the following form (in the client side):
<html>
<body>
<script>
$(document).ready(function() {
$.ajax({
url: "Search.html",
type: "POST",
dataType : "json",
success: function (result) {
console.log(result);
if(result.status == 200 && result.validationFailed ){
alert(result.message);
}
},
error: function(result){
console.log(result);
if(error.responseText == 'showAlert'){
alert( "Sorry, there was a problem!" );
}
}
})
});
}
</script>
<form action="/process_post" method="POST">
<select name="SearchTypes">
<option value="Author" selected>Author</option>
<option value="Mention">Mention</option>
<option value="Tag">Tag</option>
</select>
<input type="text" name="term">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
In the server side, I am using Node JS to validate data against the database and reply back to the client. I have one case where there is no data in the database and I want to tell the user using Ajax data are not available:
var query = connection.query(queryString, [term,term], function(err, rows) {
var res1 = {};
console.log(rows);
var tweet = JSON.parse(JSON.stringify(rows));
if (tweet.length == 0){
res1.status = 200;
res1.validationFailed = true;
res1.message = 'Empty data';
res.send(JSON.stringify(res1));
}else{
for(var i in tweet){
res.write("Author: ");
......
When I run the code, I do not get an alert. I actually get the following:
{"status":500,"validationFailed":true,"message":"Empty data"}
Can you please help me with this

You forgot to set the data in $.ajax.

Related

Pushing array of values from a form into Google Spreadsheet comes through as 'undefined'

I have a form with text fields which the user can "Add New" by clicking a button. These fields share the same name. I'm trying pass the values into Google Spreadsheets, but the values all come through as 'undefined' with the following code, even though console.log prints the answers as strings which look okay to me.
So if the user for example submits 3 separate entries for SUNDAY_NOTES[], all 3 strings should end up in one cell broken up by new lines, but instead I'm just getting "undefined".
<form action="" method="post" id="timesheet">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]"> // the user can create multiples of these ^ for each day of the week
<input type="submit" id="submit" />
</form>
<script>
$(document).ready(function() {
var $form = $('form#timesheet'),
url = 'https://script.google.com/macros/s/AKf45XRaA/exec'
$('#submit').on('click', function(e) {
e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: $form.serializeArray().map((e) => {
return e.value
}).join('\n')
});
})
});
</script>
Your code works. In the snippet below I am storing the data split by \n in a variable and logging it. You can check the output.
Although your JS is correct, I suspect that you actually want to be using a different HTTP method. Perhaps POST or PUT? I can't be specific as you have not said which API endpoint you are using.
$(document).ready(function() {
var $form = $('form#timesheet'),
url = 'https://script.google.com/macros/s/AKf45XRaA/exec'
$('#submit').on('click', function(e) {
e.preventDefault();
var data = $form.serializeArray().map((e) => {
return e.value
}).join('\n');
console.log(data);
var jqxhr = $.ajax({
url: url,
method: "POST",
dataType: "json",
data: data
}).done(response => {
console.log(response);
}).fail((jqXHR, textStatus) => {
console.log("Request failed: " + textStatus);
});
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" id="timesheet">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]">
<input type="submit" id="submit" />
</form>
remove the [] from your input's name as this is needed if you want to receive an array in the server side, then create a function that groups the values according to the inouts' keys :
function group(arr) {
var tempArr = [];
arr.forEach(function(e) {
var tempObj = tempArr.find(function(a) { return a.name == e.name });
if (!tempObj)
tempArr.push(e)
else
tempArr[tempArr.indexOf(tempObj)].value += ', ' + e.value;
});
return tempArr;
}
and use it like :
$('#submit').on('click', function(e) {
e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: group($form.serializeArray()),
//... rest of your code
this will keep the original structure that works,
here's a snippet :
var $form = $('form#timesheet');
function group(arr) {
var tempArr = [];
arr.forEach(function(e) {
var tempObj = tempArr.find(function(a) { return a.name == e.name });
if (!tempObj)
tempArr.push(e)
else
tempArr[tempArr.indexOf(tempObj)].value += ', ' + e.value;
});
return tempArr;
}
$form.submit(function(e) {
e.preventDefault();
var grouped = group($form.serializeArray());
console.log(JSON.stringify(grouped))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="timesheet">
<input type="text" name="SUNDAY_NOTES"><br />
<input type="text" name="SUNDAY_NOTES"> // user can click a button to keep adding more SUNDAY_NOTES fields
<input type="text" name="MONDAY_NOTES"> // and so forth
<input type="submit" id="submit" />
</form>

call ajax when checkbox is checked after submission javascript/php

I have four files like this. The user click on a submit button in file interactive-map.php. The data then pass to statesearch.php with a javascript file overview.js and overview-statistic.js. Then I want to be able to click on the checkbox, which will invoke a construtor that will make an ajax call. The problem starts at file overview.js saying that I got an error after the call status 0. I know that means the page refreshes after ajax call. I look at other solution How to stop refreshing page after ajax call? but the problem does not go away after doing event.preventDefault(). I don't understand why.
interactive-map.php
<form action="statesearch.php" class="post" id="post" method="get">
<input class="stateAttr" name="stateAttr" type="hidden" value=data[stateAttr]>
<input class="counties" name="counties"type="hidden" value=data[county]>
<input class="river" name="rivers" type="hidden" value=data[river]>
<input class="city" name="cities" type="hidden" value=data[city]>
<input id="submit" type="submit">
</form>
statesearch.php
<script src="overview.js"></script>
<script src='overview-statistic.js'></script>
...
<?php
if (isset($_GET["data"])) {
$stateAttr = str_replace("\"", "" ,$_GET["data"]["stateAttr"]);
$cities = str_replace("\"", "" , $_GET["data"]["cities"]);
$counties = str_replace("\"", "" , $_GET["data"]["counties"]);
$rivers = str_replace("\"", "", $_GET["data"]["rivers"]);
}
....
<div class='cities-display'>
<p><label><input class='city-checkbox0' type='checkbox'</label>city1</p>
<p><label><input class='city-checkbox1' type='checkbox'</label>city2</p>
<p><label><input class='city-checkbox2' type='checkbox'</label>city3</p>
...
</div>
?>
overview.js
$(document).ready(function () {
$(".cities-display input[type=checkbox]").on("change", function (event) {
if (this.checked) {
city = $(this).closest("p").text();
address = city + ', USA';
var graphDemo = new GetStat(city); //<-- Problem here. Call from overview-statistic.js
...
}
else {
deleteMark($(this).closest("div").index()); // Call from map-animate.js
}
});
}
overview-statistic.js
function GetStat(input) {
...
this.input = input;
this.getEntity();
}
GetStat.prototype = {
getEntity: function () {
var self = this;
// Look up entity
$.ajax({
url: "https://api.opendatanetwork.com/entity/v1?entity_name="+this.input+", CA&entity_type=region.place&app_token="+this.apiKey,
type: "GET",
success: function (data) {
var entity_id = data["entities"][0]["id"].toString();
self.entity = entity_id;
self.getDemo(entity_id);
self.getEdu(entity_id);
self.getJob(entity_id);
},
error: function(xhr) {
var response = xhr.responseText;
console.log(response);
var statusMessage = xhr.status + ' ' + xhr.statusText;
var message = 'Query failed, php script returned this status: ';
var message = message + statusMessage + ' response: ' + response;
alert(message);
}
})
}
....
}

JQuery Display Alert Message on Form Submit

I am trying to display alert messages on jquery from the client side. The jquery will be called once the submit button is clicked. The form then will call the server side php. Here is my code:
FORM
<form action="branch_add_verifier.php" method="POST" id="formAdd">
<input type="text" name="id" id="id">
<input type="submit" value="submit">
</form>
JQUERY
$(document).ready(function(){
var $form = $('#formAdd');
$form.submit(function(){
var id= $("#id").val();
if (id.length < 12) {
alert("INPUT ERROR");
return false;
}
$.post($form.attr('action'), $(this).serialize(), function(response){
alert("DATA SUCCESSFULLY ADDED");
},'json');
return false;
});
});
But the alert message does not pop up inside the $.postmethod
And I also want to know how I can pop up the alert message from the server side. Here is my sample code:
SERVER SIDE
<?php $query = mysqli_query($conn, "SELECT * FROM table1
INNER JOIN table2
ON table1.col1= table2.col1
WHERE table2.col3= '".$_REQUEST['id']."'");
if (mysqli_num_rows($query) != 0) {
echo "<script>alert('ERROR')</script>";
return false;
} ?>
In summary, the code above works but I need to display messages that would tell me if the query is successful or not. Thanks
My new problem is that the code below bring me to another page:
FORM
<form action="branch_add_verifier.php" method="POST" id="formAdd">
<input type="text" name="id" id="id">
<input type="submit" value="submit">
</form>
JQUERY
$(document).ready(function(){
$('#formAdd').on('submit', function (e) {
e.preventDefault();
var id= $("#id").val();
if (id.length < 12) {
alert("INPUT ERROR");
return false;
}
$.ajax({
context: this,
url: $(this).attr('action'),
type: 'POST',
data: new FormData(this),
dataType: 'json'
}).done(function (data) {
if(data == 'ok') {
alert("DATA SUCCESSFULLY ADDED");
}
if(data == 'no') {
alert("ERROR");
}
}).fail(function (data) {
console.log('failed');
});
});
});
SERVER
$query = mysqli_query($conn, "SELECT * FROM table1
INNER JOIN table2
ON table1.col1= table2.col1
WHERE table2.col3= '".$_REQUEST['id']."'");
if (mysqli_num_rows($query) != 0) {
mysqli_close($conn);
echo json_encode('no');
return false;
}
I need to return after the json_encode because there are still methods below that.
HTML Form
<form action="branch_add_verifier.php" method="POST" id="formAdd">
<input type="text" name="id" id="id">
<input type="submit" value="submit">
</form>
Script :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(function() {
$(document).on('submit', "#formAdd", function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
type: "post",
data: $(this).serialize(),
error:function(){
alert("ERROR : CANNOT CONNECT TO SERVER");
},
success: function(data) {
alert(data);
}
});
return false;
});
});
</script>
PHP server side like this:
<?php
$insert = mysqli_query($conn, "insert query here");
if($insert) {
echo json_encode('ok');
} else {
echo json_encode('no');
}
?>
Just you need to put id="id" in input type text.
<input type="text" name="id">
Working Code
$(document).ready(function(){
var $form = $('#formAdd');
$form.submit(function(){
var id= $("#id").val();
if (id.length < 12) {
alert("INPUT ERROR");
return false;
}
$.post($form.attr('action'), $(this).serialize(), function(response){
alert("DATA SUCCESSFULLY ADDED");
},'json');
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="branch_add_verifier.php" method="POST" id="formAdd">
<input type="text" id="id" name="id">
<input type="submit" value="submit">
</form>

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