Answer the question
In order to leave comments, you need to log in
How to pass HTML object with ajax to php script?
I want to pass the entire HTML page to the php handler using the POST method. Starting from
and ending
. I use the $.post (jQuery) method for this, which allows you to pass either a string or an object.
I haven't figured out how to pass HTML content as a string. When I try to send a page in JSON format
, I get something completely different from what I need:
</html>
JSON.stringify(window.document)
{"location":{"href":" http://test3.ru/","origin":"http://test3.ru","prot... ":""}}
Answer the question
In order to leave comments, you need to log in
Andrey In my opinion, it's a bad idea to send an entire page. But if that's what you decide. You need to pass not JSON data, but html or text. The jQuery.ajax( [settings ] ) method accepts a settings object whose properties must be set to dataType
$.ajax({
url: you_url,
type : 'POST'
dataType : 'html',
data: window.document,
success: function(data){
console.log(data);
}
});
As far as I understand, dataType determines the type of data that we receive from the server. And I have a problem with the type of data passed to the server.
Of course, I tried your solution, but got an error:
TypeError: 'click' called on an object that does not implement interface HTMLElement.
I so understand that swears on a format of the transferred data.
P.S. I transfer the entire page to the server in order to save it to a file. It is created in the user's browser by Ajax and then, if desired, it can be saved to a file and downloaded.
Just in case, here's the full code:
$("#save-but").on('click', function () {
var pagePath = "results/" + Math.random().toString(36).substring(2) + ".html";
var pageContent = window.document;
$.ajax({
url: "constructor.php",
type: 'POST',
dataType: 'html',
data: {name: pagePath,content:pageContent}
});
});
Ajax request passes string data. Therefore, you need to receive not an object, and not a jquery object, trying to pass it to the server! but to get string data, and assign them as values to keys. Which you will already pass in your POST request.
var data="";
data="name="+encodeURIComponent($("ваш_блок").prop("outerHTML"));
data+="content="+encodeURIComponent($("ваш_другой_блок").prop("outerHTML"));
$.ajax({
url: url,
type: "POST",
data: data,
success: function(){ /*обработчик вашей функции*/}
)}
Mb, who needs it. For myself, I found this way, simplifying the answer a little - Oleg and for passing not only the dom-tree of the element, but also other parameters.
var par1 = 'какие-то текстовые данные';
var par2 = $("#elem").prop("outerHTML"); //получаем весь dom элемента
$.ajax({
type: 'post',
url: "url",
dataType: 'html',
data: ({
d: par1,
v: par2,
}),
success: function(response){}
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question