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);
}
})
}
....
}
Related
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>
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');?>";
}
here's my code.
In my .js file:
function Sendit()
{
bValidate = validateField();
if(bValidate)
{
var title = $("#title").val();
theUrl = 'index.php';
params = '';
params += 'action=Send';
params += '&title='+title;
$.ajax ({
url: theUrl,
data: params,
async:true,
success: function (data, textStatus)
{
//do smth
alert('went well');
}
,
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
}
}
function validateField()
{
var title = document.getElementById('title').value;
if(!title.match(/\S/))
{
//do some alerting
return false;
}
else
{
return true;
}
}
And in my index.php file:
<form action="" method="post" name="myform" id="myform"" >
Title: <input class="" type="text" name="title" value="" id="title"/> <br>
<input type="submit" value="Submit" onClick="javascript:Sendit();return false; ">
</form>
<?php
if ($_REQUEST["action"]=='Send')
{
$title = $_REQUEST["title"];
$sql = "INSERT INTO ...
$retval = $mysqli->query($sql, $conn);
if(! $retval ) {
echo('Could not enter data insert: ' . mysql_error());
}
else
{
//inform that everything went well
}
?>
This does not send a thing when the sunmit button is clicked. In fact, you can click the button until the end of the day that nothing happens (not even a message in the debugger)
If I delete the return false; from the onClick in the button, I click on the button and the page reloads even without filling in the title input which has to be filled in.
Ajax's success does not alert a thing and in both cases, nothing gets inserted in my database.
The insert query is correct, I've checked it.
Any ideas on how to send the data and validate?
Thanks
Use below Code to send req.
function Sendit()
{
bValidate = validateField();
if(bValidate)
{
var title = $("#title").val();
theUrl = 'index.php';
params = {};
params["action"] = 'Send';
params["title"] = title;
$.ajax ({
url: theUrl,
data: params,
async:true,
success: function (data, textStatus)
{
//do smth
alert('went well');
}
,
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
}
}
your validateField() function never returns true, so your if(bValidate) will never run. Javascript functions return undefined unless you explicitly return something, try this:
function validateField()
{
var title = document.getElementById('title').value;
if(!title.match(/\S/))
{
//do some alerting
return false;
} esle {
return true;
}
}
I have an AJAX function that works just fine when I'm on my PC. But when I switch to Safari (mobile), only the radio-boxes will trigger the AJAX. How come?
HTML:
<input type="radio" id="q1r1" name="q1" value="Awesome" onchange="GrabData(this)">
<input type="radio" id="q1r3" name="q1" value="Awful" onchange="GrabData(this)">
<div class="comment"><textarea name='q1comment' id='comment' maxlength="400" placeholder="Add a comment (max 400 characters)" onchange="GrabC(this)"></textarea>
AJAX
//AJAX question 1.
function GrabData(Passeddata){
var radioValue = Passeddata.value;
var URL = "question1.php?q1=" + radioValue + "&teamid=" + <?php echo $teamid; ?>;
$.ajax( {
url : URL,
type : "GET",
dataType: 'json',
success : function(data) {
if (data == "") {
alert("data is empty");
} else {
console.log('got your data back sir');
}
}
});
};
//AJAX for comment question 1.
function GrabC(PassedComment){
var radioValue = PassedComment.value;
var URL = "question1.php?comment1=" + radioValue + "&teamid=" + <?php echo $teamid; ?>;
$.ajax( {
url : URL,
type : "GET",
dataType: 'json',
success : function(data) {
if (data == "") {
alert("data is empty");
} else {
console.log('got your data back sir');
}
}
});
};
Again, works fine on my PC, the textarea onchange does not seems to work on Safari on the mobile. Can't figure out why!
Try keyup event along with change; change triggers when you blur, focus (not sure of this) on the element, but keyup actually listens for changes while the user is typing/tapping the keys.
$('input[type="text"]').on('change keyup', function(){
$('#console').text($('#console').text()+ "\r\n"+ this.value);
});
$('textarea').on('change keyup', function(){
$('#console').text($('#console').text()+ "\r\n"+ this.value);
/** Send to AJAX
GrabC(this);
GrabData(this);
**/
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text"/>
<textarea row="4"></textarea>
<pre id="console"></pre>
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>