I am trying to get latest data for a div and trying to replace it. The ajax query fetches the entire html page. Out of which I am finding right div. Now I need to replace current right div with what I have received.
$.ajax(
{
url: url,
type: "POST",
dataType: "text",
data: dataArray,
success: function (data) {
var content = $(data).find('.right');
$(".right").html(content[0])
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("Error");
}
});
It works but the result data has some weird layout issues. What is the proper way to setting the div.
You are selecing the element and putting it inside of it, not replacing it.
var content = $(data).find('.right');
$(".right").html(content[0]);
So your output looks like
<div class="right">
<div class="right">
<p>New content</p>
<div>
<div>
Either set the html
$(".right").html(content.html())
or replace it
$(".right").replaceWith(content)
Related
I have a View as shown below
**<div id = 123 class ="Country">**
<div class = "content">
**<need to load partial view here>**
</div>
**</div>**
**<div id = 234 class ="Country">**
<div class = "content">
**<need to load partial view here>**
</div>
**</div>**
...
...More div's here
...
so on clicking the Country div, i need to load its inner div "content". My jQuery ajax call is like below
$(".country").on('click', function () {
$.ajax({
url: '#(Url.Action("FilesByCountry", "RelatedFiles"))', //Cont & ActionResult
type: "GET",
data: $(this).attr('id'), //getting the click id
contentType: "application/json; charset=utf-8",
success: successFunc,
error: errorFunc
});
function successFunc(data) {
**$(this).attr('id').children($('#content', data).html())**
}
function errorFunc(xhr, errorType, exception) {
alert(xhr.status + ": " + exception);
}
});
});
So the controller is hitting fine and it went through the PartialView in debug mode. But the partial view is not binding in Main View. Any thoughts on this?
I think it is the way you are stuffing the content:
$(this).find('.content').html(data);
I think #content would be for the ID selector and .content for the class selector.
Another try is to just stuff a known div -->
$('#234').find('.content').html(data);
Or
$('#234').html(data);
Then inspect the element using dev tools F12 and see what was put inside.
Also, make sure you are injecting an html fragment. You can check the data for <head><body> tags, I am sure they should not be there for what you are doing.
I found the answer to this. Actually $(this) is not working inside my successFunc and was returning null always. So i modified my Javascript code to something as below.
$(".country").on('click', function () {
var _this = $(this);
$.ajax({
url: '#(Url.Action("FilesByCountry", "RelatedFiles"))', //Cont & ActionResult
type: "GET",
data: $(this).attr('id'), //getting the click id
contentType: "application/json; charset=utf-8",
success: successFunc,
error: errorFunc
});
function successFunc(data) {
_this.find('.content').html(data);
}
function errorFunc(xhr, errorType, exception) {
alert(xhr.status + ": " + exception);
}
});
});
I want to send some parts of the html source code with an ajax call.
If I define the data to be sent for the ajax call in this way:
var content={};
content['mypart1']='my content 1';
content['mypart2']='my content 2';
content=JSON.stringify(content);
In the console I see this string for sending:
... , content: "{\"mypart1\":\"my content 1\",\"mypart2\":\"my content 2\"}" ...
It works. After $test=json_decode($post['content']); I have the wanted array of my content parts.
Now I need to use it with real content parts, so i tried this;
$("[myselector]").each(function(i, part) {
content['mypart1']=$(part)[0].outerHTML;
content['mypart2']=$(part)[0].outerHTML;
});
content=JSON.stringify(content);
Now I see in the console, that the wanted html code is correctly inside the string.
But if I send this, I see in the console that inside the string there are multiple ///-signs and the keys are also inside \" now.
"{\"mypart1\":\"<div id=\\\"myid\\\" data-mydataid=\\\"123456\\\" class=\\\".....
I think it was because this faulty string that the jason_decode won't work correctly.
$test=json_decode($post['content']);
With this data I won't receive the wanted array, $test is empty.
What caused the multiple ///-signs and /-around the keys and how I can prevent this?
Thanks a lot for helping and explaining.
Maybe i have to unserialize the outerhtml part before add them to a stringify string?
This is the Ajax call
do_ajax_call({
'content': content,
...
});
function do_ajax_call(data,ajaxurl){
....
$.ajax({ url: ajaxurl,
method: 'POST',
data: data,
dataType:'json',
success: function(result){
...
});
HTML:
<div class="progress-bar progress-primary" id="bar" role="progressbar" style="width: 0%"></div>
<b id="import"></b>
js:
var data = {};//js object
data["key1"] = document.getElementById('import').outerHTML;
data["key2"] = document.getElementById('bar').outerHTML;
$.ajax({
beforeSend: function () {
},
complete: function () {
},
type: "POST",
url: ajaxurl,
data: data,
success: function (data) {
setTimeout(function () {
}, 1000);
}
});
php :
echo'<pre>';print_r($_POST);die;
output :
<pre>Array
(
[key1] => <b id="import"></b>
[key2] => <div class="progress-bar progress-primary" id="bar" role="progressbar" style="width: 0%"></div>
)
This is tested code
I am typing with the div on the login screen. I want this article to be dynamic. That's why I am using ajax jQuery to pull data. I want it to be written in the div. How do you do that?
<div class ="bas">Write here(title)</div>
$.ajax({
type: "GET",
url: MY,
success: function (msg, result, status, xhr) {
var obj = jQuery.parseJSON(msg);
title = obj[0].Write;
}
});
You can use either text() or html() to set the content of the required div element. Try this:
<div class="bas">Write here(title)</div>
$.ajax({
type: "GET",
url: MY,
dataType: 'json',
success: function(msg) {
$('.bas').text(msg[0].Write);
}
});
Note that by using dataType: 'json' jQuery will deserialise the response for you, so you don't need to call JSON.parse manually.
Use .text() function
<div class ="bas">Write here(title)</div>
$.ajax({
type: "GET",
url:MY,
success: function (msg, result, status, xhr) {
var obj = jQuery.parseJSON(msg);
title= obj[0].Write;
$(".bas").text(title);
}
});
You can do it by html() or text() depends on what object contains. If containing data includes html tags such as <strong> or .. use html() but if it's plain text use text() instead.
$.ajax({
type: "GET",
url:MY,
success: function (msg, result, status, xhr) {
var obj = jQuery.parseJSON(msg);
title= obj[0].Write;
$('.bas').html(title); // this line
}
});
if only remote read text file
<div class="bas">Write here (title)</div>
jQuery.get(myURL, /*ifMyParams,*/ function(data){
jQuery('.bas').text(data);
})
Use hanlderbars.js or <div class ="bas">Write here<span class="title"></span></div>
I'm trying to get the response of a GET request inside a textfield on my webpage using jquery. Currently, I have the following code with which I can get the response on the console.
$(document).on('click', '#get-button', function(e) {
e.preventDefault();
$.ajax({
type: "GET",
url: $("#url").val(),
data: '',
success: function(response, textStatus, XMLHttpRequest) {
console.log(response);
}
});
return false;
});
$(document).on('click', '#post-button', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $("#url").val(),
data: $("#json-data").serialize(),
success: function(response, textStatus, XMLHttpRequest) {
console.log(response);
}
});
return false;
});
Below is a part of the HTML code where I want to fit the response(in JSON) format.
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-danger">
<div class="panel-heading">JSON Response</div>
<div class="panel-body text-danger">
<textarea class="form-control" rows="8" placeholder="server response"></textarea>
</div>
</div>
</div>
</div>
Place your code in ready function, or add deffer to your script definition. In that way your script will execute after DOM is loaded.
Don't add events on docuemnt like this, it is too big. You are using id's, thats nice, so use it:) It depends on your DOM size, butin most cases find a element by id and then add event to it.
Add an id to your textbox, that will be more usable and faster.
.
$(document).ready(function(){
$('#get-button').on('click', function(e) {
e.preventDefault();
$.ajax({
type: "GET",
url: $("#url").val(),
success: function(response) {
console.log(response);
$('.form-control').val(response); // personally I would give your textbox an ID
}
});
return false;
});
$('#post-button').on('click', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $("#url").val(),
data: $("#json-data").serialize(),
success: function(response) {
console.log(response);
$('.form-control').val(response);
}
});
return false;
});
})
If your URL are correct, this will work.
Just remember that after you get the response, and you will get a JSON object, you will have to convert it to String using JSON.stringify().
I will try to explain. In Javascript we have Objects and simple types (boolean, String, float, etc). When we want to print a simple type, we just see it's value. But when we want to display a Object, JS engine has a problem, because each object can be very big, complex. Thats why when printing an object or JSON (witch is an Object) we get [Object]. Luckilly JSON is so popular that JS has an default methods for serializing String to JSON (JSON.parse(someString)) and other way around (JSON.stringify(JSONObject)).
What am I missing? I've added the get element by Id and I'm definitely getting a response back, I checked using firebug and the response is correct. But I can't figure out why it won't populate my div area.
<script>
$(document).ready(function () {
$("#cmdSend").click(function () {
// Get he content from the input box
var mydata = document.getElementById("cmdInput").value;
$.ajax({
type: "POST",
url: "/Terminal/processCommand",
data: { cmd: mydata }, // pass the data to the method in the Terminal Contoller
success: function (data) {
//alert(data);
// we need to update the elements on the page
document.getElementById("terminal").value = document.getElementById("terminal").value + mydata;
document.getElementById("terminal").value = document.getElementById("terminal").value + data;
},
error: function (e) { alert(e); }
})
});
});
</script>
And the Div I want the response to be put in:
<div class="terminal" style="overflow:scroll">
<br>
</div>
First, you are calling document.getElementById(), but your div does not have an ID of terminal, it has a class called terminal.
Second, you are using jQuery but then switch back to classic JavaScript. You could update your code to the following:
success: function (data) {
//alert(data);
// we need to update the elements on the page
var existingHtml = $(".terminal").html();
$(".terminal").html(existingHtml + mydata + data);
}
Note that the $(".SomeName") selector is for selecting by class and $("#SomeName") is to select by id.
Edit and Note
If this terminal div could start to get a lot of data inside of it, you may look at using the .append() function in jQuery to prevent having to make a copy of the HTML and overwrite the HTML each time a request is made. The update would be something similar to the following (its a little shorter and should be more efficient as well)
success: function (data) {
//alert(data);
// we need to update the elements on the pag
$(".terminal").append(mydata + data);
}
If you want to get your element by id, add an id to the div:
<div id=terminal class="terminal" style="overflow:scroll">
<br>
</div>
If you want to change the contend of div not using jquery, you should use innerHTML instead of value.
document.getElementById("divID").innerHTML = document.getElementById("divID").innerHTML + data