I need to redirect to a page from response. I made a ajax call and can handle success. There is html page in response, but how to redirect it to that page.
Here's my code.
$("#launchId").live('click',function(){
var id= $("#id").val();
var data = 'id='+id;
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'json',
complete : function(response) {
window.location.href = response;
}
});
});
Not using ajax would make this easier:
<form type="POST" action="xyz.json">
<label for="id">Enter ID:</label><input id="id" name="id">
<button type="submit" id="launchId">Send</button>
</form>
If you really want to use ajax, you should generate a distinct server response, containing only the HTML parts you want to update in your page or actual JSON.
If you insist on using the response which you currently get, the appropriate way of dealing with it would be document.write:
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'html', // it's no JSON response!
success: function(response) {
document.write(response); // overwrite current document
},
error: function(err) {
alert(err+" did happen, please retry");
}
});
Please try this.
var newDoc = document.open("text/html", "replace");
newDoc.write(response.responseText);
newDoc.close();
Your response is an object containing the full HTML for a page in the responseText property.
You can probably do $(body).html(response.responseText); instead of window.location.href = ...; to overwrite the current page content with what you got a response.
...
complete : function(response) {
$(body).html(response.responseText);
}
But i suggest you don't and there could be style and other conflicts with whats already there on the page.
In your HTML add a div with id as 'content', something like this
<div id='content'/>
Since your response is html in your complete function append the content into the div like this -
complete : function(response) {
$('#content').append(response.responseText);
}
Let me know if you still face issues.
try this
$("#launchId").live('click',function(){
var id= $("#id").val();
var data = 'id='+id;
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'json',
complete : function(response) {
window.location.href = '/yourlocation?'+response;
}
});
});
Related
is it possible to call a page of another website from an ajax call ?
my guess is that is possible since connection is not denied , but i can't figure out how to make my ajax call works , I am calling a list of TV Channels of a website , but I am getting no results , would you please see if my script contains any errors
function showValues(){
var myUrl="http://www.nilesat.com.eg/en/Home/ChannelList";
var all = 1;
$.ajax({
url: myUrl+"&callback=?",
data: "channelType="+all,
type: 'POST',
success: function(data) {
$('#showdata').html(data);
},
error: function(e) {
alert('Error: '+data);
}
});
}
showValues();
html div for results
<div id="showdata" name ="showdata">
</div>
Ajax calls are not valid across different domains.you can use JSONP. JQuery-ajax-cross-domain is a similar question that may give you some insight. Also, you need to ensure thatJSONP has to also be implemented in the domain that you are getting the data from.
Here is an example for jquery ajax(), but you may want to look into $.getJSON():
$.ajax({
url: 'http://yourUrl?callback=?',
dataType: 'jsonp',
success: processJSON
});
Another option is CORS (Cross Origin Resource Sharing), however, this requires that the other server to enable CORS which most likely will not happen in this case.
You can try this :
function showValues(){
var myUrl="http://www.nilesat.com.eg/en/Home/ChannelList";
var all = 1;
$.ajax({
url: myUrl,
data: channelType="+all,
type: 'POST',
success: function (data) {
//do something
},
error: function(e) {
alert('Error: '+e);
}
});
}
$(".content-short").click(function() {
$(".content-full").empty();
var contentid=$(this).parent().find(".content-full").attr('data-id');
var content=$(this).parent().find(".content-full");
alert(contentid);
var collegename = $(this).attr('data-id');
$.ajax({
type: "post",
url: "contenthome.php",
data: 'collegename=' + collegename,
dataType: "text",
success: function(response) {
$content.html(response);
}
});
});
here the alert displays the specific data-id but
content=$(this).parent().find(".content-full");
this didn't displays data in content-full div with that specific data-id
anything wrong in the code or something else?
the query displays data if i use(."content-full"); instead of
$(this).parent().find(".content-full");
Inside the ajax callback you are using $content, but you declare your variable as content. May that be the problem?
Your question is not clear. What are you trying to achieve?
alright, I have a popup which displays some notes added about a customer. The content (notes) are shown via ajax (getting data via ajax). I also have a add new button to add a new note. The note is added with ajax as well. Now, the question arises, after the note is added into the database.
How do I refresh the div which is displaying the notes?
I have read multiple questions but couldn't get an answer.
My Code to get data.
<script type="text/javascript">
var cid = $('#cid').val();
$(document).ready(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "ajax.php?requestid=1&cid="+cid,
dataType: "html", //expect html to be returned
success: function(response){
$("#notes").html(response);
//alert(response);
}
});
});
</script>
DIV
<div id="notes">
</div>
My code to submit the form (adding new note).
<script type="text/javascript">
$("#submit").click(function() {
var note = $("#note").val();
var cid = $("#cid").val();
$.ajax({
type: "POST",
url: "ajax.php?requestid=2",
data: { note: note, cid: cid }
}).done(function( msg ) {
alert(msg);
$("#make_new_note").hide();
$("#add").show();
$("#cancel").hide();
//$("#notes").load();
});
});
</script>
I tried load, but it doesn't work.
Please guide me in the correct direction.
Create a function to call the ajax and get the data from ajax.php then just call the function whenever you need to update the div:
<script type="text/javascript">
$(document).ready(function() {
// create a function to call the ajax and get the response
function getResponse() {
var cid = $('#cid').val();
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "ajax.php?requestid=1&cid=" + cid,
dataType: "html", //expect html to be returned
success: function(response) {
$("#notes").html(response);
//alert(response);
}
});
}
getResponse(); // call the function on load
$("#submit").click(function() {
var note = $("#note").val();
var cid = $("#cid").val();
$.ajax({
type: "POST",
url: "ajax.php?requestid=2",
data: {
note: note,
cid: cid
}
}).done(function(msg) {
alert(msg);
$("#make_new_note").hide();
$("#add").show();
$("#cancel").hide();}
getResponse(); // call the function to reload the div
});
});
});
</script>
You need to provide a URL to jQuery load() function to tell where you get the content.
So to load the note you could try this:
$("#notes").load("ajax.php?requestid=1&cid="+cid);
I'm using onload() and ajax to get the array from php, but it didnt work. The html page should be able to get the array from n1.php and alert("GOOD"), but it's not giving any response, not even alerting GOOD or BAD so i really dont know what's wrong with the code. How can I fix this??
n1.html:
<!DOCTYPE html>
<html>
<body onload="getArr();">
here
</body>
<script type="text/javascript">
function getArr(){
alert('return sent');
$.ajax({
url: "n1.php",
dataType: 'json',
success: function(json_data){
var data_array = $.parseJSON(json_data);
var rec = data_array[0];
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
}
</script></html>
n1.php:
<?php
$output = array("cat","dog");
echo json_encode($output);
?>
The request must contains the type of request. Also the dataType refers on data you are going to send,as long as you don't send any data, it does not need here.
Try this:
$.ajax({
url: "n1.php",
type: "GET",
success: function(json_data){
var data_array = $.parseJSON(json_data);
var rec = data_array[0];
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
Try this
$.ajax({
url: "n1.php",
dataType: 'json',
success: function(json_data){
var data_array = json_data; // Do not parse json_data because dataType is 'json'
var rec = data_array[0];
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
Now, two things to note here:
You have not passed HTTP Method in the ajax but by default it is GET as mentioned here in jQuery AJAX docs. Please pass appropriate method type if it is not GET.
Since you have sent dataType as 'json', you need not parse json received in the response in success handler.
The title is quite self-explanatory: I need to read a HTML file through jQuery and store its contents into a string variable.
I tried using .load and $.get, but they wouldn't do what I needed.
This is the code I've tried so far, based on the comments below, but they didn't populate my template variable at all:
var template = "";
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
success: function(html) {
var twig = String(html);
template.concat(twig);
}
});
console.log(template);
AND:
var template = "";
var fileUrl = "includes/twig/image_box.twig";
jQuery.get(fileUrl).then(function(text, status, xhr){
var html = String(text);
template.concat(html);
// console.log(html); // WORKS!
});
console.log(template); // Does not work
It's weird why this isn't working. Weird for me at least. This is how I'd populate a variable in PHP so I've carried the same logic to JS. Maybe there is an alternative way?
P.S:V I've also tried all alternative ways, like concatenating with += and assigning inside the callback function to template with =, but nothing worked.
Thanks to the ones who are trying to help me!
Maybe you should try a AJAX request with $.ajax()
Check the jQuery API here
$.ajax({
url: 'yourHTMLfile.html',
type: 'get',
async: false,
success: function(html) {
console.log(html); // here you'll store the html in a string if you want
}
});
DEMO
EDIT: Added a demo!
I reread your question and I noticed you're calling the console log right above the ajax request but you forgot the ajax is asynchronous that means the page will do a request and only will set the template value when the response return with success(if it returns). So the console.log(template) don't appears because it may be not loaded yet.
var template = "";
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
success: function(html) {
var twig = String(html);
template.concat(twig);
console.log(template); // the change!
}
});
or
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
async: false,
success: function(html) {
var twig = String(html);
template.concat(twig);
}
});
console.log(template); // the change!
You can try this:
//as you see I have used this very page's url to test and you should replace it
var fileUrl = "/questions/20400076/reading-a-file-into-a-string-in-jquery-js";
jQuery.get(fileUrl).then(function(text, status, xhr){
//text argument is what you want
});
and if it won't work try if your browser can open the file. if it could you'd better try ajax method in jQuery if not you might have some problems regarding permissions or somethings like that in you application server.