ajax success event doesn't work after being called - javascript

After searching here on SO and google, didn't find an answer to my problem.
The animation doesn't seem to trigger, tried a simple alert, didn't work either.
The function works as it is supposed (almost) as it does what i need to, excluding the success part.
Why isn't the success event being called?
$(function() {
$(".seguinte").click(function() {
var fnome = $('.fnome').val();
var fmorada = $('.fmorada').val();
var flocalidade = $('.flocalidade').val();
var fcodigopostal = $('.fcodigopostal').val();
var ftelemovel = $('.ftelemovel').val();
var femail = $('.femail').val();
var fnif = $('.fnif').val();
var fempresa = $('.fempresa').val();
var dataString = 'fnome='+ fnome + '&fmorada=' + fmorada + '&flocalidade=' + flocalidade + '&fcodigopostal=' + fcodigopostal + '&ftelemovel=' + ftelemovel + '&femail=' + femail + '&fnif=' + fnif + '&fempresa=' + fempresa;
$.ajax({
type: "GET",
url: "/ajaxload/editclient.php",
data: dataString,
success: function() {
$('.primeirosector').animate({ "left": "+=768px" }, "fast" );
}
});
return false;
});
});

you are trying to pass query string in data it should be json data.
Does your method edit client has all the parameters you are passing?
A simple way to test this is doing the following:
change this line to be like this
url: "/ajaxload/editclient.php" + "?" + dataString;
and remove this line
data: dataString
The correct way of doing it should be, create a javascript object and send it in the data like so:
var sendData ={
fnome: $('.fnome').val(),
fmorada: $('.fmorada').val(),
flocalidade: $('.flocalidade').val(),
fcodigopostal: $('.fcodigopostal').val(),
ftelemovel: $('.ftelemovel').val(),
femail: $('.femail').val(),
fnif: $('.fnif').val(),
fempresa: $('.fempresa').val()
}
$.ajax({
url: "/ajaxload/editclient.php",
dataType: 'json',
data: sendData,
success: function() {
$('.primeirosector').animate({ "left": "+=768px" }, "fast" );
}
});
Another thing shouldn't this be a post request?
Hope it helps

Related

JQuery click 1 does nothing

I have a feeling there is something wrong with my for loop. When my websites event is activated the first time, I get no response. It works as intended every time after that. I have tried tuning the numbers in the for loop looking for mistakes but as far as what I've tried. It works best as is.
For the full app: https://codepen.io/xcidis/full/KvKVZb/
var reference = [];
function random() {
$.ajax({
url: "https://api.forismatic.com/api/1.0/?",
dataType: "jsonp",
data: "method=getQuote&format=jsonp&lang=en&jsonp=?",
success: function(quote) {
reference.push([quote.quoteText + "<br/><br/><br/><div align='right'>~" + quote.quoteAuthor + "</div>"]);
}
});
}
$("button").click(function(){
random();
for(i=0;i<4; i++){
if(reference[reference.length-1] == undefined){continue}else{
var boxes = $("<div id='boxes'></div>").html("<p>" + reference[reference.length-1] + "</p>");
$('body').append(boxes);
break;
};
};
});
Your rest of the code ran before your ajax push the value to reference variable.
https://www.w3schools.com/xml/ajax_intro.asp
You can either put your page rendering code within the ajax or use some tips to run the rederer synchronously
$("button").click(function(){
$.when( $.ajax({
url: "https://api.forismatic.com/api/1.0/?",
dataType: "jsonp",
data: "method=getQuote&format=jsonp&lang=en&jsonp=?",
success: function(quote) {
reference.push([quote.quoteText + "<br/><br/><br/><div class='tweet' align='left'></div><div align='right'>~" + quote.quoteAuthor + "</div>"]);
}
})).then(function() {
console.log(reference)
for(i=0;i<4; i++){
if(reference[reference.length-1] == undefined){continue}else{
var boxes = $("<div id='boxes'></div>").html("<p>" + reference[reference.length-1] + "</p>");
$('body').append(boxes);
break;
};
};
});
});

Ajax Response add under each element

I have a question that I can't seem to answer about Jquery Ajax Response.
I use a for each to select some data from <p> tags in each info_div. This data I then use to do a ajax call to a service that replies with a XML. I want to place some elements from this XML under each div from where I took the two variables. Each div should have it's own reply.
$(document).ready(function () {
$('#action-button').click(function () {
$(".info_div").each(function () {
var var1 = $(this).find('p:nth-child(4)').text();
var1 = var1.slice(-10);
var var2 = $(this).find('p:nth-child(8)').text();
var2 = var2.slice(-1);
$.ajax({
type: "GET",
url: "http://www.mypage.com/mypage&value1=" + "va1" + "&value2=" + "var2",
cache: false,
dataType: "xml",
success: function (xml) {
$(xml).find('member').each(function () {
var name = $(this).find("title").text()
/* how do I get this variable under each $('.info_div') from where I selected the var1 and var2
Every attempt I made places all replies under all the divs in class .info_div */
});
}
});
});
});
});
I would not recommend you to send ajax requests in a loop. Better collect all your data, then send it to the server and handle the response.
Meanwhile, if you insist to do it in a loop, you should make a reference to the iterated element from $(".indo_div) collection, and use it in ajax callback.
$(".info_div").each(function() {
var _that = $(this);
var var1 = $(this).find('p:nth-child(4)').text();
var1 = var1.slice(-10);
var var2 = $(this).find('p:nth-child(8)').text();
var2 = var2.slice(-1);
$.ajax({
type: "GET",
url: "http://www.mypage.com/mypage&value1=" + "va1" + "&value2=" + "var2",
cache: false,
dataType: "xml",
success: function(xml) {
$(xml).find('member').each(function(){
var name = $(this).find("title").text()
that.append(name);
});
}
});
});

Returning Response in jquery ajax function

Getting problems in Response.d , based on the result which is returning by the checkusers() function I am saving the values. If the entered name is in already in database it should say "User already exists", if it is not in database it should create a new record.
But I am not getting the correct value from (response), I observed that Console.log(response.d) giving me correct values like 'true' or 'false'. I tried everything I know like-
changing async:"false"
var jqXHR = $.ajax({ and returning jqXHR.responseText
But none of they worked for me . Please help me with this.
submitHandler: function (form) {
var txtName = $("#txtName").val();
var txtEmail = $("#txtEmail").val();
var txtSurName = $("#txtSurName").val();
var txtMobile = $("#txtMobile").val();
var txtAddress = $("#txtAddress").val();
var obj = CheckUser();
if (obj == false) {
$.ajax({
type: "POST",
url: location.pathname + "/saveData",
data: "{Name:'" + txtName + "',SurName:'" + txtSurName + "',Email:'" + txtEmail + "',Mobile:'" + txtMobile + "',Address:'" + txtAddress + "'}",
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function (response) {
$(".errMsg ul").remove();
var myObject = eval('(' + response.d + ')');
if (myObject > 0) {
bindData();
$(".errMsg").append("<ul><li>Data saved successfully</li></ul>");
}
else {
$(".errMsg").append("<ul><li>Opppps something went wrong.</li></ul>");
}
$(".errMsg").show("slow");
clear();
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
}
else {
$(".errMsg").append("<ul><li>User Already Exists </li></ul>");
$(".errMsg").show("slow");
}
}
});
$("#btnSave").click(function () {
$("#form1").submit()
});
});
checkusers function is:
function CheckUser() {
var EmpName = $("#txtName").val();
$.ajax({
type: "POST",
url: location.pathname + "/UserExist",
data: "{Name:'" + EmpName + "'}",
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function (response) {
console.log(response.d);
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
}
Just because your database returns true or false doesn't mean this also gets returned by your CheckUser().
There are several options here:
Either you make a local variable in your CheckUser, Make your Ajax call synchronous, set the local variable to response.d in the success function and then return that local variable.
Another option is to work with Deferred objects and make your submithandler Ajax call wait for the Checkuser Ajax call to return;
A third option is to call your create ajax call from your success callback in your CheckUser Ajax call if the user isn't created yet.
I would recommend either option 2 or 3, because option 1 is not userfriendly.

Getting this in ajax result

im trying to make a script that changes P lines to input fields, let user edit them and then revert back to p lines after a check in an external php document through ajax. However the problem seems to be that I cant use this within the ajax part, it breaks the code. How can I solve that? Do I need to post the HTML?
$(document).ready(function () {
function changeshit(result, that) {
if (result == "success") {
$(that).closest('div').find('input').each(function () {
var el_naam = $(that).attr("name");
var el_id = $(that).attr("id");
var el_content = $(that).attr("value");
$(that).replaceWith("<p name='" + el_naam + "' id='" + el_id + "'>" + el_content + "</p>");
});
$(".editlink").replaceWith("Bewerken");
} else {
alert(result);
}
}
$(".editinv").on('click', 'a', function () {
var editid = $(this).attr("id");
var edit_or_text = $(this).attr("name");
if (edit_or_text == "edit") {
$(this).closest('div').find('p').each(function () {
var el_naam = $(this).attr("name");
var el_id = $(this).attr("id");
var el_content = $(this).text();
$(this).replaceWith("<input type='text' name='" + el_naam + "' id='" + el_id + "' value='" + el_content + "' />");
});
$(".editlink").replaceWith("Klaar");
} else if (edit_or_text == "done") {
var poststring = "";
$(this).closest('div').find('input').each(function () {
var el_naam = $(this).attr("name");
var el_id = $(this).attr("id");
var el_content = $(this).attr("value");
poststring = poststring + '' + el_naam + '=' + el_content + '&';
});
poststring = poststring + 'end=end'
$.ajax({
url: 'http://' + document.domain + '/klanten/updateaddress.php',
type: 'post',
data: poststring,
success: function (result, this) {
changeshit(result, this);
}
});
}
});
});
Yes, the common solutions is declare a var example self = this and use that variable
var self = this;
$.ajax({
url: 'http://'+document.domain+'/klanten/updateaddress.php',
type: 'post',
data: poststring,
success: function(result) {
changeshit(result, self);
}
});
}
In that way, the this context is save in the variable.
Try the following:
Right under $(".editinv").on('click', 'a', function () { add
$(".editinv").on('click', 'a', function () {
var element = this;
And then change this to:
$.ajax({
url: 'http://' + document.domain + '/klanten/updateaddress.php',
type: 'post',
data: poststring,
success: function (result) {
changeshit(result, element);
}
});
That is if I am understanding correctly what you are trying to do
If you simply add:
context: this
to the $.ajax options then the success handler will automatically be called with the correct value of this, so you won't need the that parameter.
You'll then also no longer need the extra function wrapper around the success callback, so you can just use:
$.ajax({
url: 'http://' + document.domain + '/klanten/updateaddress.php',
type: 'post',
data: poststring,
context: this, // propagate "this"
success: changeshit // just pass the func ref
});
There are a few ways you can achieve this
1) If you read the docs (jQuery.ajax) you'll see that you can supply a context to the ajax method
context
Type: PlainObject This object will be made the context of all Ajax-related callbacks. By default, the context is an object that
represents the ajax settings used in the call ($.ajaxSettings merged
with the settings passed to $.ajax).
$.ajax({
url: 'http://'+document.domain+'/klanten/updateaddress.php',
type: 'post',
data: poststring,
context: this,
success: function(result) {
// the context sent above would become the context of this function when called by jquery
changeshit(result, this);
}
});
Using it this way you could even do it like the bellow code
function changeshit (result) {
var $that = $(this);
if (result == "success") {
$that.closest('div')... // cool ha ?
};
$.ajax({
url: 'http://'+document.domain+'/klanten/updateaddress.php',
type: 'post',
data: poststring,
context: this,
success: changeshit
});
2) You can take advantage of closures ( read more here or search google ), so your code would become
var context = this;
$.ajax({
url: 'http://'+document.domain+'/klanten/updateaddress.php',
type: 'post',
data: poststring,
success: function(result) {
// here you can use any variable you declared before the call
changeshit(result, context);
}
});
As a side note, i would recommend you use variable/object caching, so declare var $this = $(this) at the top of the function and use it thruought your function, instead of calling $(this) each time you need it.

jqGrid: grid function executes only once

Sorry, this is a Javascript beginner question. My jqGrid function works fine the first time around, but when I call it a second time, nothing happens, no request is issued. Code fragment:
$(document).ready(function() {
$("#submit").click(function(e) {
e.preventDefault();
var brandsDropdown = document.getElementById("brandsDropdown");
var brandId = brandsDropdown.options[brandsDropdown.selectedIndex].value;
var searchParams = "brandId=" + brandId;
doGrid(searchParams);
});
});
function doGrid(searchParams) {
alert("doGrid, searchParams:" + searchParams);
var url="${pageContext.request.contextPath}/services/setup/project";
var editurl="${pageContext.request.contextPath}/services/setup/project";
$("#projectList").jqGrid({
url: url + "?" + searchParams,
editurl: editurl,
datatype: 'xml',
mtype: 'GET',
...
});
The alert() shows me that doGrid() is really called successfully the second time. So it's really the $("projectList").jqGrid() function that doesn't execute, or fails silently .. Unless I made an obvious mistake in the way I call it?
I think the second time is no longer a need to regenerate the entire Grid. Then you only change the set parameters and grid computing to date. For this you need a trigger("reloadGrid") call.
$(document).ready(function() {
var runonce=false;
$("#submit").click(function(e) {
e.preventDefault();
var brandsDropdown = document.getElementById("brandsDropdown");
var brandId = brandsDropdown.options[brandsDropdown.selectedIndex].value;
var searchParams = "brandId=" + brandId;
doGrid(searchParams);
});
});
function doGrid(searchParams) {
alert("doGrid, searchParams:" + searchParams);
var url="${pageContext.request.contextPath}/services/setup/project";
var editurl="${pageContext.request.contextPath}/services/setup/project";
if (false==runonce) {
$("#projectList").jqGrid({
url: url + "?" + searchParams,
editurl: editurl,
datatype: 'xml',
mtype: 'GET',
...
});
runonce=true;
} else {
$("#projectList").jqGrid({
url: url + "?" + searchParams,
editurl: editurl
}).trigger("reloadGrid");
}

Categories

Resources