I am using the following code for sending ajax request but the request is not being sent. Can anyone help me to find the problem?
$("input.ub").click(function () {
console.log("I am here");
var id = $(this).attr('id');
var pid = "p" + id.substring(1, 2);
var text = $("#" + pid).text();
$("#" + pid).html('<input type="text" id="up" value="' + text + '" /><input type="button" id="req" value="Submit" />');
//Ajax request to be sent
$("#req").one("click", function () {
//var action = $("#postform").attr('action');
console.log("I am Second");
var form_data1 = {
post: $("#up").val(),
is_ajax: 1,
update: parseInt(id.substring(1, 2))
};
console.log($("#up").val());
$.ajax({
type: "POST",
url: "updatePosts.php",
data: form_data1,
success: function (response) {
if (response == "success") {
console.log("Succes MEssage");
$(location).attr('href', 'viewPosts.php');
} else console.log("You are failed here instead");
}
});
console.log("Request not sent");
return false;
});
I am getting the failure console messages. But i don't see any problem in the code.
You're returning "request not sent" even when it is successful. You need to use the error setting in your AJAX call.
http://api.jquery.com/jquery.ajax/
It looks like you may have forgotten a bracket after else...
$("input.ub").click(function(){
console.log("I am here");
var id = $(this).attr('id');
var pid="p"+id.substring(1,2);
var text=$("#"+pid).text();
$("#"+pid).html('<input type="text" id="up" value="'+text+'" /><input type="button" id="req" value="Submit" />');
//Ajax request to be sent
$("#req").one("click",function(){
//var action = $("#postform").attr('action');
console.log("I am Second");
var form_data1 = {
post: $("#up").val(),
is_ajax: 1,
update:parseInt(id.substring(1,2))
};
console.log($("#up").val());
$.ajax({
type: "POST",
url: "updatePosts.php",
data: form_data1,
success: function(response){
if(response == "success"){
console.log("Succes MEssage");
$(location).attr('href','viewPosts.php');
}
else { <=====HERE
console.log("You are failed here instead");
}
});
console.log("Request not sent");
return false;
});
Related
Upon ajax successful return, the return data contains status. if status is false(not ajax fail), return data contains array of element names and associated error message. The goal is to replicate .validate() error functionality by appending msg after element and highlight.
HTML form:
<form class="form-horizontal" id="chngPwdForm" action="changepwd.php" method="post">
.
. various HTML....
.
<div class="form-group">
<div class="alert alert-div font-weight-bold" id="errorTxt" role="alert" style="display:none;"> </div>
<label for="crntPwd">Existing Password:</label>
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-key fa-fw"></i></span>
<input type="password" class="form-control" id="crntPwd" name="crntPwd" required>
</div>
</div>
.
. more HTML follows
.
JQUERY:
.
.yada, yada, yada
.
$("#chngPwdForm").submit(function(event){
event.preventDefault();
if ($("#chngPwdForm").valid() ) {
$('#chngPwdForm div[id="errorTxt"]').hide();
Msg = $('#chngPwdForm div[id="errorTxt"]').text("Password changed. Click on Login to continue.");
var formURL = $("#chngPwdForm").attr('action');
$.ajax({
url: formURL,
type: 'POST',
data: $(this).serialize(),
dataType: 'JSON'
})
.done (function(data, textStatus, jqXHR) {
if (!data.status) {
var Msg = "Password Not Changed. Password Change Failed.";
var element;
var errorObj = new Error("");
$.each(data.Msg, function(elemName, errMsg) {
element = $("#chngPwdForm").filter("#" + elemName);
errorObj.message = errMsg;
$(element).closest(".form-group").addClass("has-error");
errorObj.insertAfter(element);
});
}
$('#chngPwdForm div[id="errorTxt"]').text(Msg).show();
})
.fail (function(response){
var Msg = "chngPwd call failed. errorThrown: " + response;
var obj = JSON.stringify(response);
alert("obj is: " + obj);
$('#chngPwdForm div[id="errorTxt"]').text(Msg);
})
}
else {
$('#chngPwdForm div[id="errorTxt"]').text('Please Correct errors').show();
}
return false;
The JSON response from changepwd.php:
{\"status\":false,\"Msg\":{\"crntPwd\":\"Current Password may only contain a-z, A-Z, 0-9, ! or #\"}
JS error
"TypeError: errorObj.insertAfter is not a function" is thrown for
"errorObj.insertAfter(element);"
The implemented solution:
JQuery:
// New Code has leading and trailing *
$("#chngPwdForm").submit(function(event){
*$(".chngPwderr").removeClass("error").text('');* //used to remove old messages
event.preventDefault();
if ($("#chngPwdForm").valid() ) {
$('#chngPwdForm div[id="errorTxt"]').hide();
Msg = $('#chngPwdForm div[id="errorTxt"]').text("Password changed. Click on Login to continue.");
var formURL = $(this).attr('action');
$.ajax({
url: formURL,
type: 'POST',
data: $(this).serialize(),
dataType: 'JSON'
})
.done (function(data, textStatus, jqXHR) {
if (!data.status) {
var Msg = "Password Not Changed. Password Change Failed.";
var focusSet = false;
$.each(data.Msg, function(elemName, errMsg) {
*$("#" + elemName).attr("type", "text");
if (!$("#" + elemName).parent().hasClass("error")) {
$("#" + elemName).parent().append('<div class="chngPwderr error">' + errMsg + '</div>');
}
if (!focusSet) {
$("#" + elemName).focus();
focusSet = true;
}*
});
}
$('#chngPwdForm div[id="errorTxt"]').text(Msg).show();
})
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.
function update(){
var name= document.getElementById("TextBox").value;
$.ajax({
url: '....',
type: 'post',
data: {....//many data include// 'name' : name, ....},
success: function(data) {
var replacevalue=data.replace(/[\[\]']/g,'' );
alert(replacevalue);
var stringstatus=replacevalue.replace(/['"]+/g, '');
alert(stringstatus);
if(stringstatus == "success"){
alert ("Successfully Update ")
}
else{
alert("Failed!");
return ;
}
returnToDisplayPage();
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
});
}
function returnToDisplayPage(){
var id = document.getElementById("TextBox").text;
window.location = './DisplayPage.php?Name='+id;
}
Please suggest me. How should I do to get the updated data when click update button and refresh or reload page ? In function returnToDisplayPage() methods. I got only the name of update data and other related fields data didn't get back.
Try something like this:
$.post('url', {params}, function(response){
//Here you check if you got response from url
// And then you can do whatever you like to do with received data
if(response == 'ok'){
//do your stuff
//then
window.location.reload();
}
}
When we will get result in response then After 5 seconds page will be refresh..
success: function(data){
if(data.success == true){ // if true (1)
setTimeout(function(){// wait for 5 secs(2)
location.reload(); // then reload the page.(3)
}, 5000);
}
}
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);
}
});
});
I have a button that turns on and off a connection. When the button is in on state and the user clicks on it. In order to turn it off, a modal pops up and asks for confirmation. But when the button is in off state, no modal should pop up. The problem is that its the same button that is being toggled to display "On" and "Off" and a modal element is attached to it. Even when the off button is clicked the modal pops up which I don't want. Please help me out.
if(status == 'On'){
var url = "/streams/status";
$('button[id="modal-'+ streamId + '"]').click(function(){
console.log("close modal function")
$('myModal-'+ streamId).modal('hide');
$.ajax({
type: "POST",
url: url,
data: "streamId="+streamId,
success: function(res){
$('button[id="profile-'+ res.streamId + '"]').toggleClass('btn-success btn-danger');
$('button[id="profile-'+ res.streamId + '"]').text(function (){
console.log($(this).text())
return 'Off';
});
},
error: function (res){
console.log('there was an error', res);
}
});
})
}
else{
console.log("button is off currently");
$('myModal-' + streamId).modal('hide');
var url = "/streams/status";
$.ajax({
type: "POST",
url: url,
data: "streamId="+streamId,
success: function(res){
$('button[id="profile-'+ res.streamId + '"]').toggleClass('btn-success btn-danger');
$('button[id="profile-'+ res.streamId + '"]').text(function (){
console.log($(this).text())
return 'On';
});
},
error: function (res){
console.log('there was an error', res);
}
});
}
})
i think you should add a rel attribute (off or on), detect onclick event and check this attribute :
$('#myModal-' + streamId).click(function(event){
if($('#myModal-' + streamId).attr('rel') == 'on'){
//do ajax request ON here
//on success ajax, replace return 'off' by
$('#myModal-' + streamId).attr('rel', 'off');
}
else{
//do ajax request OFF here
//on success ajax, replace return 'on' by
$('#myModal-' + streamId).attr('rel', 'on');
}
}
it should be works
Here is the correct way to do it:
script.
function toggleStatus (streamId, statusBefore){
$.ajax({
type: "POST",
url: "/streams/status",
data: "streamId="+streamId,
success: function(res){
$('button[id="profile-'+ res.streamId + '"]')
.toggleClass('btn-success btn-danger')
.attr('data-toggle', statusBefore == true ? "": 'modal');
$('#profile-glyphicon-'+ res.streamId).toggleClass('glyphicon-ok glyphicon-remove');
},
error: function (res){
console.log('there was an error', res);
}
});
}
$('button[id^="modal-"]').click(function(){
var streamId = this.id.split('-')[1];
toggleStatus(streamId, true);
$('myModal-'+streamId).modal('hide');
})
$('button[id^="profile-"]').on("click", function(e){
var streamId = this.id.split('-')[1];
var statusBefore;
var dataToggleStatus = $('#profile-' + streamId).attr("data-toggle");
if(dataToggleStatus=='modal'){
statusBefore = true;
e.preventDefault();
} else {
statusBefore = false;
toggleStatus(streamId, statusBefore);
}
})