I have an ajax function, which on success redirects to the response returned from the url:
document.getElementById("button1").addEventListener("click", function (e) {
e.preventDefault();
$.ajax({
url: 'http://localhost:8080/someLoginUrl',
method: 'GET',
crossDomain : true,
xhrFields: {
withCredentials: false
},
success: function(response){
window.location.href = response;
}
});
});
The response, which is returned by http://localhost:8080/someLoginUrl is just a webpage, containing a url:
This is the html of the response page:
<html><head></head><body>https://localhost:8080/anotherLogin</body></html>
So, once I click my button button1, instead of redirecting to http://localhost:8080/someLoginUrl, it redirects to https://localhost:8080/anotherLogin, which is the desired behavior for me.
However, I want to do a small manipulation on the response inside the success function - I want to change the protocol from https to http. How do I do that?
I tried response = response.replace('https', 'http'); but this did not change anything.
May Be I understand your Question ! You want your success Response data to your Same page where this action took place
First You have to create a dive with id <div id=res_data> </div> and place this div where you want to show your response data .
Then Your Final code is
document.getElementById("button1").addEventListener("click", function (e) {
e.preventDefault();
$.ajax({
url: 'http://localhost:8080/someLoginUrl',
method: 'GET',
crossDomain : true,
xhrFields: {
withCredentials: false
},
success: function(response){
$('#res_data').val(response);
}
});
});
Tuned me if you not find this helpful .
Related
So I am dealing with this weird service when returns a html page as the ajax response which has a form and the form is triggered automatically by some scripts in the page (so when you render the page a post request will be sent to you). What I am trying to do is to load this page I am getting from the response.
Say this is my Ajax call:
var ajax_call_test = function() {
var formData = new FormData($('#documentForm')[0]);
console.log("doc form: " + formData);
$.ajaxSetup({
xhrFields: {
withCredentials: true
}
});
$.ajax("/documents/upload/", {
type: 'POST',
data: formData,
processData: false,
contentType: false,
cache: false,
async: false,
dataType: 'html',
success: function(html){
// ?
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("failed: " + errorThrown);
}
});
}
So I tried to use .html to set the response to a hidden <div>. It sets the html but never triggers the form. I am guessing the javascript in that page is not loaded when I use .html.
I also cannot use jQuery.parseHTML() since the version of library I am using does not support that functionality. Any idea what should I do with response?
When ever you load new html into the DOM. The javascript does not know about it.
I have to re invoke my javascript to work with the new DOM.
Lets say I have some click events
$(function(){invokeClicks()}) // onload call
function invokeSomeAction(){
$("selector").off(); // disable previous events from old html
$("selector").on("event", function(){
// handle event
})
}
function invokeClicks(){
invokeSomeAction();
// ... etc
}
So when this JS loads, the invokeClicks() method gets called.
Now, if I replace the HTML through a $.ajax() call, all I have to do is call invokeClicks() again to clear the old events and now the new HTML will work with the javascript
$.ajax({
url: "somepath",
data: {id: 1},
method: "GET",
success: function(html){
$("container_selector").html(html);
invokeClicks(); // reinit
},
})
For a university homework, I have to create a little e-commerce website.
After the login, the user is redirected to the homepage. In this homepage, the client will recive a JSON object from the server (containing some product to be loaded) to generate the DOM of the homepage dynamically.
Note: I must use AJAX and JSON
I have this client.js file:
$(document).ready(function() {
// AJAX request on submit
$("#login_form").submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "submit.php",
data: {
Email: document.getElementById('login_email').value, // Email in the form
Password: document.getElementById('login_password').value // // Password in the form
},
cache: false,
success: function(){
window.location.href = "home.php"; // load the home.php page in the default folder
}
});
});
});
$(document).ready(function() {
// AJAX request to open a channel between php and client
function (e) {
e.preventDefault();
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
var data = JSON.parse(data);
alert(data); // debug
showProducts(data);
});
});
});
});
function showProducts(data){
alert(data);
// Insert object into the page DOM
}
I don't know why, but I can't access after the login if the second Ajax request (the AJAX request to open a channel between php and client) is not commented, and I don't know why, because the code seems right... Any suggestion?
after login action you need to set to cookie token in response
success: function(response){
console.log(response)
// then set to cookie response.token
window.location.href = "home.php";
}
after set token to cookie, you need to send this token to next ajax request url: "queries.php",
You need to wrap your anonymous function in parenthesis and add () at the end if you want to execute it:
(function (e) {
// I don't know why you need this:
e.preventDefault();
// etc.
})();
You should also check the contents of that function as you seem to have too many closing parentheses and you don't need to parse the returned value if you set the dataType to json.
In the end I think this is about all you need for that function:
(function () {
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
console.log(data); // debug
showProducts(data);
}
});
})();
or just:
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
console.log(data); // debug
showProducts(data);
}
});
To get it directly on page load.
I am having trouble getting an ajax GET request (or any request for that matter) to retrieve the response. I am simply trying to return the response in an alert event:
<script>
$(document).ready(function() {
$('#test').click(function() {
$.ajax ({
type: 'Get',
url: 'https://crm.zoho.com/crm/private/json/Potentials/searchRecords?authtoken=XXX&scope=crmapi&criteria=(((Potential Email:test#email.com))&selectColumns=Potentials(Potential Name)&fromIndex=1&toIndex=1',
dataType: 'json',
success: function(data) {
alert(data);
}
});
});
});
</script>
I can get this and other similar post requests to work by taking away the function in the success option and editing the code like this:
<script>
$(document).ready(function() {
$('#test').click(function() {
$.ajax ({
type: 'Get',
url: 'https://crm.zoho.com/crm/private/json/Potentials/searchRecords?authtoken=XXXX&scope=crmapi&criteria=(((Potential Email:test#email.com))&selectColumns=Potentials(Potential Name)&fromIndex=1&toIndex=1',
dataType: 'json',
success: alert('success')
});
});
});
</script>
Why is this? And more importantly, how can I retrieve the response data and transfer it to an alert message? Any help is appreciated!
** Update:
Upon reading the first two users' responses on this question, this is what I have:
<script>
$(document).ready(function() {
$('#test').click(function() {
$.ajax ({
type: 'GET',
url: 'https://crm.zoho.com/crm/private/json/Potentials/searchRecords?authtoken=418431ea64141079860d96c85ee41916&scope=crmapi&criteria=(((Potential%20Email:test#email.com))&selectColumns=Potentials(Potential%20Name)&fromIndex=1&toIndex=1',
dataType: 'json',
success: function(data) {
alert(JSON.stringify(data));
},
error: function(data) {
alert(JSON.stringify(data));
}
});
});
});
</script>
I am able to get the error response, so I can confirm there is some kind of error. I also want to point out that I am making the request from a different domain (not crm.zoho.com) so should I be using jsonp? If so, how would I alter the code?
When you have
success: alert('success')
you do NOT have a successful request, you are actually executing this function at the start of AJAX method. The success parameter requires a pointer to a function, and when you use alert('success') you are executing a function instead of providing a pointer to it.
First thing that you need to try is to update type to GET instead of Get:
$.ajax ({
type: 'GET',
Try using the .done() function as follows:
<script>
$(document).ready(function() {
$('#test').click(function() {
$.ajax ({
type: 'Get',
url: 'yourUrl',
dataType: 'json',
}
}).done(function(result) {alert(data);}) //try adding:
.error(function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);})
});
});
the error function will also give you some information in your console as to the status of your request.
I have the below code in page1.jsp.
$.ajax({
type: "post",
url: "page2.jsp",
data: newdata,
success:function(msg){
return msg;
}
})
Even after POST request, the page remains in page1.jsp and doesn't navigate to page2.jsp. I am seeing statusCode as "200 OK" when I did inspect element. How should I pass the control to page2.jsp if the AJAX call is success. If I am missing some code please correct me.
If you want to navigate to the page you made the post to if the post success, you need to navigate in the success function
$.ajax({
type: "post",
url: "page2.jsp",
data: newdata,
success:function(msg) {
window.location = "page2.jsp";
}
})
I have the following code:
$("form").submit(function()
{
//Checking data here:
$("input").each(function(i, obj)
{
});
alert(JSON.stringify($(this).serializeArray()));
var url='http://127.0.0.1:1337/receive';
$.ajax({
url: url,
type: 'POST',
contentType:'application/json',
data: JSON.stringify($(this).serializeArray()),
dataType:'json'
});
});
And after I submit the form, I get a JavaScript alert with the json string, so that is made correct (on my server I only log it so it does not matter what it is in it). If I try to send a request to the same link from postman it works, it logs it.
I think I'm doing something wrong in the ajax call, but I am not able to figure out.
Try below piece of code. Add success and error handler for more details
$("form").submit(function()
{
//Checking data here:
$("input").each(function(i, obj)
{
});
alert(JSON.stringify($(this).serializeArray()));
var url='http://127.0.0.1:1337/receive';
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify($(this).serializeArray()),
dataType:'json',
success : function(response) {
alert("success");
},
error: function (xhr, status, error) {
alert(error);
}
});
});
data:{ list : JSON.stringify($(this).serializeArray())}
From the Jquery docs:
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
crossDomain attribute simply force the request to be cross-domain. dataType is jsonp and there is a parameter added to the url.
$.ajax({
url:'http://127.0.0.1:1337/receive',
data:{ apikey: 'secret-key-or-any-other-parameter-in-json-format' },
dataType:'jsonp',
crossDomain: 'true',
success:function (data) {alert(data.first_name);}
});