I'm trying to upload a file using $.ajaxFileUpload. My server script is returning a json object eg.
{"imgName": "test.jpg", "imgUrl": "/uploadtest/images/profile/sam.jpg"}
When I check in firefox it shows the correct response. Json is also received. But still I'm getting an error in alert:
SyntaxError: missing } in XML expression
I couldn't understand why this error is shown up.
Also in firebug Json object is shown correctly.
<script type='text/javascript' src='/js/ajaxfileupload.js'></script>
<script type='text/javascript'>
function doFileUpload(){
$("#loading")
.ajaxStart(function(){
$(this).show();
})
.ajaxComplete(function(){
$(this).hide();
});
$.ajaxFileUpload(
{
url:'/json/image/upload.html?action=saveImage&nameSpace=tot',
secureuri:false,
fileElementId:'imgFile',
dataType: 'json',
success: function (data, status){
alert("Success: "+data.imgUrl);
},
error: function (data, status, e){
alert("Error: "+e+"---URL: "+data.imgUrl);
}
}
)
}
</script>
....
....
<div>
<strong>Upload Images:</strong><br>
<input type='file' name='imgFile' id='imgFile'>
<img src='/images/loading.gif' id='loading' height='60px' width='60px' style='display:none'>
<br><button name='upload' id='upload' onclick='return doFileUpload();'>Upload</button>
</div>
Anyone can tell me what's the reason for the Error?
I finally found the problem. The problem is with AjaxFileUpload plugin of Jquery which I'm using. Instead of 'json' in dataType it requires it to be capitalized. dataType: 'JSON'. Also after fixing this it automatically adds <pre> and </pre> to the beginning and end of the received json data. So it is not interpreted ad json.
Actual data that i received was
<pre>{"imgName": "test.jpg", "imgUrl": "/uploadtest/images/profile/sam.jpg"}</pre>
Now I'll have to remove there tags and then parse it with $.parseJson().
If anyone have the same error then check these problems.
I hope ajaxFileUpload plugin will be fixed soon.
I found that with the return data in Mozila I was having this problem. Actually the message was being returned with <p>message</p> and this was giving an error.
The fix I applied was to remove anything not needed in the return message and it's working. But I'm not sure if its a permanent fix. At the end of the ajaxfileupload.js script file I modified the uploadHttData function
uploadHttpData: function( r, type ) {
var data = !type;
var dataparsed = r.responseText.split("{"); //added by Jude
dataparsed = dataparsed[1].split("}"); //added by Jude
///Commented By Jude
///data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
data = type == "xml" || "{ " + dataparsed[0] + " }"; //added by Jude
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" ) {
eval( "data = " + data );
}
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts();
//alert($('param', data).each(function(){alert($(this).attr('value'));}));
return data;
}
I have fixed this,
Just update the code line:
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
With this one:
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.textContent:null;
The innerHTML is causing the problem.
to reformat the pre from the response you can use regex(credit:https://github.com/carlcarl/AjaxFileUpload)
if ( type == "json" )
{
// If you add mimetype in your response,
// you have to delete the '<pre></pre>' tag.
// The pre tag in Chrome has attribute, so have to use regex to remove
var data = r.responseText;
var rx = new RegExp("<pre.*?>(.*?)</pre>","i");
var am = rx.exec(data);
//this is the desired data extracted
var data = (am) ? am[1] : ""; //the only submatch or empty
eval( "data = " + data );
}
i found the solution to the json problem by searching github for ajaxfileupload, and found this version which worked correctly for me once I capitalized JSON
Jude Adeline answer was correct if you were looking to return back a single dimensional json response. If you are looking to kick return a multi dimensional array from PHP, modify your code to this below.
uploadHttpData: function( r, type ) {
var data = !type;
var dataparsed = r.responseText.substr(1); //changed-added
dataparsedLength = dataparsed.length; //changed-added
dataparsed = dataparsed.substr(0, dataparsedLength-1); //changed-added
data = type == "xml" || "{ " + dataparsed + " }"; //changed-added
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
eval( "data = " + data );
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts();
return data;
}
i have been though this problem - u need to change only one line
if ((type == "json") || (type == "JSON")) then works fine in both FireFox and IE
I had an error like this
I used:
$Ex=end(explot('.', image));
in doajaxfileupload.php, which gave the error:
"AjaxFileUpload SyntaxError: missing } in XML expression"
I changed it to:
$tmp=explot('.', image);
$Ex=end($tmp);
It's worked for me
The PHP documentation gives this example:
mixed end ( array &$array );
$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry
To solve the problem make sure you set the Content-Type of you answer to "text/html".
That look strange indeed :-)
The reason is that the answer is processed by Firefox to build a document.
When the Content-Type of the answer is "text/plain" Firefox, that only display html, convert the answer into html by adding the tags.
Related
I'm using the tinyMCE editor plugin in my webpage.
When I use a simple HTML page post to post the contents to the backend PHP and save them to a database or file, all seems OK.
When I try to do the same using an AJAX post, I am finding it impossible to prevent encoding issues.
In particular (I'll escape it here) \&\n\b\s\p\; is being converted to  and a "-" character is being converted to �
I've tried a few suggestions but with little luck.
The suggestion is that it is either an issue with my charset or encoding.
My save function is as follows:
function letterSave(newfile,fname){
var newDate = new Date;
var uniq=newDate.getTime();
var input = $('#myTextareastdletter');
var contents=input.val();
var context='<?=(!strcmp($sessobj->mode,"SA_ViewAbs")?"A":"S");?>';
// alert(fname);
$.ajax({
type: "POST",
url: '<?=auto_version("./SVajaxSaveDocContents.php")?>?duff='+uniq,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: {'S_sessid' : '<?=$sessobj->sessionid?>', 'context' : context, 'contents' : encodeURIComponent(contents), 'fname' : fname, 'newfile' : newfile},
success: function(data){
data = JSON.parse(data);
fname=data[0];
newLetterList=data[1];
if (fname != 'FAIL') {
alert ('OK: Letter Contents Saved to File ('+fname+').');
var versionOutput = $('#popupOutput');
versionOutput.html('');
var box = $('#popupDisplay');
var cover=$('#coverDiv');
box.css({
display:"none"
});
cover.css({
display:"none"
});
var letterOutput = $('#AbsenceLetters');
letterOutput.html(newLetterList);
} else {
alert ('Sorry: Failed to Save Letter Contents!');
}
},
error: function(data){
alert ('Sorry: Failed to Save Letter Contents!');
// console.log(data);
// console.log('error');
}
});
}
As you can see, I've been playing with setting the contentType and using encodeURIComponent().
Any help would be appreciated.
Cheers
In order to avoid these encoding issues, don't use .val on the textarea that the tinyMCE instance is attached to. Instead, you can utilize tinyMCE's built-in getContent method like so:
tinyMCEInstance.getContent()
I'm sending a HTML form and javascript array using AJAX post method. But I can't get my data in the PHP file.
$.post("addOrder.php", {
"form": $("#placeOrderForm").serialize(),
"array": array
}, function(responce) {});
Please read the docs clearly.
The update code:
$.post("addOrder.php",
$("#placeOrderForm").serialize(),
function(response) {
}
);
And in addOrder.php, print the posted array using.
echo '<pre>';print_r($_POST);echo '</pre>';
If you are using firebug, you will get the posted variables' array in response tab.
// You can access the values posted by jQuery.ajax
// through the global variable $_POST, like this:
$var = isset($_POST['var']) ? $_POST['var'] : null;
Can you try something like below:
var request = $.ajax({
url: "addOrder.php",
type: "POST",
data: {<data1> : <val1>},
dataType: "html"
});
request.done(function(msg) {
$("#log").html( msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
Looks like you passing argument is having issue.
In addForm.php try this:
var_dump($_POST)
This will enable you to inspect the form data posted.
Try something like this in your php file:
$params = array();
echo parse_str($_POST, $params);
Thanks everyone. I found my answer. I used "serializeArray" for sending form.
html
<form id="placeOrderForm">
<input name="po">
<input name="desc">
</form>
javascript
var array = [1,2];
$.post("addOrder.php",{
"form":$("#placeOrderForm").serializeArray(),
"array":array
}, function (responce) {});
php
$form_input_data_1 = $_POST['form'][0]['value']; // get po's data
$form_input_data_2 = $_POST['form'][1]['value']; // get desc's data
$array_index_1_data = $_POST['array'][0]; // get 1
$array_index_2_data = $_POST['array'][1]; // get 2
How can I pass data from a query in php and set it's result using an ajax method.
Here is what I have so far in a file called file1.php:
<script type = "text/javascript">
function myAjax () {
$.ajax( { type : 'POST',
data : { },
url : 'query.php',
success: function ( data ) {
$doc = new DomDocument();
$doc->Load('file2.php');
$element = $doc->getElementById('resultFromFile1');
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
I wanna put the contents in this html element in the php file file2.php:
<p id ="resultFromFile1" name = "results">No Results</p>
Many stack overflow posts haven't been any help. Could someone point me in the right direction?
It's wrong approach.
You should rather create php script which will save your ajax request data in let's say database and then in file2.php load this data from DB, not directly update file
First of all what kind of content is query.php returning? Is it a JSON Object or are you just "echoing" the output as a string?
Next Question: Are you using jQuery, AngularJS or something in that direction?
Usually what you want to do is get the information from the "query.php" and pass it as a JSON formatted ajax result...
Now to your actual Problem: You want to get the element called "resultFromFile1" that's inside file2.php but you aren't adding anything to the "visible scope" yet since Load only loads the content but it doesn't add the content to any element you have to define an element holding your "file2.php". If i were you to avoid all these Problems i would use AngularJS for displaying your data in to a view and just include your "result" template via ng-include and let the ajax fill the document..
To solve your Problem:
<script type = "text/javascript">
// Your Solution
function myAjax () {
$.ajax( { type : 'POST',
data : { },
url : 'query.php',
success: function ( data ) {
$doc = new DomDocument();
$doc->Load('file2.php');
$element = $doc->getElementById('resultFromFile1');
},
error: function ( xhr ) {
alert( "error" );
}
});
}
// My Solution for this problem using native js
// Load the "file2" contents in to the file2Holder element
LoadUrlToElement('file2.php','file2Holder',function(data){
/* When the first loading of file2.php is done, load the results from the query.php and put it in to the element called "resultFromFile1" which we just loaded and placed in to the dom before. But i would recommend you to use AngularJS to avoid this Callback hell and get many cool features that webdevelopers don't want to miss these days.... */
LoadUrlToElement('query.php','resultFromFile1',function(){
alert('Content of resultFromFile1 is => '+document.getElementById('resultFromFile1'));
});
});
function LoadUrlToElement(url,elementID,done) {
$.ajax( { type : 'POST',
data : { },
url : url,
success: function ( data ) {
if(document.getElementById(elementID) === undefined){
alert("Can't proceed cause the content holder"+elementID+" is not found");
return; // Abort here cause there is no container with this id...
}
document.getElementById(elementID).html = data;
if(done !== undefined && typeof done === 'function') done(data);
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
<div id="file2Holder"></div>
I have called an ajax function that gather data from an xml file formatted like this
<?xml version="1.0" encoding="utf-8"?>
<values>
<value date="2015-07-12">37.170</value>
<value date="2015-07-13">7.190</value>
<value date="2015-07-12">37.170</value>
<value date="2015-07-12">3.210</value>
<value date="2015-07-12">37.20</value>
</values>
When I get the response from the console it says
not well-formed :1:80
Not sure what this means since when I use xml validator they all tell me that there are no errors. Any help would be awesome to have.
var data = [];
$.ajax({
url: 'test.xml', // name of file you want to parse
dataType: "xml", // type of file you are trying to read
success: parse, // name of the function to call upon success
async: false,
error: function(xhr, status, error) {
alert(xhr.responseText);
console.log("readyState: " + xhr.readyState);
console.log("responseText: "+ xhr.responseText);
console.log("status: " + xhr.status);
console.log("text status: " + textStatus);
console.log("error: " + err);
}
});
function parse(xml) {
var items = jQuery(xml).find("values");
var data = [];
var values = $(items).text();
$(document).find("Values").each(function () {
$(this).find("value").each(function () { data.push($this.text);});
});
console.log(data.length);
}
Not sure ethier how to get all of the values into the array.
You may be trying to parse it twice, per the documentation:
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).
Thus I'm imagining that this is what you are looking for:
function parse(xml) {
//var items = jQuery(xml).find("values");
var items = xml.find("values");
var data = [];
var values = $(items).text();
$(document).find("Values").each(function () {
$(this).find("value").each(function () { data.push($this.text);});
});
console.log(data.length);
}
EDIT!
Fiddle is updated.
http://jsfiddle.net/b62tx8Ln/1/
No need to parse data with parseXML.
Erik Phillips is probably right about the double parsing. Anyways, this should work.
Note the use of ECHO in fiddle..... just to simulate a local xml-file.
$.ajax({
url: 'test.xml', // name of file you want to parse
dataType: "xml", // type of file you are trying to read
success: parse, // name of the function to call upon success
async: false,
error: function(xhr, status, error) {
alert("error");
}
});
function parse(xmldata) {
$(xmldata).find("value").each(function(){
alert($(this).text());
});
}
For anybody else having a problem parsing non-well-formed (self-closing tags) xml in IE, $(xmlthing).find('nodename').each... works, whereas IE will parse $(xmlthing).children('nodename').each... (which is fine in FF and Chrome), as nested.
That is:
<thing />
<thing />
<thing />
will be 3 things in FF/Chrome, but one in IE if you use $(node).children(thing)
$(node).find(thing) will give you 3 things in all browsers. Thanks #Steen
The script below works great, but today I came across a scenario I think is being caused by escaped JSON.
As you'll see in the code below, I'm using remote validation to return error messages in JSON format as required.
On particulr error message being returned that looks like this is not being displayed:
{"valid":false, "error":"XDMP-BADCHAR: (err:XPST0003) Unexpected character found '\"' (0x0022)"}
My suspicion is that it's due to the escaped double quote (in bold above).
I suspect this because a similar error message that looks like this displays just fine: {"valid":false, "error":"XDMP-BADCHAR: (err:XPST0003) Unexpected character found ''' (0x0027)"}
I tried messing with escaping things further but to no avail. Any suggestions would be greatly appreciated.
CODE:
$(document).ready(function(){
$('#form-validate').validate();
$("[name^=customfields]").each(function(){
$(this).rules("add", {
remote: {
type: "GET",
url: "/xpath-evaluator.xqy",
dataType: "json",
dataFilter: function(data) {
var json = JSON.parse(data);
if (json.valid != false) {
return true;
}
else {return "\"" + json.error.split(')')[1] + "\"";}
}
}
});
});
});
Since I could not change the remote response coming back I used replace to escape the character it was having trouble with, in this case it was the '\"' as shown in the error below:
{"valid":false, "error":"XDMP-BADCHAR: (err:XPST0003) Unexpected character found '\"' (0x0022)"}
Here's the updated Javascript showing how I did it:
$(document).ready(function(){
$('#form-validate').validate();
$("[name^=customfields]").each(function(){
$(this).rules("add", {
remote: {
type: "GET",
url: "/xpath-evaluator.xqy",
dataType: "json",
dataFilter: function(data) {
var json = JSON.parse(data);
if (json.valid != false) {
return true;
}
else {
var jerror = json.error.split(')')[1]
return '\"' + jerror.replace('\"', '\\"') + '\"'}
}
}
});
});
});
Thanks are in order to Sippy who commented and set me on the right track to fixing this. Hope it helps someone else in the future.