how to fill an input with html code with AJAX - javascript

I can't understand why this is not working.
I have an input in my site which is filled by an ajax request.
I would like to fill it with htmlCode, but it's empty when tried.
<form name="form" id="form" method="post" action="secondpage" />
<input type="hidden" name="htmlCode" id="htmlCode"/>
</form>
$.ajax({
url : url,
type: "POST",
async: true,
data : {
"requestData": JSON.stringify(request)
},
success: function(data, textStatus, jqXHR){
var response = data.methodResult;
alert(response.htmlCode);
document.getElementById("htmlCode").value = response.htmlCode;
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
the alert shows the htmlCode, so, I'm sure it exists.
I read the variable in jsp:
System.out.println("htmlCode Value - " + request.getParameter(htmlCode));
And this is empty.
If I change the REST server, and returns "hello" instead of htmlCode it is filled.
Is there any forbidden character I'm trying to set or something?
I got the solution, I should encode UTF-8 the html text

Does it work when you use JSON.stringify?
document.getElementById("htmlCode").value = JSON.stringify(response.htmlCode);
Documentation: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

Try this one
$.ajax({
url : url,
type: "POST",
async: true,
data : {
"requestData": JSON.stringify(request)
},
success: function(data, textStatus, jqXHR){
document.getElementById("htmlCode").value = data;
},
error: function (jqXHR, textStatus, errorThrown) {}
});

Related

passing the parameter in post in jquery

I want to pass the response data to another page in ajax success.
I'm using jquery in laravel. I have called the function and get the data from the controller in success call. I want to pass the received data to another page detail
$.ajax({
type: 'get',
url: 'am_detailed_report', //send the request to the controller
data: {
am_geo_selection: am_geo_selection
},
dataType: 'json',
success: function(data) {
console.log(data);
$url = "am_detailed?filter=" + data;
window.open($url, "_blank"); //want to send the parameter in post instead of passing it in url.
$('.loaderImage').hide();
},
error: function(jqXHR, textStatus, errorThrown) {
$('.loaderImage').hide();
}
});
Try this
$.ajax({
type: 'get',
url: 'am_detailed_report', //send the request to the controller
data: {
am_geo_selection: am_geo_selection
},
dataType: 'json',
success: function(data) {
console.log(data);
$url = "am_detailed"
const html = `<form action="${url}" method="post">
<textarea name="filter">${data}</textarea>
</form>`
const w = window.open("", "_blank");
w.document.write(html);
w.document.close();
w.document.querySelector("form").submit()
$('.loaderImage').hide();
},
error: function(jqXHR, textStatus, errorThrown) {
$('.loaderImage').hide();
}
});

how to get the returned URL from ajax request

i'm trying to get only the returned URL from ajax request
like this
$.ajax({
type: "GET",
dataType : "jsonp",
async: false,
url: $('#FaceBookProfileLink').attr('href'),
success: function(response) {
console.log(response);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
but i can't.
the returned URL showing in the console as js file but i can't get it
please any help and many thanks in advance.
As you are using 'GET' method, retrieve them with $_GET[], ie:
echo $_GET['code']

Error occurs when i use jQuery Ajax

$('#deviceLoadMore') is a link. When this link is being clicked, it will trigger a ajax to the web service I have created.
The problem I'm having now is it keeps on throwing this error in the console.log
Uncaught TypeError: Converting circular structure to JSON. But when I just paste the ajax part in the console.log, it able to retrieve the data back. I have checked that all the value is just a normal string and integer.
I was wondering why i can trigger in console log without having any issue and couldn't if i just click on the link?
var currentContextSection = '<%=currentSection %>';
var currentTemplateIds = '<%=templateIds %>';
var currentItemPerPage = <%=itemPerPage %>;
var currentPageIndex = <%=currentPage %>;
var arguments = { templateIds:'<%=templateIds %>' , currentSection:'<%=templateIds %>', currentPage:currentPageIndex, itemPerPage:currentItemPerPage };
$(document).ready(function () {
$('#deviceLoadMore').click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/AJAX/WS.asmx/GetItems",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(arguments),
dataProcess: false
}).done(function (data) {
test = data;
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
});
});
});
------ EDIT -------
If I have this:
var arguments = {"templateIds":currentTemplateIds ,"currentSection":currentContextSection,"currentPage":currentPageIndex,"itemPerPage":currentItemPerPage};
and executing with the ajax data:JSON.stringify(arguments), i will get the following errror:
Converting circular structure to JSON.
When I console.log the "arguments", it displays:
Object {templateIds: "963C1D18A93849309D6014CE2135173C", currentSection: "Personal", currentPage: 1, itemPerPage: 8}
And it displays this when I console.log JSON.stringify(arguments):
"{"templateIds":"963C1D18A93849309D6014CE2135173C","currentSection":"Personal","currentPage":1,"itemPerPage":8}"
After google around for some successfully implemented ajax sample, I changed my code to the following, and it works! And I have no idea why it works this way.
$(document).ready(function () {
$('#deviceLoadMore').click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/AJAX/WS.asmx/GetItems",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({"templateIds":currentTemplateIds ,"currentSection":currentContextSection,"currentPage":currentPageIndex,"itemPerPage":currentItemPerPage}),
dataProcess: false
}).done(function (data) {
test = data;
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
});
});
});
try after removing, JSON.stringify from
data: JSON.stringify(arguments),

php - return the value of an ajax post back to javascript

I'm trying to test the successful submission of data from javascript to a php file by having that php file return the results of the javascript post back to javascript. I'm getting a successful response in the ajax post, but the data is an empty string. How do I find out what data was posted? Here's my code:
JAVASCRIPT:
var benefitsArray = ["someData","someOtherData"];
$('#drop-submit').on('click',function(){
if (benefitsArray.length > 0){
var formData = { "benefits" : benefitsArray };
debugger;
$.ajax({
url : "dd-receiver.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{
console.log(data); //result is "";
debugger;
//data - response from server
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log('failure');
}
});
}
});
PHP:
<?php
echo $_POST["benefits"]
?>
UPDATE:
I got a response by, in the php code, doing:
echo json_encode($_POST['benefits']);
but the problem is that in the javascript, if I log the data, the result is
"["someData","someOtherData"]" (a string)
and not
["someData","someOtherData"] (an array)
how do I get it to return an array and not a string?
You're not parsing the JSON being sent to you.
You can make jQuery do this for you by adding dataType: 'JSON' to your $.ajax options...
$.ajax({
dataType: 'JSON',
url : "dd-receiver.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR) ...
Or manually with JSON.parse:
success: function(data, textStatus, jqXHR) {
benefits = JSON.parse(data);
...
}

Jquery ajax post request not working

I have a simple form submission with ajax, but it keeps giving me an error. All the error says is "error". No code, no description. No nothing, when I alert it when it fails.
Javascript with jQuery:
$(document).ready(function(){
$(".post-input").submit(function(){
var postcontent = $(".post-form").val();
if (postcontent == ""){
return false;
}
$(".post-form").attr("disabled", "disabled");
$.ajax({
url: '/post',
type: 'POST',
data: {"post-form": postcontent},
dataType: json,
success: function(response, textStatus, jqXHR) {
alert("Yay!");
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
});
});
HTML:
<form class="post-input" action="" method="post" accept-charset="utf-8">
<textarea class="post-form" name="post-form" rows="1" cols="10" onFocus="this.value='';return false;">What are you thinking about...</textarea>
<p><input class="post-submit" type="submit" name = "post.submitted" value="Post"></p>
</form>
and if there are no problems there, then the server-side (pyramid):
def post(request):
session = Session()
user = authenticated_userid(request)
postContent = request.POST['post-form']
if not postContent == '':
session.add(Activity(user.user_id, 0, postContent, None, None))
return {}
return HTTPNotFound()
UPDATE:
After some more debugging with firebug, I discovered that the post request body contains only post.submitted=Post, instead of the intended result of {"post-form": postcontent}.
According to jQuery documentation, you must declare the data type:
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
Also, looking at your server-side code, you don't actually want to post JSON formatted data. This {"post-form":postcontent} is JSON formatted data. What you actually want to do is send TEXT or HTML. Seeming as it's form data, I would guess at TEXT.
Try this:
$.ajax({
url: '/post',
type: 'POST',
data: 'post-form='+postcontent,
dataType: 'text',
success: function(response, textStatus, jqXHR) {
alert("Yay!");
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
Since you are posting JSON-data you have to declare the dataType "JSON":
$.ajax({
url: '/post',
type: 'POST',
dataType: "json",
data: {"post-form": postcontent},
success: function(response, textStatus, jqXHR) {
alert("Yay!");
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
I think the problem is that the data that you are passing is not properly written.
Try to change this:
data: {"post-form": postcontent},
To this:
data: 'post-form='+ $('.post-form').val(),

Categories