Having trouble accessing javascript code in a mixed html/js ajax response. jQuery ajax doc states:
If html is specified, any embedded JavaScript inside the retrieved
data is executed before the HTML is returned as a string
Which I can confirm by adding a simple snippet to the html reply:
<script type="text/javascript"> alert($(this)); </script>
How then to retain access to the js code vs. one-and-done execution?? Trying to implement a modal login (to prevent data loss on session timeout in form submission screens). Of course I need to be able to access the ajax'd js code to then validate email/password fields and ajax authenticate user credentials on the remote server.
Here's the modal login coffeescript snippet:
# submit form
$.ajax
success: (data) -> ...
error: (data) ->
popAuth(data.responseText) if(data.status == 401)
popAuth = (title) ->
$.fancybox({
href: "/login"
ajax: { type: "GET" }
title: title
})
Perhaps I can add a success callback to popAuth() ajax options to store the returned js code? How about jQuery "live" handler? Unfortunate that this scenario is not as straight forward as one would hope ;-) I have seen $.getScript as an option, but would prefer to not separate html from js since server-side already assembles html + js and the original ajax call pulls it all down in one go. (i.e. avoid creating a dedicated server-side controller to send back js file content bundle)
I am of course open to alternative solutions to workaround this issue. For example, I could store login fields and js login validation code on every screen (JVM CRUD application living behind WordPress front end so every screen is basically auth required) in a hidden div, and then pop the modal login window "locally", which I assume would get around the annoying one-and-done js execution of remote ajax content.
Anyway, Ideas appreciated! client-side is both wonderfully simple and...horribly complex ;-)
Ok, fending off the veritable deluge of responses, I'll take a stab myself.
As I understand it now, since mixed html/js content is one-and-done executed, we have one chance to capture ajax response js code and bind it to current scope.
First, in the original ajax call (i.e. form submit that returns a potential 401 not authorized status) set the context of the modal login's ajax setup to $(this), the currently executing scope that contains jquery validation and other shared js code needed for modal login ajax submit to work.
In my case, using fancybox, adding context param it now looks like:
popAuth = (title) ->
$.fancybox({
href: "/login"
ajax: { type: "GET" }
context: $(#)
title: title
})
Then, since the parent window contains the majority of needed javascript, the only requirement is to create a js file that binds modal login form button click event to validation and $.ajax submission.
# login.coffee
jQuery ->
$('#loginSubmit').click (e) ->
e.preventDefault()
isValid = $('#loginForm').validate().form()
if isValid
$('#spinner').show()
$.ajax
data: $('#loginForm').serialize()
success: (data) ->
$('#status').fadeOut()
location.href = '/foo'
error: (data) ->
$('#status > div').html( data.responseText )
$('#status').fadeIn()
complete: () ->
$('#spinner').hide()
Done, all good, works ;-)
Related
I have a custom form that posts to a 3rd party server as an appointment booking module. If i submit the form thru the action of the <form> tag i do recieve the email, but i would like to submit the form using $.POST so that i can alter the redirect URL.
I have jQuery running successfully on my site, and if i use:
$.post('URL', {data}).then(function () {alert('Form Submitted!')});
The redirect (or alert for this example) works fine, but the POST doesnt seem to actually run. Has anyone had a similar issue and found a way to resolve this?
ACTUAL CODE
I am using mailthis.to's API to avoid having to run a server just to do this
$('#sendForm').click(()=>{
$.post('https://mailthis.to/support#gadget-pro.com', {
Name:$('#Name').val(),
Email:$('#Email').val(),
Phone:$('#Phone').val(),
Device:$('#device').val(),
Repair:$('#repairType').val(),
Price:$('#price').val()
}).then(function (data) {
location.href = 'https://gadget-pro.com/formconfirm'
});
})
I would say to update your code to return back the page. you are likely not triggering the post to page properly or there is an error.
alos console.log the post data before to know what is being sent.
update your code to
console.log(data);
$.post('URL', {data}).then(function (retpage) {console.log(retpage)});
before we start apologies for the wording and lack of understanding - I am completely new to this.
I am hoping to run a php script using Ajax - I don't need to send any data to the php script, I simply need it to run on button press, after the script is run I need to refresh the body of the page. What I have so far:
HMTL Button with on click:
<font color = "white">Next Question</font>
JS Ajax call:
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'php',
success:function(content,code)
{
alert(code);
$('body').html(content);
}
});
}
this runs the php script but doesn't stay on the current page or refresh the body - has anyone got any ideas - apologies if this is completely wrong I'm learning - slowly.
Many thanks in advance.
**As a small edit - I don't want a user to navigate away from the page during the process
How about using load instead of the typical ajax function?
function AjaxCall() {
$(body).load('increment.php');
}
Additionally, if you were to use the ajax function, php is not a valid type. The type option specifies whether you are using GET or POST to post the request.
As far as the dataType option (which is what I think you mean), The Ajax doesn't care what technology the called process is using (like ASP or PHP), it only care about the format of the returned data, so appropriate types are html, json, etc...
Read More: http://api.jquery.com/jquery.ajax/
Furthermore, if you are replacing the entire body content, why don't you just refresh the page?
your ajax should be
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'post',
success:function(data)
{
console.log(data);
$('body').html(data);
}
});
}
if you want to learn ajax then you should refer this link
and if you just want to load that page then you can use .load() method as "Dutchie432" described.
If you are going to fire a javascript event in this way there are two ways to go about it and keep it from actually trying to follow the link:
<font color = "white">Next Question</font>
Note the return false;. This stops the following of the link. The other method would be:
<font color = "white">Next Question</font>
Note how this actually modifies the href to be a javascript call.
You can study about js and ajax here http://www.w3schools.com/ajax/default.asp will help a lot. Of course all js functions if called from internal js script should be inside <script></script> and if called from external you call the js gile like <script src"somejs.js"></script> and inside js there is no need for <script> tags again. Now all those function do not work by simply declaring them. So this:
function sayHello(){
alert("Happy coding");
}
doesn't work because it is just declared and not called into action. So in jQuery that you use after we declare some functions as the sayHello above we use:
jQuery(document).ready(function($){
sayHello();
});
Doing this we say that when everything is fully loaded so our DOM has its final shape then let the games begin, make some DOM manipulations etc
Above also you don't specify the type of your call meaning POST or GET. Those verbs are the alpha and omega of http requests. Typically we use GET to bring data like in your case here and POST to send some data for storage to the server. A very common GET request is this:
$.ajax({
type : 'GET',
url : someURL,
data : mydata, //optional if you want to send sth to the server like a user's id and get only that specific user's info
success : function(data) {
console.log("Ajax rocks");
},
error: function(){
console.log("Ajax failed");
}
});
Try this;
<script type="text/javascript">
function AjaxCall() {
window.location.reload();
}
</script>
<body>
<font color = "white">Next Question</font>
</body>
i am new to web development creating a kind of social networking website for college project. I want to include update the messages count in the message menu every time there is a new msg in the database for the user(like facebook message menu on homepage)
But it's frustrating learning ajax, however after searching on web and reading some topics from some books I came to the solution that i can make an $ajax call in my js file in the homepage and send data ('name'=>'user') stored in javascript cookie that i have created on loading of home page after the user login, to a php file which will search across the recent_msg table in database to fetch the recent message for the logged in user if any after fetching the php file will create the html file with code snippet and further another jquery code will append that snippet from file to the message list menu.
the PHP part is not the problem but how can i send the username to the php file using jquery ajax api, here is the code what i think i can apply but i am doubtful in that if this is the correct way
$(document).ready(function{
setInterval ( function()
{
var usr = getCookie("name");
$.ajax ( {
url: '/phpScripts/recent_msg.php',
type: 'POST',
data: usr,
success: function(data){
}
} );
},10);
});
what is the purpose of success function in the code?
data needs to be in the form of an object / key-value-pair (EDIT: or if a string, as a valid querystring). data: { name: usr }. However, since it's in a cookie, your PHP page will have direct access to that cookie. It's safer to let your session cookie tel the PHP page who the user is instead of relying on an AJAX call to tell the PHP page who it is.
http://php.net/manual/en/features.cookies.php
So I'd drop data from your AJAX call altogether, and in your PHP page, use $_COOKIE["name:"]
Then whatever HTML gets passed back from the PHP page will arrive in the data call. If it's HTML, then simply add it to your HTML to some message div, such as.
<div id="recent-messages"></div>
<script type="text/javascript">
$(document).ready(function{
setInterval ( function()
{
var usr = getCookie("name");
$.ajax ( {
url: '/phpScripts/recent_msg.php',
type: 'POST',
data: usr,
success: function(data){
$('#recent-messages').html(data);
}
} );
},10);
});
</script>
The success function executes whenever your ajax call completes successfully. This means that the page actually exists and no server-side errors occurred on the page. The variable data will contain whatever information is returned from the page on the sever /phpScripts/recent_msg.php. Generally this is either json or xml, but it entirely depends on your implementation of recent_msg.php.
If the user has to log in that means you have to have created a session. In that case you can store the logged in user's information such as their name in $_SESSION on the server and there is no need to store it as a cookie. Since $_SESSION is already on the server, there is no need to send that data via ajax in any case.
Environment:
Windows 8
Apache 2.4
ZF 1.12
PHP 5.4
YUI framework for the behind-the-scenes connection to the server
I am trying to carry out a very simple ajax/js combination where the user interacts with:
2 of 4 people found this review helpful. Was this review helpful to you? Yes No
When the user hits either yes/no the 2 of 4 should be updated through ajax/js. I have the following code in the init() method of my ReviewController (extends Zend_Controller_Action). Mind you, the view script that follows this action (feedbackAction) is /views/scripts/review/feedback.json.phtml
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('feedback', 'json')
->initContext();
When feedbackAction is executed an exception jumps out stating that it could not find feedback.phtml. This is telling me that AjaxContext is not, in effect, appending the "json" format. Why is this happening?
I read somewhere that the initContext() should be called inside the action. I tried it...same exception.
Then I tried using ContextSwitch, but it seems that it beats the purpose of having AjaxContext be a subclass of ContextSwitch. The code in the init() in ReviewController was replaced by:
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$contextSwitch->addActionContext('feedback', 'json')
->initContext();
This time, inexplicably, the exception does not occur, but instead the following is rendered: the header code (generated by my _header.phtml file called by my layout.phtml file). I don´t understand at all. I had understood (obviously not well) that "addActionContext"+initContext() DISABLED layouts if any was enabled. ¿?
EDIT
I figured out that it wasn´t html content form my _header.phtml file but from another .phtml file that was being rendered because of some actions I had added to my actionStack. Once this was taken care of, what was rendered was the following:
{"originalModule":"default","originalController":"review","originalAction":"feedback","result":true,"id":1,"helpful_yes":"3","helpful_total":"4"}
Which is the variables placed in the $this->view being rendered as json thanks to ContextSwitch helper initiated at the init() method of my ReviewController(). When I say "this was rendred" is because I placed in the address bar the following url: http://localhost/PlacesforKids/public/review/feedback/format/json/id/1/helpful/1
which supposedly is the URL being sent by the YUI framework.
I say "supposedly" because in my javascript success function (being called back by the YUI framework when the ajax call is being executed successfully) I do the fowlling: alert(response), to print out the responce I am getting...and it prints out the whole shabang: html tags, headers...etc. I don´t know how that´s possible.
I thought then that I might be misusing the YUI framework, so I tried to change to jquery.js. To do so I copied the contect of this to a file named jquery.js and placed it under my /public/js directory. Here is the ajax call it´s making to the server:
$.ajax({
url: sUrl,//that would be
//localhost/PlacesforKids/public/review/feedback/format/json/id/$id/helpful/$helpful
type: "GET",
async: false,
success: function(response){
alert(response);
}
});
Here is the HILARIOUS part of all, the action for my ReviewController is NOT being called whatsoever. Instead, the view that was last rendered is re-rendered, meaning it´s re sending the content generated by the view script called by the last action (which belongs to a different controller than ReviewController). I know it´s been re-rendered because in the action that´s the owner of that view script I added this:
if($this->getRequest()->getQuery('ajax') == 1)
throw new Exception ("WRONG controller's action being called");
But it never throws the exception.
EDIT I THINK I GOT IT but I need to know how to clean the baseUrl()
So I opened up the java console on my chrome browser so I could look up the actual http request that my reviewFeedback.js was making through the $.ajax() method. Funny thing, this is what I got:
Request URL:http://localhost/PlacesforKids/public/place/index/id/localhost/PlaceforKids/public/review/feedback/format/json/id/1/helpful/0
Request Method:GET
Status Code:200 OK
Accept:*/*
Referer:http://localhost/PlacesforKids/public/place/index/id/1
X-Requested-With:XMLHttpRequest
WHY in the world is $ajax() APPENDING the url I have as GET to the EXISTING url? It means that whatever url I am trying to generate through my $.ajax() is gettign APPENDED to my "referer". So, I only need to be to CLEAN it and start from zero, for the url I mean... How could I do that in zend framework? Any ideas?
Now if I enter the string in sUrl (localhost/PlaceforKids/public/review/feedback/format/json/id/1/helpful/0) directly onto the address bar in my broswer, it does as it is supposed to do, print out the variables in $this->view that have been set by ReviewController, and send them as json.
{"originalModule":"default","originalController":"review","originalAction":"feedback","result":true,"id":1,"helpful_yes":"3","helpful_total":"4"}
Same problem I had with YUI framework. I´m going crazy.
I could really use the help, thank you.
You need to change the ajax request to asynchronous mode: async: true
Silly silly silly me. Here is the reason why $.ajax() was appending the made up url instead of sending a new one.
$.ajax({
url: sUrl,//that would be
//localhost/PlacesforKids/public/review/feedback/format/json/id/$id/helpful/$helpful
type: "GET",
async: false,
success: function(response){
alert(response);
}
I was writing a GET without a leading "http://", which by default, caused it to append to the existing url.
sUrl was localhost/PlacesforKids/public/review/feedback/format/json/id/$id/helpful/$helpful
and should have been http://localhost/PlacesforKids/public...
Though it still baffles me that ajaxContext did not stop layout rendering as it should have, making me use switchContext instead.
The ajax switch in zend 1.1x.x is only for the "special" html context (if memory serves) and you were trying to set it to a json context.
there is any sample showing how to use the blobstore api with ajax?
when i use forms works fine, but if i use jquery i don't know how to send the file and i get this error:
blob_info = upload_files[0]
IndexError: list index out of range
I have this code in javascript
function TestAjax()
{
var nombre="Some random name";
ajax={
type: "POST",
async:true,
//dataType:"json",
url:"{{upload_url}}",
data:"nombreEstudio="+nombre,
error: function ()
{
alert("Some error");
$("#buscando").html("");
},
success: function()
{ alert("it's ok") }
};
$.ajax(ajax);
}
When i use forms the file it's sended with a input tag (exactly like the doc's sample)
I wrote a series of posts about exactly this.
Somehow you still need to get the multipart form data request to the server... so when you're using forms, I assume your <form> tag has something like this on it: enctype="multipart/form-data", right?
When you're just sending a "POST" via ajax, you're losing that multipart request, which is where your file is.
There are some jQuery "ajax file upload" plugins out there that may help you out.
Hope this helps!
** EDIT **
I guess one thing I can add to this is usually ajax file uploads (on the client) are implemented by either creating a hidden iframe, and using that iframe to submit a form, or using a form and posting it via JavaScript.