I would like to have an alert whenever people start typing in the text box. It will return "Data Saved: " + my msg that's in the test.php folder.
$("#textbox").on('change keyup paste', function() {
$.ajax({
method: "POST",
url: "test.php",
data: { content: $("#textbox").val() }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
I've tried changing "method" to "type".
Using .serialize().
Using success: function
I'm not sure what the problem is. Thank you!
Edit:
Added an error code. So far no error messages on console for this.
$.ajax({
method: "POST",
url: "test.php",
data: { content: $("#textbox").val() }
})
error: function (request, error) {
alert("An error occurred");
},
success: function (response) {
if (response == 'OK') {
$("#diary").val()
} else {
alert("An error occurred");
}
From your comment you are getting the following error:
$.ajax is not a function at HTMLTextAreaElement. (loggedinpage.php:92) at HTMLTextAreaElement.dispatch (jquery-3.1.1.slim.min.js:3) at HTMLTextAreaElement.q.handle (jquery-3.1.1.slim.min.js:3)
The error is telling you that the code cannot find the $.ajax() function anywhere in order to execute it.
At the same time, the message gives away the fact that you are using jQuery Slim. This cut-down version of the library does not include the $.ajax() function, among other things. You need to use the full version of jQuery.
Details in the latest (or any recent) release notes (in the "Slim build" section): https://blog.jquery.com/2017/03/20/jquery-3-2-1-now-available/
As a side note, I'm surprised that you want to show an alert every single time a user types a character into the textbox. I predict that this will quickly get very annoying for users. Maybe just showing a message inside a div nearby (which doesn't steal the focus and stop them typing) would be better. I'd also question whether it's really necessary to save the data to to the server every time a character is entered? If the user types quite a lot it will trigger off dozens of ajax requests. Your inclusion of the "keyup" is the reason for this. Perhaps have a rethink of exactly how you want this to work, and why.
Related
I am working inside of an Oracle package. I am trying to use an AJAX call to call a procedure from a button click. The ajax call is inside of a function. I am not getting any syntax errors from Oracle or when I'm using the browsers debug mode so I'm not sure what the problem is. Function is below.
htp.p('
function ApplyTest(_ht) {
var _inst = "";
var _pidm = '||v_web_pidm||';
var _inst = document.getElementById("Test").value;
alert("Heat Ticket value is: " + _ht);
alert("the instance is: " + _inst);
var resp = confirm("Are you sure you want patch applied to TEST8?");
if (resp == true) {
alert ("user pidm is: " + _pidm);
return $.ajax ({
type: "POST",
cache: false,
dataType: "json",
url: "gyapatch.p_update",
data: {"v_instance" : _inst, "v_ht" : _ht},
success : function(data) { alert("success"); }
});
alert("Got here");
alert("value: " + _inst);
window.location.reload;
alert("got to the end");
} else {
return;
}
}
');
code for the button is:
<button name="TestApply" id = "Test" onclick="ApplyTest('||val_patch.heat_ticket||')" type="button" value="T">Apply to TEST8</button>'
When I try to return the ajax call nothing is happening and I can't even reach the "Got Here" alert. When I remove the "return" keyword, I can reach the alerts but either way, nothing is happening. GYAPATCH.p_update is the package/procedure I wish to have executed when this is ran
I'm not sure what the problem is. Any help on this would be greatly appreciated. Thanks in advance.
So after a couple of hours, I had figured out the problem. This was more of a learning lesson as the issue was pretty simple. I needed to remember that I was working inside of an Oracle database AND also using WebTailor. The code posted above is correct. It turns out that the procedure I was trying to call (p_update) was not registered.
WebTailor allows you to build web applications utilizing Banner. In WebTailor, any pages that are used (usually stemming from a package.procedure), need to be registered or else they are not recognized.
I found this while debugging. Under the Network tab in my debugger, I noticed that when I click my button, I am getting a 404 error when my package.procedure is called. So I then realized it couldn't find my package and then proceeded to check if it was registered. This was a simple, silly error on my part. I am grateful for the feedback, but this will probably serve as a learning lesson or reminder to anyone trying to use ajax while working with Banner data.
I have a link, which links to domain.com , when a person clicks, I want it to do an ajax call to counter.php and post 2 variables to it, so it can add 1 to the views for that link.
I have a link:
Link Title
How would I do this with jquery?
EDIT:
I tried something like this
function addHit(str, partNumber){
$.get("counter.php", { version: str, part: partNumber })
}
It seems to work, but in firebug, the request never completes... it just does that "working..." animation. counter.php echos out some text when its done (doesnt need to show up anywhere).
From the jQuery documentation: http://api.jquery.com/jQuery.ajax/
function addHit(data1, data2)
{
$.ajax({
type: "POST",
url: "http://domain.com/counter.php",
data: "var1=data1&var2=data2",
success: function(msg){
alert( "Data Saved: " + msg ); //Anything you want
}
});
}
You need to add a callback on success
function addHit(str, partNumber){
$.get(
"counter.php",
{
version: str,
part: partNumber
},
function(data){
alert("Data Loaded: " + data);
})
)};
In the case of an anchor, you're leaving the page, so firebug's going to show some weird behavior here as it thinks execution would stop. Unless you're also preventing the default event behavior of the anchor...you're leaving the page and the request (in firebug's view) is discarded.
I have a form which submits data via AJAX to an external server.
The data which gets sent is then validated and if correct the user can then advance onto the next step of the form.
If the data is not valid, then the server returns an error which is outputted as a JSON object.
I can see the JSON object in FIDDLER.
My aim is to grab that JSON data and output it on the page and notify the user.
Ideally, i would do this as part of an error handler on the AJAX request(found below).
Is this achievable?
PS:
Unfortunately, I can't set up a demo because the link that the data is posted to is only available on my network.
It is also worth pointing out that the error that the back-end script outputs is actually stored in the link that the data is posted to.
AJAX REQUEST:
var setUpVrmData = function() {
$("#getvrmdata").click(function () {
var p_vrm = $('#p_vrm').val();
$.ajax({
dataType: "JSON",
type: "POST",
url: "http://217.35.33.226:8888/l4_site/public/api/v1/BC8F9D383321AACD64C4BD638897A/vdata",
data: {
vrm: p_vrm,
},
success: function(data) {
//Empty the dropdown box first.
$("#p_model").empty();
appendString = "<option value='none'>-- Select your model --</option>";
$.each(data['vehiclemodel'], function (k, v) {
// += concatenate the string
appendString += "<option value='" + k + "'>" + v + "</option>";
});
$("#p_model, #ent_mileage").show();
$('.js-find-my-car').hide();
$('.js-get-price').show();
$("#p_model").append(appendString);
$("#p_model").prop("disabled", false);
$('#skey').val(data['skey']);
},
error: function() {
console.log("We return error!");
}
});
});
The Error function will return an XHR object that you may be able to parse to get the message you want. I don't know what is serving the data so depending on how that's setup your mileage may vary. I've done this using PHP as well as C# and writing to Console, but in both cases I was able to control the returned data.
I used this article : http://encosia.com/use-jquery-to-catch-and-display-aspnet-ajax-service-errors/ as a starting point.
You'll need to update:
error: function() {
console.log("We return error!");
}
to
error: function(xhr, status, error) {
console.log("We return error!");
}
Set a break point there in Firebug to check if an XHR object is passed, if not you'll need to find a way to get it.. You mention you can see the JSON in fiddler, it should be available to you. If it is, just use the eval posed in the article and you should be okay. If not you'll have to go and figure out how to get it, depending on your platform difficulty will vary.
A few things to note, eval is messy and can get you into trouble. In the cases I've done this, I removed the eval in production.
Also as of jQuery 1.8 success error and complete are deprecated. Use done fail and always if you plan on updating jQuery in the future.
jQuery API reference, for reference.
http://api.jquery.com/jquery.ajax/
I've gotten my form to submit via PHP but I'm struggling a bit with the AJAX. Upon submission, the error always comes up as if res is set to false rather than true. I've tried toying around with the code and searching for my own answer because I do want to learn, but I'm not finding what I need.
May you please point me in the right direction as to what I've done improperly?
Thank you so very much!
The code for your reference:
$('#contact_form').submit(function() {
var this_form = $(this);
$.ajax({
type: 'post',
data: this_form.serialize(),
url: 'scripts/send_email.php',
success: function(res) {
if(res == "true") {
$(this_form)[0].reset();
$(".notice").removeClass("error").text("Thank you for contacting us!").addClass("success").fadeIn("fast");
} else {
$(".notice").text("Please check all fields and try again.").addClass("error").fadeIn("fast");
}
}
});
});
try to ask for:
if(res == true)
instead. Also a good way to avoid this kind of problems is to debug your javascript via firebug or the chrome debugger, if you are using chrome you could add this line to your code:
debugger;
if(res == "true")
and the javascript will stop there so you can inspect the variable and see what's happening. you can open it by going to "options --> tools --> developer tools --> scripts".
Hope this helps :)
In your send_email.php file, echo "success" if it succeed.
Then modify your AJAX call like so :
success: function(data) {
if (data == "success") {do stuff} else {do failure stuff}
}
It appears that your truth comparison is returning false due to the value that res represents. You are checking to make sure it is a string with the value of "true". If not, then trigger else code.
Your success property will only be executed if the AJAX transmission was successful. You will want to set the comparison check to the desired output of send_email.php, i.e. 'Success!' or 'Failure!' to indicate the proper handling.
success(data, textStatus, jqXHR)
A function to be called if the request succeeds. The function gets passed three
arguments: The data returned from the server, formatted according to
the dataType parameter; a string describing the status; and the jqXHR
(in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the
success setting can accept an array of functions. Each function will
be called in turn.
See docs for additional information for handling AJAX requests in jQuery.
success: function(res) {
if (res == "Success!") {
$(this_form)[0].reset();
$(".notice").removeClass("error").text("Thank you for contacting us!").addClass("success").fadeIn("fast");
} else {
$(".notice").text("Please check all fields and try again.").addClass("error").fadeIn("fast");
}
}
I know why the post fails, but I'm not sure how to resolve it and I can't find any other references to this. I'm taking our references to jEditable to make this simpler, as it happens without the jEditable plugin.
So how the heck do I "escape" the keyword so that it posts correctly? Here's relevant code:
Test
<script type="text/javascript">
$(function() {
$('#button').click(function() {
$.ajax({
type : 'POST',
url : 'ajax/post_cms.php',
dataType : 'html',
data : {
id : '1',
data : '<p>This is a test of the system that shows me an alert !</p>'
},
success : function(data) {
console.log(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
console.log('An Ajax error was thrown.');
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
});
});
});
</script>
<input type="button" name="button" value="button" id="button" />
When it errors out, it's throwing the "error:" callback function, and the "errorThrown" is logged as undefined. I'm positive it's the word "alert" because if I spell it "allert" in the one place it appears, everything posts just fine. If you take out the HTML (so it's just "data : 'This is a test of the system that shows me an alert !'") it works just fine.
XMLHttpRequest = "XMLHttpRequest readyState=4 status=0 multipart=false"
textStatus = "error"
errorThrown = "undefined"
GAH!! HELP!!
UPDATE:
The problem was a firewall catching the AJAX request as a XSS attack. If you're experiencing problems similar to those exhibited below, make sure to check your environment.
Symptoms:
Post data is failing with an error code of 0
Post data works in other places but not in your environment
Post data works as long as it doesn't contain any javascript functions
Your library doesn't seem like it should be at fault based on documentation
You can't find a bug in your library.
I think there's something else wrong here other than jQuery.
Your initial example works fine for me.
See a working example here: http://jsbin.com/ifami
Note: I had to change your the ajax URL to a valid url but otherwise there were no other changes.
That being said, you could try encoding your values as URI components:
<script type="text/javascript">
$(function() {
$('#button').click(function() {
$.ajax({
type : 'POST',
url : 'ajax/post_cms.php',
dataType : 'html',
data : {
id : '1',
data : encodeURIComponent('<p>This is a test of the system that shows me an alert !</p>')
},
success : function(data) {
console.log(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
console.log('An Ajax error was thrown.');
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
});
});
});
</script>
If it's only the word alert, you could simply change it to something else, like #1234# and then parse it back. It's hacky but a library that crash if you enter "alert" sounds pretty funky to me.
You could also go in the lib code and fix it... or open a ticket and get them to fix it. It sounds to me it's a pretty important issue!
I think maybe your data: parameter needs another set of parenthesis, like so:
data : ({ id : '1',
data : '<p>This is a test of the system that shows me an alert !</p>'
}),