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
Related
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)
I am new to jQuery and I am trying to iterate through a list of strings after making an ajax call to a controller. In this controller, I am returning a list of strings and I want to iterate over this list in jquery and present it to the screen. Here is my code.
This is my controller
[HttpPost]
public ActionResult GetComments() {
var cmts = ex.GetComments(psts, psons);
var lstCmt = ex.GetCommentsList(cments, psons);
return Json(lstCmt);
}
This is my view:
<div>
<button id="ldBtn" class="btn btn-primary">Load</button>
</div>
<div id="cments">
</div>
<script src="~/Scripts/jquery-3.2.1.js"></script>
<script>
$(document).ready(function() {
$("#ldBtn").on('click', function(evt) {
$("#cments").empty();
$.ajax({
type: "POST",
dataType: "html",
url: '#Url.Action("GetComments")',
data: {},
success: function(lists) {
//Something needs to be fixed here
$.each(lists, function(i, name) {
$('#comments').append('<p>' + name.Value + '</p>');
});
}
});
});
});
</script>
When I return the list, I am getting a huge string. How do I fix this?
Thanks in Advance
There's a couple of issues in your JS code. Firstly you're telling jQuery to expect a HTML response in the dataType setting. This is why you see the response as a string. This should be changed to JSON instead, that way jQuery will deserialise the response for you.
Secondly you're attempting to concatenate a Value property on each item in the list, yet they are strings (as you state you're returning a List<string> from your action), and will not have that property. You can simply append the name itself. Try this:
$("#ldBtn").on('click', function(evt) {
$("#cments").empty();
$.ajax({
url: '#Url.Action("GetComments")',
type: "POST",
dataType: 'json',
success: function(comments) {
$('#cments').append('<p>' + comments.join('</p><p>') + '</p>');
}
});
});
I assume the #comments/#cments discrepancy is only due to amending parts of your code when creating the question.
Also note that I simplified the append() logic so that it appends all comments in a single call, which should be slightly faster.
I am trying to set the content of an empty div after an AJAX call with the data message. I also wired the function to my CHtml::submitButton, which should call the function when clicked, but nothing is happening. Any suggestions?
<div id="myResult">
</div>
JavaScript:
function successMessage(){
$.ajax({
type: "GET",
data: "<div> Replace div with this contentf</div>",
success: function(data){
$('myResult').html(data);
}
})
}
PHP:
echo CHtml::beginForm(array('myForm'), 'get', array('form'));
echo '<div class="row form">';
echo '<div class="row buttons">';
echo CHtml::submitButton('Download Content', array('htmlOptions' => 'successMessage()'));
echo '</div>';
echo '</div>';
Your problem relies in the following line:
$('myResult').html(data);
Here, you are trying to do a jquery selection to an element, which you are not using in your html (this is only possible via pollyfils). So you have to select the element by its ID:
$('#myResult').html(data);
And another thing i've seen, what is the url where you are doing the request?
<script>
function successMessage(){
$.ajax({
type: "GET",
url: "/please/add/an/url/",
data: "<div> Replace div with this contentf</div>",
success: function(data){
$('myResult').html(data);
}
})
}
</script>
first of all, when you are using onclick function like this :
<input type="submit" onclick="successMessage()">
you should use this instead:
<input type="submit" onclick="successMessage();result false;">
but when you are already using jquery, then better approach is:
$( document ).ready(function() {
successMessage(){
// your ajax goes here
}
$('#myResult').click(function(e){
e.preventDefault();
successMessage();
});
});
Then you need to repair your successMessage function. You see, the data you are setting there are not the data, that are coming out as an output. If you need ajax then you probably want to get the result from some php script on some other url. Then you should do it like this :
function successMessage(){
$.ajax({
type: "GET",
url : 'index2.php',
dataType: "json",
data: { mydata: '<div> Replace div with this content</div>'},
success: function(data){
$('#myResult').html(data);
}
})
}
Then you need a php file named index2.php which can look like this :
<?php
echo json_encode($_GET['variable']);
?>
And i dont know if this your line :
echo CHtml::submitButton('Download Content', array('htmlOptions' => 'successMessage()'));
also put the </form> tag after the form to close it.
This should work for you. I tried it and it works fine.
Try this:
$.ajax({
url: "test.html",
type: "GET",
data: "<div> Replace div with this contentf</div>",
success: function(data){
$('#myResult').html(data);
}
})
selector jQuery incorrect in response ajax. and define Url in ajax.
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)).
I have this URL, that I supposedly should receive an XML from. So far I have this:
function GetLocationList(searchString)
{
$.ajax({
url: "http://konkurrence.rejseplanen.dk/bin/rest.exe/location?input=" + searchString,
type: "GET",
dataType: "html",
success: function(data) {
//Use received data here.
alert("test");
}
});
Tried to debug with firebug, but it doesn't go into the success method.
Though, in DreamWeaver it is able to post a simple alert, which is inside the success method.
I tried writing xml as dataType, but it doesn't work (in DreamWeaver) when I write alert(data).
But it shows an alert with the entire XML, when I write html as dataType.
How do I get the XML correctly, and how do I parse and for example get the "StopLocation" element?
Try to add an Error function as well.
See enter link description here
This will give you all the informations you need to debug your code with Firefox.
$.ajax({
url: "http://konkurrence.rejseplanen.dk/bin/rest.exe/location?input=" + searchString,
type: "GET",
dataType: "html",
success: function(data) {
//Use received data here.
alert("test");
},
error: function(jqXHR, textStatus, errorThrown ){
// debug here
}
});
you need to parse it first, and then you can search for the attributes. like this.
success: function(data) {
var xml = $.parseXML(data)
$(xml).find('StopLocation').each(function()
{
var name = $(this).attr('name');
alert(name);
}
);
this will give you the name of each StopLocation.
hope this helps, you can use the same method for all other attributes in the document also.