I have a PHP code for uploading files, which works fine, and as final outcome I have sent JSON response with uploading status which I'm not able to retrieve.
After uploading file (POST) my response looks like:
{"html_content":"<p>File was uploaded<\/p>"}
PHP uploader code looks like:
if (!is_file($targetFile)) {
move_uploaded_file($tempFile,$targetFile);
$html_content="<p>File was uploaded</p>";
}
else {
$html_content="<p>You have uploaded duplicate.</p>";
move_uploaded_file($tempFile,$targetFile);
}
$json_array=array('html_content'=>$html_content);
header('Content-type: text/json');
header('Content-type: application/json');
echo json_encode($json_array);
and JavaScript main code to get message displayed:
this.on("success", function(file,responseText) {
$.ajax({
dataType: 'json',
success: function (response) {
var htmlElement = document.createElement("div");
htmlElement.setAttribute("class","success-message");
var responseText = response.html_content;
var messageText = document.createTextNode(responseText);
htmlElement.appendChild(messageText);
file.previewTemplate.appendChild(htmlElement);
console.log(response.html_content);
}
});
});
When I will unwrap above JS from AJAX part and set variable responseText
as a static all works fine.
Also when I will not use AJAX and just output console.log(responseText);
I'm getting this in the console:
Object {html_content: "<p>File was uploaded</p>"}
Any clue what I have missed in my case?
You're not sending a request to your PHP server. Specify URL argument.
$.ajax({url: "your_php_file",
dataType: 'json',
success: function (response) {
...
}
});
Or even better:
$.getJSON( "your_php_file", function( data ) { ... });
OK, got it solved. JavaScript code looks like
this.on("success", function(file,responseText) {
str = JSON.stringify(responseText);
responseMessage = $.parseJSON(str);
var htmlElement = document.createElement("div");
htmlElement.setAttribute("class","success-message");
htmlElement.innerHTML = responseMessage.html_content;
file.previewTemplate.appendChild(htmlElement);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.