I'm attempting to learn to make use of AJAX. I removed most of the complexity of the program to just isolate the problem I'm having. So I have a text area and beneath that a div that has "STATUS" printing out. On button submit using AJAX I want to change the word "STATUS" to the value of my variable, status, which in this case should be "SUCCESS".
What happens instead when I click is it prints out the word STATUS. It appears like nothing is happening when I click my submit button. Any ideas what I am doing wrong?
$(document).ready(
function () {
$('#sub').live('click',
function () {
url = 'http://whatever.php'
success = "Success!"
$.ajax({
url: url,
type: 'POST',
data: null
dataType: 'xml',
async: false,
success: function (data, statusText, reqObj) {
status = $(data).find('status').text()
if (status == 'SUCCESS') {
$('#succ').html(status)
} //if( status == 'SUCCESS' ) {
else {
msg = $(data).find('msg').text()
alert('NOT ADDED: ' + msg)
return
} // else
} //function()
}) //$.ajax( {
} /* function */ ) //live(
} //function()
) //$(document).ready
HTML:
<div id="buttonArea">
<textarea name="txtarea" cols=80 rows=30>>THIS TEXT BOX
IS USED FOR THINGS I WILL WORK ON LATER
</textarea><br/>
<input type=submit value='Submit Textbox Info!' id='sub'>
</div>
<div class="float-left" id='succ'>STATUS</div>
I think your find is empty. Try to replace with
status = $(data).text()
I'm not sure you use .find() the right way. it's used on html elements and expects to be passed a jquery selector or element or jquery object.
here's more details http://api.jquery.com/find/
what you want is to get your response text, so assign your ajax call to a variable:
xmlhttp = $.ajax({
then on success use your response text:
status = xmlhttp.responseText;
Your code works fine for me, on the proviso that:
(i) you add the missing comma from the line:
data: null,
(ii) the content-type returned by your php handler is text/xml
Related
I have a simple page that takes a form and makes a jsonp ajax request and formats the response and displays it on the page, this is all fine, but I wanted to add it so that if the form was populated (via php $_GET variables) then the form would auto-submit on page load but what happens instead is that the page constantly refreshes despite the submit function returning false.
Submit Button (just to show it doesn't have an id like submit or anything)
<button type="submit" id="check" class="btn btn-success">Check</button>
jQuery
$(document).ready(function() {
$('#my_form').on('submit', function() {
var valid = 1;
$('#my_form .required').each(function() {
if ($(this).val() == '') {
$(this).parents('.form-group').addClass('has-error');
valid = 0;
} else {
$(this).parents('.form-group').removeClass('has-error');
}
});
if (valid === 1) {
$.ajax({
url: '/some_url',
data: $('#my_form').serialize(),
type: 'GET',
cache: false,
dataType: 'jsonp',
success: function(data) {
var html = 'do something with data';
$('#results').html(html);
},
error: function() {
$('#results').html('An error occurred, please try again');
}
});
} else {
$('#results').html('Please fill in all required fields');
}
return false;
});
});
The part I added just after the $(document).ready(function(){ and before the submit was:
if ($('#input_1').val() != '' || $('#input_2').val() != '') {
// $('#check').trigger('click');
$('#my_form').submit();
}
Both those lines have the same effect but I am doing the same in another project and it works fine, as far as I can see, the only difference is the jQuery version, I'm using 1.11 for this page.
Update
Apologies, I seem to have answered my own question, I thought that since the programmatic submit was the first thing in $(document).ready(function(){ then maybe it was the case that the actual submit function wasn't being reached before the event was triggered so I simply moved that block after the submitfunction and it now works fine.
url: ''
it seems like you are sending your ajax request to nothing.
just an additional: if you want to submit your form through jquery without using AJAX, try
$("#myForm").submit();
it will send your form to the action attribute of the form, then redirect the page there.
EDITED
I have a "Save Changes" button that I want to click and toggle a div with the message "Changes saved". I do it like this:
HTML:
<input type="submit" id="savebtn" name="save" value="Save Changes"/>
<input type="hidden" id="res" name="res" value="#ViewBag.result"/>
<div class="success">Changes saved</div>
JQuery
$('#saveButton').click(function () {
var aux = res.value.toString();
if ($('#res').val() == "OK")
$(".success").show();
alert(aux);
});
However, I need the button to actually save the changes and, if the operation was successful, then show the message div. So, in my cshtml file I have a result variable that contains the success or failure of the operation.
CSHTML:
ViewBag.result = result;
Now, I need to show that message div depending on the result variable: I need to somehow make it a parameter for the JQuery function. I'm passing it in a ViewBag.
NOTE: when the page loads, the viewbag is empty. It only gets its value after the button click. And after that, the viewbag is filled and I wanted it to be used in the jQuery function but I'm not getting any luck.
Pass that result in a viewbag,
Acces that viewbag value in jquery and show/hide your div accordingly
Assuming you can store the result in input hidden field, use below query to access result and initially success div is hidden :
<input type="hidden" id="result" value"success"/>
jQuery :
$(function(){
if($('#result').val()=="success")
$(".success").show();
});
you can check it in a simple if condition
if($('#result').val()=="success")
$(".success").toggle();
or You can use Ajax method
function Save() {
$.ajax({
url: "Your Url", // Current Page, Method
data: Your data // better if you parameter map as JSON
type: "POST",
contentType: "application/json", // posting JSON content
dataType: "JSON", // type of data is JSON (must be upper case!)
timeout: 100000, // AJAX timeout
success: function (result) {
$(".success").toggle();
},
error: function (xhr, status) {
alert("An error occurred while processing");
}
});
}
Now call this save() in your button click
I am having a javascript like this which will call two different controller in two diff situation ....
Now the problem is it is one get method and one is destroy method ... when the call is generated, the controller functions never triggered. No idea wheather the url method is right or not. It is giving the 500 error.
I am also not sure about the response back from the controller. but before that I need to execute the database operation in the controller ... which is not going to execute. advance thanks for the help :)
JS code below :-->
function follow_or_unfollow(id,action)
{
//var dataString = "id=" + id;
if( action == "follow" ) {
myUrl = "{{ action('FollowsController#show', 'id') }}" ;
myMethod = "GET";
}
else
{
myUrl = "{{ action('FollowsController#destroy', 'id') }}" ;
myMethod = "DELETE";
}
var dataString = "id=" + id;
$.ajax({
type: myMethod ,
url: myUrl,
//data: dataString,
beforeSend: function()
{
if ( action == "following" )
{
$("#following"+id).hide();
$("#loading"+id).html('<img src="loading.gif" align="absmiddle" alt="Loading...">');
}
else if ( action == "follow" )
{
$("#follow"+id).hide();
$("#loading"+id).html('<img src="loading.gif" align="absmiddle" alt="Loading...">');
}
else { }
},
success: function(response)
{
if ( action == "following" ){
$("#loading"+id).html('');
$("#follow"+id).show();
}
else if ( action == "follow" ){
$("#loading"+id).html('');
$("#following"+id).show();
}
else { }
},
error : function(xhr, textStatus, errorThrown ) {
if (xhr.status == 500) {
alert("Error 500: "+xhr.status+": "+xhr.statusText);
} else {
alert("Error: "+xhr.status+": "+xhr.statusText);
}
},
complete : function(xhr, textStatus) {
allert('ok');
}
});
}
</script>
1st edit
get a point after the firefox tool check up (as suggested by Chinnu)
It is showing
`[18:38:47.658] GET http://localhost/ffdd/public/follows/id [HTTP/1.1 500 Internal Server Error 230ms]`
that means ! the id is not been generated as digit or id variable, it is just going as "id" string. Now need a specific solution , how to send the value of id there .... at the controller througn the JS.
2nd edit
If I put the digit or value of id instead of mentioning it by 'id' that means if the value of id can be print directly there it will work . What will be the easier way to do that ?
myUrl = "{{ action('FollowsController#destroy', <the value of id>) }}" ;
The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
Ref: http://api.jquery.com/jQuery.ajax/
NOTE: You can able to find this errors using in Firefox Tools->Web Developer ->Error Console or CTRL+SHIFT+J
You are trying to access a javascript variable inside a php helper function will not work. I'm not sure what's passing id into that function, but if it's being passed into the view via PHP, then you should use {{ action('FollowsController#show', array($id)) }}
If it's not being passed into the view, then you would have to use myUrl = '/follow/'+id and make sure you have routes for both GET and DELETE.
I have obviously done something stupid or failed to understand some fundamental process. Very early days playing with this.
I am trying to check for a form being validated, when the Submit Button is clicked with the onClick method.
<input class="submit" type="submit" value="Submit" onClick="submitForm()" />
I am using Jquery and the plug-in Validate. The problem I have is validating on each field is occurring, but if I click on submit with no data or not every field has been tested, I would need to validate the whole form, before submitting, I should get a return of false from validate().form(). This is not occurring as the else statement in submitForm() is never being executed.
On an empty form, after clicking submit the field error messages are shown, but my testing of a return for false, does not seem to work.
$(document).ready(function() {
$('#formEnquiry').validate();
});
function submitForm() {
$('#msgid').append('<h1>Submitting Form (External Routine)</h1>');
if ($('#formEnquiry').validate().form()) {
$("#msgid").append("<h1>(Outside Ready) VALIDATED send to PHP</h1>");
}
else {
$('#msgid').append('<h1>(Outside Ready) NOT VALIDATED</h1>');
}
};
An example of Ajax
$(function() {
$("#ipenter").submit(function() {
var ip = $("#ip").val();
var date = $("#date").val();
var spammer = $("#spammer").val();
var country = $("#country").val();
var total = $("#total").val();
var dataString = $('#ipenter').serialize();
$.ajax({
url: "/test/process",
data: dataString,
type: "POST",
success: function(msg) {
$('#ipenter').append('<h3 class="gotin">Post succesfull!');
$('h3.gotin').delay(8000).fadeOut(500);
},
error: function(data){
$('#ipenter').prepend('<h3 class="didnt">Post sucked!');
$('h3.didnt').delay(8000).fadeOut(500);
}
});
return false;
});
});
You dont really even need the val() part
You can also throw some validation into this script before the ajax
if (spammer == "") {
$("#spammer_error").show();
$("input#image").focus();
return false;
This is a basic example of ajax(I'm using codeigniter so you may need to use a valid URL for the url)
So i have this function in JS, sending a request to insert a new Status message to the database.
function DoStatusInsert(){
var wrapperId = '#statusResponseNow';
$.ajax({
type: "POST",
url: "misc/insertStatus.php",
data: {
value: 'y',
uID : $('#uID').val(),
message : $('#message').val()
},
success: function(msg){
$('#message').val("");
$('#statusResponse').toggle();
$(wrapperId).prepend(msg);
$(wrapperId).children().first().fadeIn('slow');
}
});
}
With this form:
<input name="message" type="text" id="message" value="" size="60">
<input type="hidden" name="uID" id="uID" value="<?php echo $v["id"]; ?>">
<input name="submit" type="submit" id="submit" value="Spara">
<div id="statusResponseNow"></div>
Now I wish to do something like blocking the submit button or the message field to "read-only" until you receive response / success, so you don't have the opportunity to like press submit alot of times so it inserts alot.. (i know you could make a php for checking after doubleĀ“s in DB)
So: when you click on submit then it makes either message field and/or submit button to read only
How should i do it?
function DoStatusInsert(){
$('#IdOfYourSaveButton').attr('disabled', 'disabled');
var wrapperId = '#statusResponseNow';
$.ajax({
type: "POST",
url: "misc/insertStatus.php",
data: {
value: 'y',
uID : $('#uID').val(),
message : $('#message').val(),
success: function(msg){
$('#IdOfYourSavebutton').removeAttr('disabled');
$('#message').val("");
$('#statusResponse').toggle();
$(wrapperId).prepend(msg);
$(wrapperId).children().first().fadeIn('slow');
}
});
}
enabled and disable the button. nice and easy :)
On calling the function, set the disabled property of the button, and then set it back on success.
function DoStatusInsert(){
$('#submit').attr("disabled", "true");
var wrapperId = '#statusResponseNow';
$.ajax({
type: "POST",
url: "misc/insertStatus.php",
data: {
value: 'y',
uID : $('#uID').val(),
message : $('#message').val()
},
success: function(msg){
$('#message').val("");
$('#statusResponse').toggle();
$(wrapperId).prepend(msg);
$(wrapperId).children().first().fadeIn('slow');
$('#submit').attr("disabled", "false");
}
});
}
My initial thoughts would be to insert
$('input[type=submit]', this).attr('disabled', 'disabled');
before the ajax call is started and then removed the disabled attribute with the success function of the ajax request.
Manually toggling the disabled state of the button works well enough, but jQuery has a couple helper events to make that a bit nicer: .ajaxStart() and .ajaxStop(). You can use those two handlers on your submit button and not have to worry about maintaining that manual code around your $.ajax() request.
Just throw this in with your other initialization code, probably in $(document).ready():
$('#submit').ajaxStart(function() { this.disabled = true; });
$('#submit').ajaxStop(function() { this.disabled = false; });
You can use for example jQuery BlockUI Plugin from http://jquery.malsup.com/block/ (see demo on http://jquery.malsup.com/block/#element and http://jquery.malsup.com/block/#demos).
If a div with all your form elements which you need to block has id formDiv then you can call
jQuery('#formDiv').block({ message: '<h1>Just a moment...</h1>' });
before jQuery.ajax and call
jQuery('#formDiv').unblock();
as the first line in both success and error handler of the jQuery.ajax.