AJAX call doesn't work after submitting a form - javascript

This is my code at www.domain-a.de/external.search.js. I call it from www.domain-b.de/test.php:
(function ($) {
// make the ajax request
$.getJSON('http://www.domain-a.de/external-search.js?jsoncallback=?', function(data) {
// append the form to the container
$('#embedded_search').append(data);
$('#embedded_search form').attr('action','');
myUrl = 'http://www.domain-a.de/get-form-values?jsoncallback=?'
var frm = $('#embedded_search form');
// click on submit button
frm.submit(function (ev) {
$.getJSON( myUrl )
.done(function( json ) {
console.log( "JSON Data: " + json );
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
});
});
})(jQuery);
After running this code I don't get any message in console. What is wrong with that code?

frm.submit(function (ev) {
ev.preventDefault();
.....rest of code.

Your code is not calling the submit handler on the item, it is simply binding it. You should do the frm.submit(function binding outside of your $.getJSON callback; then inside the callback add
frm.submit()
Which triggers the event.
Also, when the submit happens, your actions will take place but then the form will submit to the back end as normal, causing a page reload.
After the line
frm.submit(function (ev) {
Add
ev.preventDefault();
So your overall code should be
(function ($) {
var frm = $('#embedded_search form');
var myUrl = 'http://www.domain-a.de/get-form-values?jsoncallback=?'
frm.submit(function (ev) {
ev.preventDefault();
$.getJSON( myUrl )
.done(function( json ) {
console.log( "JSON Data: " + json );
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
});
// make the ajax request
$.getJSON('http://www.domain-a.de/external-search.js?jsoncallback=?', function(data) {
// append the form to the container
$('#embedded_search').append(data);
$('#embedded_search form').attr('action','');
// click on submit button
frm.submit();
});
})(jQuery);

Related

Cakephp (2.x) Model Validation using "onclick" in Jquery not working

I'm working on a code already wrote... in CakePHP.
And, I've add some model validations.
But, in Jquery, this code works fine (model validation and HTML5 messages):
$('#itemAdd').on('submit', function(e) {
var $itemAdd = $("#itemAdd");
e.preventDefault();
var $this = $(this);
$this.serialize();
$.ajax({
...
}).done(function (data) {
if (data == true) {
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
});
location.reload();
}
}).fail(function () {
alert("Error");
});
});
But, when it's using 'click', the ajax method works but the validation NOT... :( :
$("#next-item").on('click', function(e) {
e.preventDefault();
var $itemAdd = $("#itemAdd");
var data = $itemAdd.serializeArray();
var $this = $(this);
$.ajax({
...
}).done(function (data) {
alert(data);
alert('go !');
var $addItem = $("#addItem");
$addItem.removeData('modal-header');
$addItem.removeData('modal-body');
$("#addItem .modal-content").load('<?php echo FULL_BASE_URL; ?>/stock/stocks/modal_item_add/<?php echo $batch_id; ?>', function () {
$('#addItem').modal('show');
});
}).fail(function (jqXHR, textStatus, errorThrown) {
alert("An error : " + textStatus + ", " + errorThrown );
});
return false;
});
The validation based on the Model doesn't work. But, in the Php method ,launched with Jquery Ajax, show me (it's ok) the validations errors with :
$this->Item->invalidFields();
There's a problem cause when I use $("#next-item") I want the jQuery modal not hide.
And using "submit" instead of "click" close the modal.
Can anybody has an idea ?
Thanks.
F.

both .done and .fail fires togheter

I have this JS:
$('.save').click(function(e){
var row = $(this).closest('tr');
var button = $(this);
var myParams = new Object();
myParams.id = row.find('.id').text();
myParams.data = row.find('.data').text();
myParams.descrizione = row.find('.descrizione').text();
myParams.movimento = row.find("select[name='tipo_mov']").val();
myParams.importo = row.find('.importo').text();
myParams.from = 'carta';
var params = JSON.stringify(myParams);
$.post( "edit_mov.php", params)
.done(function( data ) {
bootbox.alert("Movimento aggiornato correttamente");
button.toggle().prev('.edit').toggle();//ripristino il pulsante di edit;
row.removeClass('info').addClass('success').find('.tbe').attr('contenteditable', false).css('color','');
row.find('.tipo_mov').toggle();
setTimeout(function () {
row.removeClass('success');
}, 2000);
})
.fail(bootbox.alert("UPS! Something went wrong"));
});
This is done to update a table row with an AJAX request.
The PHP page responsible for update will return 200 or 500 depending if the query is successful or not:
if($count==0){
http_response_code(500);
}else{
http_response_code(200);
}
If I try with a query that will fail my JS will show only the alert in the .fail.
If I try with a query that will succeed then I will see both the alerts (.done and .fail).
I also tried to replace .done with .success buth with the same results. What am I doing wrong?
You should also use a function in .fail:
.fail(function() {
bootbox.alert("UPS! Something went wrong");
});
Otherwise the code inside the brackets is always executed.
as per docs.
https://api.jquery.com/jquery.post/
var jqxhr = $.post( "example.php", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
.fail should be supplied with a function

Abort all async request

In my page, I call 15 ajax request. Also I have a button which cancels all the pending ajax requests. As per documentation, abort() terminates the request if it has already been sent.
Now when I check my console, even after I click cancel button, I get some replies from ajax script (I guess those were already sent by the time I clicked that button). So how can I make sure no reply should come once I press cancel button?
You can check the script here (couldn't use jsfiddle as not sure how to make ajax request).
JS Code
var xhrPool = [];
$(window).load(function(){
callAjax1();
});
$.ajaxSetup({
beforeSend: function(jqXHR) {
xhrPool.push(jqXHR);
},
complete: function(jqXHR) {
var index = xhrPool.indexOf(jqXHR);
if (index > -1) {
xhrPool.splice(index, 1);
}
}
});
var abortAjax = function () {
$.each(xhrPool, function(idx, jqXHR) {
if(jqXHR && jqXHR .readystate != 4){
jqXHR.abort();
}
});
console.log("All pending cancelled"); // Should not have any ajax return after this point
$.xhrPool = [];
};
$("#cancel-button").click(function (){
abortAjax();
});
function callAjax2(ajaxcallid){
console.log("Initiate ajax call " + ajaxcallid); // Should not have any ajax return after this point
$.ajax({
method: "POST",
url: "test.php"
})
.done(function( msg ) {
console.log(msg + ajaxcallid); // msg = "Ajax return for "
})
.fail(function( jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
});
}
function callAjax1(){
$.ajax({
method: "POST",
url: "test.php"
})
.done(function( msg ) {
for(var i = 0; i < 15; i++){
callAjax2(i);
}
})
.fail(function( jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
});
}
Console Output:
try this
$.each(xhrPool.slice(), function(idx, jqXHR) {
I think while you are aborting, some are returning, so the array gets messed up
this way you are working with a snapshot of the array
though, one or two may still sneak through due to timing of course

jquery: how to detect element that is being loaded every few seconds

I have a div element where a file is being loaded every 10500 miliseconds;
index.php
...
<div class="loadHere"></div>
...
code that loads every few seconds.
setInterval(
function ()
{
$('.loadHere').unload().load('filetoload.php').fadeIn('slow');
}, 10500);
filetoload.php
test
<input type="hidden" value="1234" class="hiddenelement"/>
and this is what i'm trying to do but isn't working:
$(document).on('click','.testbtn',function(event)
{
event.preventDefault();
var xyz = $('.hiddenelement').val();
alert(xyz);
});
Your strategy seems to work.
setInterval(
function () {
$('.loadHere').unload().load('toload.php').fadeIn('slow');
}, 10500);
$(document).on('click','.testbtn',function(event)
{
event.preventDefault();
var xyz = $('.hiddenelement').val();
alert(xyz);
});
Here is the working plunker : http://plnkr.co/edit/tiLv3WMDCjoW3Ggb9bTH?p=preview.
Use Callback function:
$( "#success" ).load( "/not-here.php", function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
From Jquery Docs

How to get response with .load jQuery

I am working with .load function in jQuery to load a html page into a div with ajax but I have problem since server always doesn't send a html, sometimes it send a json and I want to get that json with .load.
I thought it would be a response in callback function in .load but it return undefined and just put that json into the div so how can I get that json with .load.
The server send this json :
{ok : false}
Here is my jQuery code:
$( "#div").load( "url", function( response, status, xhr ) {
////how can I get the false result here response.ok return nothing!!!
console.log(response.ok);
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#div" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
i think you have to do something like this:
$("#div").load( "url", function( response, status, xhr ) {
var responseAsObject = $.parseJSON(response);
console.log(responseAsObject.ok);
});
Using response to replace #div html content :
$("#div").load("url", function (responseTxt, statusTxt, xhr) {
if (statusTxt == "success") {
var responseAsObject = $.parseJSON(response);
$(this).html( responseAsObject.response );
}
if (statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});

Categories