JQuery post not working in document but is working in console? - ajax

I have a page which needs to use $.post() but for some reason the exact code works when I run it from the firebug console but not from my script? My script is:
$(document).ready(function () {
$('#dl_btn').click(function () {
$.post(
"news_csv.php",
$("#dl_form").serialize(), function (data) {
alert('error');
if (data == 'success') {
alert('Thanks for signing up to our newsletter');
window.open("<?php echo $_GET['link']; ?>");
parent.Shadowbox.close();
} else {
alert(data);
}
});
});
});
It isn't the link as that does get printed properly but it gives me an error on line 140 of jquery min, I have tried using different versions of jquery and to no avail. I really dont understand why this isn't working.
When I changed from $.post to $.ajax and used the error callback I did receive an error of 'error' and the error is undefined?
Don't suppose anyone has any ideas? Would be much appreciated.
Thanks,
Tom

Is your click button placed inside a form element?
Cause doing so, clicking on it will not only trigger the onClick event you have binded to, but form submit as well, so you will end up in a case where your browser is executing both requests in parallel - with unpredicted outcome, of course.
I tried the same code with an element that does not trigger form submit and it worked as expected.
One point though: if you plan to use simple string as a return value and to do something with it (display it or so) then is ok to do what you do right now. However, if you have more complex response from the ajax request, you should specify the response type (xml, json..) as the last parameter of the post method.
Hope this helps.

Related

jQuery Mobile 1.4+ pagecontainerbeforechange bug?

I am experimenting with the new way of handling page events in jqM and have run into a curious issue. When handling the pagecontainerbeforechange event
$(document).on('pagecontainerbeforechange',function(e,u){test(e,u,'changing');})
function test(e,u,msg){console.log($(u.toPage));}
Attempting to put a jQuery object wrapper around u.toPage - as done above - produces strange behavior.
Check out this fiddle to see what I mean
Click on the Second Page button and then view the console. Nothing will happen (the second page is not shown) and you will see a message along the lines of *Uncaught error:syntax error, unrecognized expression http://jsfiddle.net/egn7g5xb/1/show/#second
Now comment out Line 7 and run the fiddle again. No such issue this time and the second page gets shown.
Perhaps someone here might be able to explain what is going on here?
On initial run, jQuery Mobile creates a fake page before navigating to first page in DOM. At that stage, pagecontainerbeforechange fires twice and returns .toPage as an object.
Later on, upon navigating to other pages, it fires twice again; however, it returns a string first time (URL/hash) and second time it returns an object which is the page itself.
Therefore, when using that event, you have to determine whether .toPage is an object or a string.
$(document).on("pagecontainerbeforechange", function (e, data) {
if (typeof data.toPage == "string") {
/* parse url */
}
if (typeof data.toPage == "object") {
/* manipulate page navigating to */
}
});
Note that pagecontainerbeforetransition is similar to beforechange, however, it fires once and returns .toPage as an object.
First, create your pagecontainer events within $(document).on("pagecreate", "#first", function(){ .. }).
Then the selector for these events should be $(":mobile-pagecontainer") or $("body") NOT $(document).
function test(e,u,msg)
{
console.log(msg);
var IsJQ = u.toPage instanceof $;
console.log(IsJQ);
if (IsJQ){
console.log(u.toPage.data());
} else {
console.log(u.toPage);
}
console.log('---');
}
$(document).on("pagecreate", "#first", function(){
$(":mobile-pagecontainer").on('pagecontainerbeforechange', function (e, u) {
test(e,u,'changing');
});
$(":mobile-pagecontainer").on('pagecontainerchange',function(e,u){
test(e,u,'changed');
});
});
Updated FIDDLE

using an ajax request in the success function of another ajax function

I'm adding some custom JS to an application built in Wordpress to set appointments so that if an appointment request is made, both the client and worker are sent request emails. The appointment is made by pressing a button, and the request is made by binding the button to the .click() event.
To send the emails, I put the ajax function inside the success function of the first ajax function to approve the appointment, so that if the appointment was approved, the emails are sent. I was trying to set this up, but found that no matter what I did, the second ajax function inside the success function wouldn't fire, and it wouldn't even correctly report what the error was.
To test to see if this was the ajax function itself that was at fault, I took it out of the success function and put it within $(document).ready(function() { }), binding it to a different event to see if it would fire - and it did. So the function itself is not the problem, but rather that it is inside the success function of another ajax request.
What should I do to get this to fire? Other suggestions on Stack Overflow are very confusing at best, so please pardon me for asking again, but there doesn't seem to be a clear satisfactory answer to this.
This is the code that I put within the first ajax request's callback function, which worked perfectly well when I took it outside the callback function and bound it to a different eventy.
$.ajax({
type: "POST",
dataType: "JSON",
url: "[home url]/wp-admin/admin-ajax.php",
data: "action=finchJsonTest",
success: process_lesson_request,
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
alert("Something\'s not right!");
}
});
function process_lesson_request(data) {
alert("Hooray!");
console.log(data);
}
And this is the php function that Wordpress calls to handle this ajax request (determined by the "action" variable in the data string) - there's nothing too important going on, I was just testing to see if it would successfully return a JSON object
function finchJsonTest() {
$json_array[] = 'This is something!';
$finaljson_array = json_encode($json_array);
echo $finaljson_array;
die();
}
add_action( 'wp_ajax_nopriv_finchJsonTest', 'finchJsonTest' );
add_action( 'wp_ajax_finchJsonTest', 'finchJsonTest' );
Again, if I use this ajax call on its own bound to some event, it works perfectly and returns the desired JSON object (just text saying 'this is something'), but if I put this in the success callback function of another ajax request, it fails, and does not even throw what the error is. I have in fact read other Stack Overflow posts related to this, and wasn't able to make heads or tails of what to do. Any thoughts out there?

jQuery get() not triggering on click, no errors in console

I'm banging my head against the wall here, and hoping I'm just blind to something obvious.
I have this DOM structure:
<ul>
<li>
<h3>Lorem ipusm</h3>
<p class="remove-story">Delete</p>
</li>
</ul>
And this is my jQuery:
$(".remove-story a").click(function()
{
var parent = $(this).closest('li');
$.get($(this).attr('href'), function()
{
$(parent).fadeOut();
});
return false;
});
As it stands, clicking on the link within .remove-story does nothing, and the action triggered by the URL in the link does not occur either.
No JS errors pop-up in the console either on page load or when clicking the link.
If I remove the $.get function and simply fade out the list item, that works as expected.
If I visit the URL manually (or remove the return false and click the link), the link works and the back-end action completes (story removed).
Is there an error in my code here that anyone can spot? If not, any ideas as to where to look next to troubleshoot this?
I would firstly check if that get request really been send our, I mean using some tool like Fiddler or Chrome developer tool network tab, and then maybe add break point inside the call see if the parent you in that certain context is nothing or a wrong object
Wrap your onclick with $(document).ready(function() {}):
$(".remove-story > a").click(function(e)
{
var parent = $(this).closest('li');
alert($(this).attr('href'));
$.ajax({
url: $(this).attr('href'),
success: function() {
alert(12);
$(parent).fadeOut();
},
error: function(e) {
alert('baaaahhhh:' + e);
}
})
//e.stopPropagation();
return false;
});
​
Update: Changed $.get to $.ajax to see if thrs error while doing Ajax request.
You need to encode your link encodeURIComponent($(this).attr('href'));
Here is a jsfiddle working:
http://jsfiddle.net/9Wnt8/

AJAX jQuery form submission with HTML in form

I'm not terribly experienced with AJAX and so am using some tools and attempting to integrate and customize them. First, this is a wordpress site using an AJAX form to submit a post. It all works great! Now, of course, I have to add a WYSIWYG editor to the mix and need to figure out how to get the html content to submit properly.
Here's the submit code:
jQuery("form.pfs").submit(function() {
// vvv I ADDED THIS LINE!!! vvv
jQuery('textarea#postcontent').val(jQuery('div.workzone iframe').contents().find('body').html());
jQuery(this).ajaxSubmit({
type: "POST",
url: jQuery(this).attr('action'),
dataType:'json',
beforeSend: function() {
jQuery('.pfs-post-form #post').val('posting...');
},
complete: function(request,textStatus,error) {
data = jQuery.parseJSON(request.responseText);
if (data && data.error) {
jQuery('#pfs-alert').addClass('error').html('<p>'+data.error+'</p>').show();
jQuery('.pfs-post-form #post').val('Post');
} else {
jQuery('form.pfs').reset();
location.reload();
}
}
});
return false;
});
As you can see, I've added that first line where I take the content of the HTML in the WYSIWYG (http://elrte.org/) and set it as the value of what would have been the original textarea (#postcontent).
The AJAX works perfectly if there's an error, so it is only the "else" portion of the routine that is throwing the error:
Uncaught SyntaxError: Unexpected token < jquery.js:2
e.extend.parseJSON jquery.js:2
jQuery.submit.jQuery.ajaxSubmit.complete pfs-script.js:31
F
So as you see, I need to validate for malicious code (not part of this help request!!) but more importantly I just want to be able to accept HTML in my form posts. Ideas? I am not 100% sure I understand what is failing and where...
turns out there was a conflict with another Plugin. tracing out the request.responseText revealed it. This code works just fine.

Running a javascript after ajax load

I'm using jQuery UI. I'm loading some content in a dialog box over AJAX. After inserting the content from the server, I need to make modifications to the document. I am using the .live() function on my link; I thought this would enable me to use Js after loading the content over ajax, but it's like the content I just loaded isn't a part of the document. Any help very much appreciated.
Are you adding the bindings (lives) in the success function of the ajax call?
If so I had the same issue, I'll try to explain what I figured out:
$.post('callURL', function(data){
// Let's say data returned from server is an ID of a div I have to hide
// by clicking on some_link
$('#some_link').live('click',function(){
$('#'+data).hide();
});
});
This won't work because the code inside the 'live' function is executed on click and at that time the 'data' value is gone.
To make it work I made a global variable 'ID' which I set in the success function and then called in the 'live' function again like this:
var ID;
$.post('callURL', function(data){
// Let's say data returned from server is an ID of a div I have to hide
// by clicking on some_link
ID = data
$('#some_link').live('click',function(){
$('#'+ID).hide();
});
});

Resources