Jquery Ajax request Fail - javascript

I have a web service that does work properly when asked directly by url but i cant seem to call it through a Jquery Ajax call.
Here's my code:
jQuery("#field1").focusout(function() {
alert("focusOut");
jQuery.ajax({
type: 'POST',
url: '/motifRes/name',
data: { 'clRef' : document.getElementById("field1") },
datatype: 'text',
success: function(msg) {
$("#nomClient").val(msg);
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
alert(textStatus, errorThrown);
}
});
});
I do enter in the function because i get the "focusOut" alert but then nothing, just nothing.
I used the Chrome developper tool and fiddler and I see no request, no error.
Any ideas ?
EDIT:
About your questions :
are you requesting from an external domain?
Blockquote
No I am not
Are you sure its a POST request?
Well either way, it doesnt change a thing =/
Here's my HTML
<div class="panel" id="standard">
<form id="test" action="#" method="get">
<fieldset>
<legend>Formulaire de changement du motif d'annulation</legend>
<div class="form-row">
<div class="field-label"><label for="field1">Ref Client</label>:</div>
<div class="field-widget"><input name="field1" id="field1" title="Entrer la référence client" /><input id="nomClient" readonly="readonly" type="text" value=""></input></div>
</div>

Use done(), fail(), and always() instead of success() and error(). Also use document.getElementById("field1").value instead of document.getElementById("field1").
jQuery("#field1").focusout(function() {
alert("focusOut");
jQuery.ajax({
type: 'POST',
url: '/motifRes/name',
data: { 'clRef' : document.getElementById("field1").value },
datatype: 'text',
done: function(msg) {
$("#nomClient").val(msg);
},
fail: function (xmlHttpRequest, textStatus) {
alert(textStatus);
}
});
});

Change your data attribute to
data: { 'clRef' : $("#field1").val() },

Finally got it. A vicious and well rookie mistake I guess...
url: '/motifRes/name'
=!
url: 'motifRes/name'
The slash does mean an absolute path and without it the root of my webservice does concat with the url...

Related

FormData ajax upload on IE8 -> alternatives and how it works

I'm tyring to upload a picture with ajax, so I'm using FormData, but it's not working with IE8. I've looked about it and it's not possible to use FormData with IE8, but I've found nothing I've been able to use instead in order to make it work on IE8 and other browser. Could someone tell me what to do please, and how to do it ?
The form I'm trying to submit
<form id="addImgForm" name="addImgForm" method="post" action="#URL(Action('ChiliTest-ImageUpload'))#" enctype="multipart/form-data">
<input id="newImage" type="file" name="newImage">
<input type="hidden" name="MAX_FILE_SIZE" value="12345">
<span id="addImage" class="button-addImage" type="submit"><isTradConstant keyword="l_customizationsChiliEditor_AddImageButtonTitle" template="CustomizationsChiliEditor" init="Ajouter"></span>
</form>
Called on addImgForm submit
$.ajax({
url: myUrl,
type: "POST",
data: new FormData($(this).parent()[0]),
contentType : false,
async: false,
processData: false,
cache: false,
success: function(data) {
//do something
}
});
return false;
Ideally when i faced this issue, i checked for FormData in browser and if that returns undefined, then i went for form submission via an iframe.
We have used jquery plugin for the same and got resolved this issue.
It is too simple just use
$('#myForm').ajaxForm(function() {
});
instead of below call, it set all options automatically.
$.ajax({
url: myUrl,
type: "POST",
data: new FormData($(this).parent()[0]),
contentType : false,
async: false,
processData: false,
cache: false,
success: function(data) {
//do something
}
});
Hope this will work out, let me know if any hurdles during implementation. Make sure you added jquery plugin before using ajaxform function. Do not need to do anything for other browser it works for IE and other both.
You can use [jQuery Form Plugin][1] to upload files via ajax in IE 8 and your example code should be like this:
[1]:
$(document).ready(function() {
var options = {
beforeSend: function() {
$("#progress").show();
//clear everything
$("#bar").width('0%');
$("#message").html("");
$("#percent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete) {
$("#bar").width(percentComplete + '%');
$("#percent").html(percentComplete + '%');
},
success: function() {
$("#bar").width('100%');
$("#percent").html('100%');
},
complete: function(response) {
$("#message").html("<font color='green'>" + response.responseText + "</font>");
},
error: function() {
$("#message").html("<font color='red'> ERROR: unable to upload files</font>");
}
};
$("#myForm").ajaxForm(options);
});
<script src="http://malsup.github.io/min/jquery.form.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<form id="myForm" action="/demo/Upload" method="post" enctype="multipart/form-data">
<input type="file" size="60" name="myfile">
<input type="submit" value="Ajax File Upload">
</form>
<div id="progress">
<div id="bar"></div>
<div id="percent">0%</div>
</div>
<br/>
<div id="message"></div>

how to prevent redirect on form submit

i am getting a form with user parameters when i make an AJAX call to a page which later on is submiited to a url so that i can create a session for the same user in advance and when
that person goes to that site he sees his name there.
i created one div tag with id "abc_session", assign that form (whose id is fm1) to it,and submitted the form.
now as per the requirement session is created but page automatically gets redirected to that site url to which form is submitted.i just don't wan't that to happen.
can anyone please suggest something..or some workaround
the form that AJAX returns looks something like this:
<html>
<body onload="document.fm1.submit();return false">
<form name = "fm1" method="post" action = "https://abcd.com/abc ">
<input type=hidden name ="name" value="xyz">
<input type=hidden name ="login_parameters" value="CDF5D71C5BDB942EE2FB6C285B8DEBFE4C5675137B615CD2276571813AAC872AC8942E26B71026414BED1FEA09427D0B20A50FE2F70032D2E5B382598EC3C71D73EAB4ECBF7273A73BEB98ACEA4A0B775E7772BDC7C6746C355">
</form></body>
</html>
and the script goes like this
$(document).ready(function() {
function callwebsite()
{
$.ajax({
url: "/NASApp/benemain/website",
data: {},
type:"POST",
dataType: 'text',
cache: false,
success: function (data) {
alert("Call made to website.. ");
console.log(data);
document.getElementById("abc_session").innerHTML=data;
document.fm1.submit();
},
error : function(response){
console.log('ERROR');
},
statusCode : {
500 : function() {
console.log('500 error');
window.location.reload(true);
},
401 : function() {
console.log('401 error');
window.location.reload(true);
},
404 : function(){
console.log('400 error');
}
}
});
}
callwebsite();
tried extracting the data and maiking another ajax call as suggested by quentin but getting this error "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource.This can be fixed by moving the resource to the same domain or enabling CORS."
$.ajax({
url: lcAction,
data: {partner_id:lcPartner,login_parameters:lcLP },
type:"POST",
headers:{'Access-Control-Allow-Origin': '*'},
dataType: 'text',
//crossDomain: true,
//cache: false,
success: function(data)
{
alert("success");
},
error:function(response)
{
//alert("error");
console.log(response);
}
});
You are submitting the form:
document.getElementById("abc_session").innerHTML=data;
document.fm1.submit(); // Here
Don't do that.
Extract the data from it and make another Ajax request.
You should use e.preventDefault() as soon as you submit the form.

Facing AJAX issue with JSP

I am working on a small tool which just consists of a single JSP which is used for view as well as for processing the AJAX response.
If the call is of type 'GET', I am showing a form the user.
<form id="submitForm" method="post">
<div class="ui-widget">
<label for="tags">Please Select the Merchant : </label>
<input id="tags" name="mechant" style="width:300px;height:40px;border: 0.5px solid;border-radius: 5px;">
<input type="submit" value="Get Data" style="border: 0.5px solid;border-radius: 5px;">
</div>
</form>
And following is the code which will make the call.
$("#submitForm").submit(function() {
$.ajax({
url: 'serve_tx_2.jsp',
type: 'POST',
data: {q: $('#tags').val()},
success: function(data) {
$('#data').html(data);
alert('Load was performed.');
},
beforeSend: function() {
// $('.loadgif').show();
},
complete: function() {
// $('.loadgif').hide();
}
});
//return false;
});
Once the user submits the form which goes as 'POST' the logic in the same JSP is returning the response.
Right now I am trying with a very simple logic.
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("Hello World");
Now when this response is return the whole of initial page is washed off and I just see "Hello World" on the page. Even though as per my understanding only the div with id "data" should be updated with value.
Kindly anyone have a look and let me know what might be going wrong here.
Thanks in advance.
You could try preventing the default handler as well as prevent bubbling up the DOM.
$("#submitForm").submit(function(event) {
// Prevent the default action
event.preventDefault();
// Pevent propagation of this event up the DOM
event.stopPropagation();
$.ajax({
url: 'serve_tx_2.jsp',
type: 'POST',
data: {q: $('#tags').val()},
success: function(data) {
$('#data').html(data);
alert('Load was performed.');
},
beforeSend: function() {
// $('.loadgif').show();
},
complete: function() {
// $('.loadgif').hide();
}
});
//return false;
});

How to print output when ajax method returns error?

i have $.ajax method like this
<form class="hidden code-box" method="GET" name="sample">
<div dir="ltr"><textarea class="php" name="codeguru"></textarea></div>
<div class="hint">This code is editable. Click Run to execute.</div>
<input type="submit" value="Run" />
<img class="hidden" style="vertical-align: middle;" alt="Try PHP " src="http://code.guru99.com/img/ajax-loader.gif" name="ajax-loader" title="Try PHP " />
<div class="hidden stdout"></div>
<div class="hidden stderr"></div>
</form>
$.ajax({
type: 'GET',
url: '/exec.php',
dataType: 'JSONP',
data: {code : code},
success: function(data)
{
//alert(data.result);
var data = data.result;
$(loader).addClass('hidden');
var stdout = $(form).children('.stdout');
if (data.search("Parse error")>0)
{
var str = data.replace('<b>Parse error</b>: ','');
$(stdout).html(str);
$(stdout).removeClass('hidden');
}
else
{
$(stdout).html(data);
$(stdout).removeClass('hidden');
}
},
jsonpCallback: 'mycallback',
error: function (xhr, ajaxOptions, thrownError,err,textStatus) {
var stdout = $(form).children('.stdout');
alert (stdout);
$stdout.html("Fatal error generated!!! Please check your code");
$stdout.removeclass('hidden');
}
});
Now i want to print the error generated because of $.ajax method. and i have tried this.
error: function (xhr, ajaxOptions, thrownError,err,textStatus) {
var stdout = $(form).children('.stdout');
alert (stdout);
$stdout.html("Fatal error generated!!! Please check your code");
$stdout.removeclass('hidden');
}
Please help
Try this:
$( document ).ajaxError(function( event, request, settings ) {
console.log(settings.url);
});
or
$.ajax({
type: 'GET',
url: '/exec.php',
dataType: 'JSONP',
data: {code : code},
success: function(data)
{
},
error: function(ts) { console.log(ts.responseText) }
});
well you don't need $ in stdout since it is already a jquery object..
try this
error: function (xhr, ajaxOptions, thrownError,err,textStatus) {
var stdout = $(form).children('.stdout'); //here stdout is jquery object
alert (stdout);
stdout.html("Fatal error generated!!! Please check your code");
//--^---notice missing $ here
stdout.removeClass('hidden');
//-----------^----- here notice uppercase `C`
}

Subscribe Form using Ajax

I'm really clueless as to how to get this done.
I need to make a subscribe with email button and it needs to be validated and show a little message for success, Loading ands Error.
I have never worked with Ajax before and this is what I have to do, I have To complete the newsletter subscribe ajax-functionality using a pre-defined controller in a php file on the server called newsletter.php and the I should use the controller function named subscribe in there to generate the response for the ajax request.
If that makes any sense please help me out.
This is my form for the email address
<div id="subscribeText">
<form action="" method="post" name="ContactForm" id="ContactForm" >
<input type="submit" name="subscribeButton" id="subscribeButton" value="Submit" />
<input type="text" name="subscribeBox" id="subscribeBox" value="Enter your email address..." size="28" maxlength="28" onFocus="this.value=''" />
</form>
</div>
http://jsfiddle.net/vaaljan/R694T/
This is what the success should look like and error and loading pretty much the same.
What the success message looks like
Hope this isn't too far fetched, I have not worked with java script that much yet but I understand more or less.
Thanks
I have made a small example on jsfiddle.
$('#send').click(function (e) {
e.preventDefault();
var emailval = $('input#email').val();
console.log(emailval);
if (emailval !== "") {
$.ajax({
cache: false, // no cache
url: '/echo/json/', // your url; on jsfiddle /echo/json/
type: 'POST', // request method
dataType: 'json', // the data type, here json. it's simple to use with php -> json_decode
data: {
email: emailval // here the email
},
success: function (data) {
console.log(data);
$('<strong />', {
text: 'Successfull subscribed!'
}).prependTo('#state');
},
error: function (e) {
$('<strong />', {
text: 'A error occured.'
}).prependTo('#state');
},
fail: function () {
$('<strong />', {
text: 'The request failed!'
}).prependTo('#state');
}
});
} else {
alert("Insert a email!");
}
});
Here it is.
It uses jQuery for the ajax request.
The example shows how ajax works.

Categories

Resources