Make Ajax Post when val on input changes and checkbox is checked - javascript

I have 3 input fields:
Title: <input type="text" value="Testa Ieraksts" id="blog_title"><br>
Check: <input type="checkbox" value="" id="blog_url_change"><br>
URL: <input type="text" value="" id="blog_slug" disabled="disabled"><br>
GOAL: When Checkbox is checked input#blog_slug is set to non-disabled, and then i want on input#blog_title changes send ajax post with var DATA.
jQuery(document).ready(function($){
$('input#blog_url_change').click(function(){
$('input#blog_slug').attr('disabled', !$(this).attr('checked'));
var STATUS = $('input#blog_url_change').prop('checked');
if (STATUS === true) {
$('input#blog_title').on('change', function() {
var DOMAIN = window.location.hostname;
var DATA = this.value;
$.ajax({
type: 'POST',
url: "http://" + DOMAIN + "/blog/helper/geturl",
data: 'data=' + DATA,
dataType: 'json',
success: function (response) {
console.log(response.url);
$('input#blog_slug').val(response.url);
},
}); // End Ajax
});
}
});
});
Problem: I need post only when checkbox is checked and title input val changes.
How to link these mothods together?

Thanks For #iCore ;)
$('input#blog_title').on('change', function() {
$('input#blog_url_change').click(function(){
$('input#blog_slug').attr('disabled', !$(this).attr('checked'));
var STATUS = $('input#blog_url_change').prop('checked');
console.log(STATUS);
if (STATUS === true) {
var DOMAIN = window.location.hostname;
var DATA = $('input#blog_title').val();
$.ajax({
type: 'POST',
url: "http://" + DOMAIN + "/blog/helper/geturl",
data: 'data=' + DATA,
dataType: 'json',
success: function (response) {
console.log(response.url);
$('input#blog_slug').val(response.url);
},
}); // End Ajax
}// End If
});
});

Related

Phonegap/Cordova - on("click") not firing

I'm creating a phonegap app.
This code is going to get by a json, the content on de database. Then I want to insert in the database the vote with the device.uuid. The problem is that the on("click") or on("touchstart") is not firing, not even in the alert(). Please help!!
$(document).ready(function() {
var url = "http://filmpix.esy.es/json.php";
$.getJSON(url, function(result) {
console.log(result);
$.each(result, function(i, field) {
var id = field.id;
$('.music-box').append("<button class='btn btn-default insert' value='" + id + "'>Votar</button>");
});
});
$(".insert").on("touchstart", function() {
alert("asdasd");
var music_id = $(this).val();
var dataString = "music_id=" + music_id;
$.ajax({
type: "POST",
url: "http://filmpix.esy.es/insert.php",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function() {
$("#insert").val('A votar...');
confirm("Tens a certeza que queres votar nesta musica?");
},
success: function(data) {
if (data == "success") {
alert("inserted");
$("#insert").val('Votado');
} else if (data == "error") {
alert("Não foi possível votar");
}
}
});
return false;
});
});
The return false statement should come after the function's "}" on your touch event.

Sending files with ajax not working as expected

I have a form which gets files along with other inputs , I want to pass those data to my ajax function. But when i check for those files in server , the server doesn't receive the file. I am new to ajax and Jquery. Here is what i have done.
<form id = "comp_inter_form">
<input type="radio" name="inter_fit" id="inter_good_fit" value = "good" >
<input type="radio" name="inter_fit" id="inter_bad_fit"
<input id="report_upload" type="file"/>
<input id="skype_upload" type="file"/>
<input id="audio_upload" type="file"/>
<input type = "submit" class = "update_interview_btn btn btn-primary" value = "Update"/>
</form>
Ajax function
function completeInterview(id,profile_id){
console.log("Candidate ID is : "+id+"\n Profile id is :"+profile_id );
$('#completeIntModal').modal('show');
var candidate_id = id;
var profile_id = profile_id;
var inter_fit,report_file,skype_file,audio_file;
$("#comp_inter_form").on('submit',function(){
var inter_fit = $("input[name=inter_fit]:checked").val();
var report_file = $("#report_upload").prop('files');
var skype_file = $("#skype_upload").prop('files');
var audio_file = $("#audio_upload").prop('files');
var dataString = 'inter_fit=' +inter_fit+ '&report_file=' +report_file+ '&skype_file=' +skype_file+ '&audio_file=' +audio_file+ '&candidate_id=' +candidate_id+ '&profile_id=' +profile_id;
$.ajax({
type: "POST",
url: "/complete_interview",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: dataString,
cache: false,
success: function(data) {
alert(data.msg);
},
error : function(xhr ,status ,error)
{
console.log(xhr);
alert(xhr);
}
});
});
Please try to make it like following and check if it works, As you are trying to post content VIA ajax with file input, it has to be treated separately.
You have to use FormData for this.
$("#comp_inter_form").on('submit',function(){
var inter_fit = $("input[name=inter_fit]:checked").val();
var report_file = $("#report_upload").prop('files');
var skype_file = $("#skype_upload").prop('files');
var audio_file = $("#audio_upload").prop('files');
var dataString = 'inter_fit=' +inter_fit+ '&report_file=' +report_file+ '&skype_file=' +skype_file+ '&audio_file=' +audio_file+ '&candidate_id=' +candidate_id+ '&profile_id=' +profile_id;
var formData = new FormData();
formData.append("inter_fit",inter_fit);
formData.append("candidate_id",candidate_id);
formData.append("profile_id",profile_id);
var fileInput = $("#report_upload").get(0);
formData.append("report_file",fileInput.files[0]);
fileInput = $("#skype_upload").get(0);
formData.append("skype_file",fileInput.files[0]);
fileInput = $("#audio_upload").get(0);
formData.append("audio_file",fileInput.files[0]);
$.ajax({
type: "POST",
url: "/complete_interview",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: formData,
contentType: false, // Not to set any content header
processData: false, // Not to process data
cache: false,
success: function(data) {
alert(data.msg);
},
error : function(xhr ,status ,error)
{
console.log(xhr);
alert(xhr);
}
});
On the server side you need to check for posted file array and process those accordingly.

Wordpress: Jquery submit event, page reloading instead of firing a document.location.href

So, I have a jQuery submit event handler, that on submit queries a database, and if no records are returned, prevents the form page from reloading, and if records were found, should then redirect the user to another page using document.location.href.
But what is actually happening is that records are being found, and instead of then redirecting the user to another page, the form page itself reloads.
What am I overlooking here?
jQuery('#MyForm').submit(function(e) {
console.log("getUserIDs is successfully hit.");
alert("The submit event has been hit");
var countryVal;
var cityVal;
var townVal;
var categoriesVal;
var serialized = jQuery('#MyForm').serialize();
var url = window.location.hostname;
countryVal = jQuery("#CountryList").val();
cityVal = jQuery("#CityList").val();
townVal = jQuery("#TownList").val();
if (typeof townVal == 'object') {
townVal = "object";
}
categoriesVal = jQuery("#CategoriesList").val();
jQuery.ajax({
cache: false,
type: "POST",
async: false,
url: gymRegions.ajaxurl,
data: {
action: "showcountries",
makeselection: "getUserIDs",
countryID: countryVal,
cityID: cityVal,
townID: townVal,
categoriesID: categoriesVal,
locationHref: url,
serialized
},
dataType: "json",
success: function(data) {
alert("Success of the submit event has been hit.");
localStorage.setItem('dataObjectTemp2', JSON.stringify(data));
var numericRecCount = parseInt(data.c);
jQuery.post('', function(data) {
document.location.href = window.location.hostname + '/index.php/anotherpage/';
});
},
error: function(data, status, error) {
alert("No records were returned for your search. Please make another selection.");
e.preventDefault();
return false;
console.log(data);
console.log(status);
console.log(error);
}
});
});
<form id="MyForm" method="Post">
<input type="submit" name="fl-button" id="fl-button" role="button" value="SEARCH" class="fl-button" disabled="disabled" value="Send" />
</form>
jQuery('#MyForm').submit(function (e) {
e.preventDefault();
var countryVal;
var cityVal;
var townVal;
var categoriesVal;
var serialized = jQuery('#MyForm').serialize();
var url = window.location.hostname;
countryVal = jQuery("#CountryList").val();
cityVal = jQuery("#CityList").val();
townVal = jQuery("#TownList").val();
if (typeof townVal == 'object') {
townVal = "object";
}
categoriesVal = jQuery("#CategoriesList").val();
jQuery.ajax({
cache: false,
type: "POST",
async: false,
url: gymRegions.ajaxurl,
data: serialized + '&action=showcountries&makeselection=getUserIDs&countryID=' +
countryVal + '&cityID=' + cityVal + '&townID=' + townVal + '&categoriesID=' +
categoriesVal + '&locationHref=' + url,
dataType: "json",
success: function (data) {
alert("Success!");
localStorage.setItem('dataObjectTemp2', JSON.stringify(data));
var numericRecCount = parseInt(data.c);
window.location.href = url + '/index.php/anotherpage/';
},
error: function (data, status, error) {
alert("No records were returned for your search. Please make another selection.");
}
});
return false;
});
jQuery('#MyForm').submit(function (e) {
e.preventDefault(); //use prevent default here
console.log("getUserIDs is successfully hit.");
alert("The submit event has been hit");
var countryVal;
var cityVal;
var townVal;
var categoriesVal;
var serialized = jQuery('#MyForm').serialize();
var url = window.location.hostname;
countryVal = jQuery("#CountryList").val();
cityVal = jQuery("#CityList").val();
townVal = jQuery("#TownList").val();
if (typeof townVal == 'object'){
townVal = "object";
}
categoriesVal = jQuery("#CategoriesList").val();
jQuery.ajax({
cache: false,
type: "POST",
async: false,
url: gymRegions.ajaxurl,
data:{action: "showcountries",
makeselection: "getUserIDs",
countryID: countryVal,
cityID: cityVal,
townID: townVal,
categoriesID: categoriesVal,
locationHref: url,
serialized},
dataType: "json",
success: function (data) {
alert("Success of the submit event has been hit.");
localStorage.setItem('dataObjectTemp2', JSON.stringify(data));
var numericRecCount = parseInt(data.c);
document.location.href = window.location.hostname + '/index.php/anotherpage/';
},
error: function (data, status, error) {
alert("No records were returned for your search. Please make another selection.");
console.log(data);
console.log(status);
console.log(error);
}
});
});

Check the value of a text input field with ajax

I have a website where the log ins are screen names. On the create user form I want to be able to have ajax check if a screen name exists already as it is typed into the form.
This is the HTML form input field
<label for="screenName">Screen Name:
<input type="text" class="form-control" name="screenName" id="screenName" size="28" required>
<div class="screenNameError"></div>
A message should be displayed in the <div class="screenNameError"></div>line if the username matches the database.
This is my Jquery code for this.
$(document).ready(function(){
if ($('#screenName').length > 0){
var screenName = $("input").keyup(function(){
var value = $(this).val();
return value;
})
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + screenName,
success: function (r) {
$('.screenNameError').html(r);
}
})
}
});
This is the PHP file that gets called to make the DB query
$screenName = $_POST['Screen_Name'];
$screenNameSQL = "SELECT Screen_Name FROM Users WHERE Screen_Name = '$screenName'";
$result = $my_dbhandle->query($screenNameSQL); //Query database
$numResults = $result->num_rows; //Count number of results
$resultCount = intval($numResults);
if($resultCount > 0){
echo "The username entered already exists. Please a different user name.";
}
For some reason my Jquery is not firing when I type the username in the form :/
Thanks in advance
Try changing your jQuery to this -
$(document).ready(function() {
$('#screenName').keyup(function() {
var value = $(this).val();
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + value,
success: function(r) {
$('.screenNameError').html(r);
}
});
});
});
However you probably want to minimise the number of ajax requests being made so I would advise putting your ajax request into a setTimeout functon and clearing it with each subsequent keypress. -
$(document).ready(function() {
var ajaxRequest;
$('#screenName').keyup(function() {
var value = $(this).val();
clearTimeout(ajaxRequest);
ajaxRequest = setTimeout(function(sn) {
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + value,
success: function(r) {
$('.screenNameError').html(r);
}
});
}, 500, value);
});
});
if ($('#screenName').length > 0){
You should change it with
if ($('#screenName').val().length > 0){
OR
var name = $('#screenName').val();
if(name.length >0) {...
not sure about the syntax...
Add an event on keyup like this :
Edit
$("#screenName").on("keyup",function(){
var screenName=$(this).val();
if(screenName!='')
{
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + screenName,
success: function (r) {
$('.screenNameError').html(r);
}
})
}
});
JsFiddle
Your ajax call should be inside the keyup handler.

Jquery insert error message returned by PHP via Json

I'm trying to submit a form via AJAX.I send my form to PHP which return error messages if there are via Json.
If there are no error, the code work well. But if not... I cannot insert error message. I don't understand why.
Here is what I would like to do :
function addWishlist(){
var formdata = $("#addwishlist").serializeArray();
$.ajax({
url: "/Shawili/<?= $profile['username'] ?>/addwishlist/",
data: formdata,
type: 'POST',
dataType: 'json',
success: function(json){
if(json.valid == 'ok') {
$('#addwishlist').each(function(){
this.reset();
});
} else {
$.each( json, function( key, value ) {
$('#'+key).before('<div class="row"><div class="col-sm-offset-2 col-sm-5"><span class="label label-danger">' + value + '</span></div></div>');
});
}
}
});
}
This code is working :
function addWishlist(){
var formdata = $("#addwishlist").serializeArray();
$.ajax({
url: "/Shawili/<?= $profile['username'] ?>/addwishlist/",
data: formdata,
type: 'POST',
dataType: 'json',
success: function(json){
if(json.valid == 'ok') {
$('#addwishlist').each(function(){
this.reset();
});
} else {
$.each( json, function( key, value ) {
alert(key +':'+ value);
});
}
}
});
}
This code is'nt :
function addWishlist(){
var formdata = $("#addwishlist").serializeArray();
$.ajax({
url: "/Shawili/<?= $profile['username'] ?>/addwishlist/",
data: formdata,
type: 'POST',
dataType: 'json',
success: function(json){
if(json.valid == 'ok') {
$('#addwishlist').each(function(){
this.reset();
});
} else {
$('#title').html('<p>test</p>')
}
}
});
}
The html form is shown via AJAX because I'm using a tabs system. (Each tab is loaded via AJAX when user click on it) The JS script is located at the end of the layout.
Here is a part of the form :
<div id="title" class="form-group"><label class="col-sm-2 control-label" for="title">Title</label>
<div class="col-sm-4">
<input type="text" placeholder="" name="title" class="form-control"></div></div>
However, when I use Firebug I can see the changes in the html structure but nothing appends in the page.
Here is my tab loading function :
$('#myTabs a').click(function (e) {
e.preventDefault();
var url = $(this).attr("data-url");
var href = this.hash;
var pane = $(this);
// ajax load from data-url
$(href).load(url,function(result){
pane.tab('show');
});
});
And here is Firebug screenshot :
Try to bind first in another not DOM element, something like this:
$('#otherDivContent').find('#title').html('<p>test</p>');
Where #otherDivContent is a div(or other element) that you have initially on your page.

Categories

Resources