loading text file using cakephp + jquery.ajax - ajax

I have the following (working) code for loading and parsing text files:
$(document).ready(function(){
var parse_file = function(url) {
var ret = null;
$.ajax({
async: false,
url: url,
dataType: "text",
success: function(data) {
// parse 'data' and set 'ret'
}
});
return ret;
};
var file_url = "./file.txt";
var ret = parse_file(file_url);
// ...
});
However, if I put it into a cakephp's view file, it doesn't work anymore.
data contains a html-file with a cakephp error, that there is an undefined index.

Related

merge ajaxform with ajax to upload image

I try to create upload photos in my nodejs site.
I used this code to choose file and upload the image:
var fileData = null;
function loadFile() {
var preview = document.querySelector('file');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.onloadend = function () {
fileData = file;
}
if (file) {
reader.readAsDataURL(file);
}
}
function uploadFile() {
data = new FormData();
data.append('file', fileData);
$.ajax({
url: "/post_pdf/",
type: "POST",
data: data,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
success: function(data) {
document.getElementById("result").innerHTML = 'Result: Upload successful';
},
error: function(e) {
document.getElementById("result").innerHTML = 'Result: Error occurred: ' + e.message;
}
});
}
With loadfile funcion i choose my image, and with Uploadfile function i upload the image with ajax.
if i use it alone its work perfect and upload the image to the location.
but when i try to add this code to my code, it make alot of errors.
in my code i send to back end all the forms in the pug file:
$('#account-form').ajaxForm({
error : function(e){
if (e.responseText == 'title-empty'){
av.showInvalidTitle();
}
},
success : function(responseText, status, xhr, $form){
if (status == 'success')
{
$('.modal-alert').modal('show');
console.log(responseText)
}}
});
i try to merge the ajaxform with the ajax but when i merege the formdata or i send in ajaxform the data of the file is send error.
how can i merge the codes?
thanks for helping.
Try to submit form it will submit form with your image.
let form = $("#form_id");
$.ajax({
url : $(form).attr("action"),
type: "POST",
dataType: "json",
processData: false,
contentType: false,
cache: false,
data: new FormData(form[0]),
success:function(data){
},
error: function (xhr, status, e) {
}
});
#Yogesh Patel
when i use this code:
$('#account-form-btn2').on('click', function(e) {
let form = $("#account-form");
$.ajax({
url: $(form).attr("action"),
type: "POST",
dataType: "json",
processData: false,
contentType: false,
cache: false,
data: new FormData(form[0]),
error: function (e) {
if (e.responseText == 'title-empty') {
av.showInvalidTitle();
}
},
success: function (responseText, status, xhr, $form) {
if (status == 'success') {
$('.modal-alert').modal('show');
}
}
});
});
for some reason it sends the values to "routes" three times.
and it doesn't catch the erorrs or success.
and it sends me to a white window with the value of the callback.
if needed, i can send the function that gets the values and returns them (app.post).

jqgrid onclickSubmitLocal using ajax

I am using the example here as a starting point. Everything works fine, I can submit the data back to the server and get a response. However I don't know how to connect the callback from the ajax to the jqgrid onclickSubmitLocal. I don't want to use alerts because even if there is an error the row is updated. I would like some how if there is an error the modal edit dialog to show the error and prevent it from updating the row. On success I would like the user to get a message saying data was saved.
Here is the relevant code:
function submitData(rowData){
var dataToSend = JSON.stringify(rowData);
$.ajax({
url: '/save',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: dataToSend,
dataType: 'json',
success: function (result) {
alert(' successfully saved.');
},
error: function(xhr, status, error) {
alert('Error processing submit ' + xhr.responseText);
}
});
}
I called the previous function from
onclickSubmitLocal = function (options, postdata) {
var $this = $(this), p = $(this).jqGrid("getGridParam"),// p = this.p,
idname = p.prmNames.id,
id = this.id,
idInPostdata = id + "_id",
rowid = postdata[idInPostdata],
addMode = rowid === "_empty",
oldValueOfSortColumn,
newId,
idOfTreeParentNode;
... same as in example from link above
if (postdata[p.sortname] !== oldValueOfSortColumn) {
// if the data are changed in the column by which are currently sorted
// we need resort the grid
setTimeout(function () {
$this.trigger("reloadGrid", [{current: true}]);
}, 100);
}
// !!! the most important step: skip ajax request to the server
options.processing = true;
submitData([postdata]);
},

how to read response from ajax

I have a form and it reads another js file which has ajax. and then the formauthentication file in php.
now the response
is
"hasError":true,"errors":{"lastname":"lastname</b> is required.","firstname":"firstname</b> is required.","email":"e-mail</b> is required
notice the hasError is true.
now i am reading this through google chrome. how do i read this value on the webpage itself.
i want to use if hasError is true then do something. but i cannot and don't want to touch the ajax js file but in this page itself.
ajax code in a js file code
$.ajax({
type: 'POST',
headers: { "cache-control": "no-cache" },
url: callingFile + '?rand=' + new Date().getTime(),
async: false,
cache: false,
dataType : "json",
data: 'ajax=true&'+params+'&token=' + static_token ,
success: function(jsonData)
{
if (jsonData.hasError)
{
var tmp = '';
var i = 0;
for(var error in jsonData.errors)
//IE6 bug fix
if(error !== 'indexOf')
{
i = i+1;
tmp += '<li>'+jsonData.errors[error]+'</li>';
}
tmp += '</ol>';
var errors = '<b>'+txtThereis+' '+i+' '+txtErrors+':</b><ol>'+tmp;
$('#opc_account_errors').slideUp('fast', function(){
$(this).html(errors).slideDown('slow', function(){
$.scrollTo('#opc_account_errors', 800);
});
});
}
this is the ajax and this goes to an authentication.php file and returns a response
and works accurately as you have seen
hasError is true

responseText always returns 'undefined' even though Im using asynchrous 'success' trigger

function WyslijRequestAjaxem(){
var pole1 = document.getElementById("data_albo_czas");
var url1 = "date_time_now.php";
alert(pole1.value);
alert("xd");
$.ajax({
url: url1,
type: "get",
dataType: "html",
data: { zmienna: pole1.value},
success: OdbierzResponse
})
}
function OdbierzResponse(response) {
var p = document.getElementById("pt1");
p.innerHTML = response.responseText;
}
In the case of a html dataType for jQuery's AJAX function, the first argument passed to the success callback is the responseText, so change your function to:
function OdbierzResponse(response) {
var p = document.getElementById("pt1");
p.innerHTML = response;
}
As explained in the docs this function is passed three arguments:
The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object.
If you need the actual jqXhr object to work with you'd need to do:
function OdbierzResponse(response, status, xhr) {
var p = document.getElementById("pt1");
p.innerHTML = response;
...
}
and use xhr to access the properties or methods that you require.
function WyslijRequestAjaxem() {
var pole1 = document.getElementById("data_albo_czas");
var url1 = "date_time_now.php";
alert(pole1.value);
alert("xd");
$.ajax({
url: url1,
type: "get",
dataType: "html",
data: {
zmienna: pole1.value
},
success: function (response) {
OdbierzResponse(response); // call OdbierzResponse function with parameter here
}
})
}
Try change
p.innerHTML = response.responseText;
to
p.innerHTML = response;

Needing example to load jqplot with multiple series, date-based data from json file

Been searching and cannot find exactly what I am looking for. Need to load multiple series into one jqplot, with each series coming from its own data file.
The example here http://www.jqplot.com/tests/data-renderers.php does show how to load a series from a file, but when I convert file to have date data, then it stops working, probably just a formatting issue, but cannot solve. What am I doing wrong?
Here is the data in the txt file:
[["7/11/2011 04:00:00am",85.0],["7/12/2011 04:00:00AM",87.4],["7/13/2011 04:00:00AM",90.0]]
Here is the code:
<script class="code" type="text/javascript">$(document).ready(function(){
var line = [ ];
var ajaxDataRenderer = function(url, plot) {
var ret = null;
$.ajax({
// have to use synchronous here, else returns before data is fetched
async: false,
url: url,
dataType:'json',
success: function(data) {
ret = data;
}
});
return ret;
};
var jsonurl = "./jsondata1.txt";
plo12 = $.jqplot('chart2', jsonurl,{
title: 'AJAX JSON Data Renderer',
dataRenderer: ajaxDataRenderer,
axes: {
xaxis: {
renderer:$.jqplot.DateAxisRenderer,
tickInterval: '1 day',
tickOptions:{formatString:'%y/%m/%d'}
}
}
});
});</script>
You could use the dataRendererOptions parameter to declare possible files, like this:
plo12 = $.jqplot('chart2', jsonurl,{
title: 'AJAX JSON Data Renderer',
dataRenderer: ajaxDataRenderer,
dataRendererOptions: {file1:'name_of_file_1', file2:'name_of_file2'}
axes: {
xaxis: {
Next use for-each to iterate trough the dataRendererOptions - Object:
var ajaxDataRenderer = function(url, plot,op) {
var ret = null;
$.each(op,function(i,n) {
$.ajax({
// have to use synchronous here, else returns before data is fetched
async: false,
url: url+'/'+i,
dataType:'json',
success: function(data) {
ret[]= data;
}
}); //end ajax
});//end each
return ret;
}
This code is not testet, but the idea behind could fit your needs.

Resources