Onchange AJAX for textarea not working in Safari - javascript

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>

Related

Maintain the state of checkbox on page Load in MVC

My issue is related to Page load.
I have the following code:
Controller:
public ActionResult Index()
{
BD.isEmailON_OFF= db.Email_ON_OFF_T.Select(x=>x.isEmailON_OFF).FirstOrDefault().GetValueOrDefault();
}
[HttpPost]
public ActionResult CheckEmail(string checkemails)
{
//calling Stored Procedure
if (!string.IsNullOrWhiteSpace(checkemails)|| checkemails=="true" || checkemails=="false")
{
var checkemails1 = new SqlParameter("checkemails", checkemails);
db.Database
.ExecuteSqlCommand("EXEC Sp_Email_on_off #checkemails", checkemails1);
}
return new JsonResult { };
}
I have table IS_Email_on_OFF_T:
I inserted to isemailonoff column as 0
Functionality:
I have turned on the email button and checkbox.
turn on email----->becomes turn off button and checkbox checked.
turn off button----> becomes turn on button and checkbox unchecked.
worked correctly till here.
turn on email----->becomes turn off button and checkbox checked.
page load(loading the page)
clicking on turn off button and not changing to turn on the button(1st attempt)(ISSUE)
clicking on turn off button(2nd tym) and it changes.
What I have tried is:
Views:
#{
if (Model.isEmailON_OFF == 0)
{
<input type="button" value="Turn Email on" class="btn btn-success" id="btnturnemailonoff" />
<input type="checkbox" id="Chkemailonoff" style="float:right;" />
}
else
{
<input type="button" value="Turn Email off" class="btn btn-success" id="btnturnemailonoff" />
<input type="checkbox" id="Chkemailonoff" style="float:right;" checked/>
}
}
AJAX call on button click:
<script type="text/javascript">
$(document).ready(function () {
$('#btnturnemailonoff').on('click', function () {
var checked = !$(this).data('checked');
var message = checked ? 'Turn Email ON' : 'Turn Email OFF';
if (confirm("Do you want to " + message + "? ")) {
$("#Chkemailonoff").prop('checked', checked);
$(this).val(checked ? 'Turn Email Off' : 'Turn Email on')
$(this).data('checked', checked);
debugger;
var url = '#Url.Action("CheckEmail", "BillingDetails")';
$.ajax({
url: url,
type: "POST",
data: { checkemails: checked },
dataType: "json",
// traditional: true,
success: function () {
alert("ajax request to server succeed");
}
});
}//end of if
});
});
</script>
SP:
ALTER procedure [dbo].[Sp_Email_on_off]
#checkemails varchar(10)
As
Begin
if(#checkemails='false')
Update Email_ON_OFF_T set isEmailON_OFF=0
else
Update Email_ON_OFF_T set isEmailON_OFF=1
End
I made changes in AJAX call button click and it worked for me.
$(document).ready(function () {
$('#btnturnemailonoff').on('click', function () {
debugger;
var checked = $("#Chkemailonoff").prop('checked');
var message = checked ? 'Turn Email On' : 'Turn Email Off';
if (confirm("Do you want to " + message + "? ")) {
$("#Chkemailonoff").prop('checked', !checked);
$(this).val(message)
var url = '#Url.Action("CheckEmail", "BillingDetails")';
$.ajax({
url: url,
type: "POST",
data: { checkemails: !checked },
dataType: "json",
success: function () {
//alert("ajax request to server succeed");
}
});
}
});
});

Form/button stop work after ajax partly reload page after form success

(If my english is bad I'm from pewdiepieland)
I have a problem that itch the hell out of me.
I have a page with a picture gallery. When logged in every picture gets a form where you can change the description or delete the picture. I also have a form where you can add a new picture to the gallery.
If I add a picture or delete/edit an existing one the part of the page where all of the pictures are shown reloads so that the new content is loaded. (since I don't want the whole page to reload and also wants to show a message about what happened, eg. "The picture was successfully uploaded/changed/deleted").
The problem is that the forms inside of the part which were reloaded stops working. I need to reload the whole page if I want to delete or edit another image. (The form for submitting a new picture still works, since it's outside of the "reloaded part of the page")
Do I have to reload the javascriptfile or anything else, or what do I need to do?
Do you guys need some parts of the code to check? It feels like I need to add something to my code to prevent this instead of changing the existing.. but hey what do I know...
Best Wishes and Merry Christmas!
UPDATE << with Simplyfied code:
HTML/PHP
<form id="addimg" role="form" method="POST" enctype="multipart/form-data">
<input type="file" name="img">
<input type="text" name="imgtxt">
<input type="submit" name="gallery-submit" value="Add Image">
</form>
<div id="gallery_content">
<?php
$result = mysqli_query($link, "SELECT * FROM gallery");
$count = 1;
while($row = mysqli_fetch_array($result)) {
$filename = $row['filename'];
$imgtxt = $row['imgtxt'];
$id = $row['id'];
echo '<div>';
echo '<img src="gallery/' . $filename . '">';
echo '<form id="editimg' . $count . '" role="form" method="POST">';
echo '<input type="text" name="imgtxt">';
echo '<input type="hidden" name="id">';
echo '<input type="submit" name="changeimgtxt" data-number="' . $count . '" value="Update" class="edit_img">';
echo '</form>';
echo '<button class="delete_img" value="' . $id . '">Delete</button>';
echo '</div>;
}
?>
</div>
JAVASCRIPT/JQUERY
$(document).ready(function() {
$('#addimg').submit(function(e) {
e.preventDefault();
gallery('add', '');
});
$('.edit_img').click(function(e) {
e.precentDefault();
var formNr = $(this).data('number');
var dataString = $('#editimg' + formNr).serialize();
gallery('edit', dataString)
});
$('.delete_img').click(function(e) {
e.preventDefault();
var imgid = $('this').value();
gallery('delete', imgid);
});
function gallery(a, b) {
if (a == 'add') {
var dataString = new FormData($('#addimg')[0]);
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'add_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content');
} else {
- Show fail message -
}
},
cache: false,
contentType: false,
processData: false
});
} else if (a == 'edit') {
var dataString = b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'edit_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content');
} else {
- Show fail message -
}
}
});
} else if (a == 'delete') {
var dataString = 'imgid=' + b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'delete_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content');
} else {
- Show fail message -
}
}
});
}
}
});
I don't think you need to see my process-file. Any clues?
Your problem is probably the .click function on add and delete image so change it to $('body').on('click', 'delete_img', function() {// do something});
See Here
Your problem is that you only hook up the .click() listeners once on "document ready".
When the $(document).ready() callback is executed the gallery has already been filled and you hook up click listeners on the elements that are currently in the DOM. When you reload the gallery it is no longer the same DOM elements and no click listeners are being set up on these ones. There are a multitude of ways you correct this, for example, jQuery .load() takes a complete callback in which you can set up the event listeners. Your sample adapted with this:
$(document).ready(function() {
var setupGalleryEventListeners = function () {
$('.edit_img').click(function(e) {
e.preventDefault();
var formNr = $(this).data('number');
var dataString = $('#editimg' + formNr).serialize();
gallery('edit', dataString)
});
$('.delete_img').click(function(e) {
e.preventDefault();
var imgid = $('this').value();
gallery('delete', imgid);
});
};
$('#addimg').submit(function(e) {
e.preventDefault();
gallery('add', '');
});
setupGalleryEventListeners(); // Setup initial event listeners on page load
function gallery(a, b) {
if (a == 'add') {
var dataString = new FormData($('#addimg')[0]);
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'add_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content', setupGalleryEventListeners); // setupGalleryEventListeners called when load is done
} else {
- Show fail message -
}
},
cache: false,
contentType: false,
processData: false
});
} else if (a == 'edit') {
var dataString = b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'edit_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content', setupGalleryEventListeners); // setupGalleryEventListeners called when load is done
} else {
- Show fail message -
}
}
});
} else if (a == 'delete') {
var dataString = 'imgid=' + b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'delete_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content', setupGalleryEventListeners); // setupGalleryEventListeners called when load is done
} else {
- Show fail message -
}
}
});
}
}
});

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);
}
})
}
....
}

textarea update not working with ajax submit

I have a textarea field where some data already exist
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="message" id="editor1">There is some lines with basic html tags like strong,underline</textarea>
If I change above to like this
<textarea name="message" id="editor1">Some new lines with basic html tags like strong,underline</textarea>
But after submit action Everything works fine but I always get old textarea data not new updated data.
While js code
$(document).on('click', ".send-mail", function (e) {
e.preventDefault();
var s_message=$("textarea[name=message]").val();
$('#send_mail').modal({backdrop: 'static', keyboard: false}).one('click', '#sendmail', function () {
sendMail(s_message);
});
});
function sendMail(s_message) {
jQuery.ajax({
url: 'request/sendmail.php',
type: 'POST',
data: s_message,
dataType: 'json',
success: function (data) {
if (data.status == "Success") {
$("#notify .message").html("<strong>" + data.status + "</strong>: " + data.message);
$("#notify").removeClass("alert-danger").addClass("alert-success").fadeIn();
$("html, body").scrollTop($("body").offset().top);
} else {
$("#notify .message").html("<strong>" + data.status + "</strong>: " + data.message);
$("#notify").removeClass("alert-success").addClass("alert-danger").fadeIn();
$("html, body").scrollTop($("body").offset().top);
}
}
});
}
</script>
I need new updated data to a PHP Post variable. Why it is not working?

Why doesn't jquery submit work properly?

This code works fine in its current state where im using a click event on a button. But if i use a form tag around the input tags in my html code and use jquery's submit method it doesnt give any results. why is that happening? i have to use the form element because i want to be able to search with an enter key insted of clicking on a button
Html:
<body>
Title: <input type="text" id="title"><br/>
<input type="submit" value="Submit" id="btn">
<p id="results"></p>
<body>
jQuery:
$(document).ready(function(){
$("#btn").on("click", function(){
var textval = $('#title').val();
var playListURL = 'https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=' + textval + '&format=json&callback=?';
$.ajax({
type: "GET",
url: playListURL,
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data, textStatus, jqXHR) {
for (var i = 0; i < 10; i++)
{
var url = "https://en.wikipedia.org/wiki/" + data.query.search[i].title;
$("#results").append("<b> <a href='" + url + "' > " + data.query.search[i].title + "</a></b></br> ");
//console.log(url);
}
},
error: function (errorMessage) {
}
});
//alert($('#title').val());
});
});
Try to change this line
$("#btn").on("click", function(){
to this:
$("#btn").on("click", function(e){
e.preventDefault();
Then the form will not submit default way on click

Categories

Resources