I create a xml document in jQuery as following
var xmlDocument = $('<xml/>');
var foo = $('<foo/>');
var bar = $('<bar/>');
foo.append(bar);
xmlDocument.append(foo);
and try to forwards it to the server.
$.ajax({
url : 'js/foobar.php',
type : 'POST',
precessData : false,
contentType : 'text/xml',
data : xmlDocument,
sucess : function( data ) {
alert('success');
},
error : function() {
alert('failed to send ajax request');
},
complete : function() {
alert('ajax request completed');
}
});
Even if the server echos a 'foo' only, I get the alert('ajax request completed') and not the alert('success'). What am I doing wrong? Is it the way I'm creating the xml document or is it the way I forward it to the server?
An ajax request without a xml document works fine and I get the 'foo' back.
UPDATE #1
After changing precessData to processData and sucess to success i get the failed to send ajax request dialog.
When I change the data parameter in the ajax method to
$.ajax({
...
data : {
data: xmlDocument
},
...
});
I also get the failed to send ajax request dialog.
The code on the server side should be fine cause it's only
<?php
echo 'foo';
?>
UPDATE #2
I converted my string as in AndreasAL's answer
// Convert to string instead of DOM Elements
xmlDocument = $("<wrap/>").append(xmlDocument).html();
// Url encode the string
xmlDocument = encodeURIComponent(xmlDocument);
but i still get the same dialog box (failed to send the ajax request). So i thought the error could be in my xml document and overwrote my xml document by using the code snipplet from AndreasAL's answer.
xmlDocument = $('<xml/>');
foo = $('<foo/>').appendTo(xmlDocument);
bar = $('<bar/>').appendTo(foo);
Still the same behaviour.
So I checked my xml document again and printed it in a dialog box and it looks fine.
I'm running out of ideas where the error could be ...
EDIT:
You have a typo - it's not precessData it's processData
$.ajax({
url : 'js/foobar.php',
type : 'POST',
precessData : false, // change to processData
and again in sucess which should be success
Try:
var xmlDocument = $('<xml/>'),
foo = $('<foo/>').appendTo(xmlDocument),
bar = $('<bar/>').appendTo(foo);
// Convert to string instead of DOM Elements
xmlDocument = $("<wrap/>").append(xmlDocument).html();
// Url encode the string
xmlDocument = encodeURIComponent(xmlDocument);
$.ajax({
url : 'js/foobar.php',
type : 'POST',
processData : false,
contentType : 'text/xml',
data : xmlDocument,
success : function( data ) {
alert('success');
},
error : function() {
alert('failed to send ajax request');
},
complete : function() {
alert('ajax request completed');
}
});
You are using jQuery Object through the entire process.
Write your XML like this, concatenating the string together. Not making them as DOM Object.
var xmlDocument = '<xml/>';
xmlDocument += '<foo/>';
xmlDocument += '<bar/>';
Then post it, like this
$.ajax({
url : 'js/foobar.php',
type : 'POST',
precessData : false,
contentType : 'text/xml',
data : {
data: xmlDocument //wrapped inside curly braces
},
// Here is your spelling mistake
success : function( data ) {
alert('success');
},
error : function() {
alert('failed to send ajax request');
},
complete : function() {
alert('ajax request completed');
}
});
Finally, I decided to convert the xml document and send it as a string to the server.
$xmlString = $(xmlDocument).html();
Due to the fact, that I only have to store the recieved data, it makes no difference if I'm revieving it as string or xml.
I only had to change my ajax request at everything works fine now.
$.ajax({
url : 'js/foobar.php',
type : 'POST',
data : 'data=' + xmlString,
success : function( data ) {
alert(data);
},
error : function() {
alert('failed to send ajax request');
},
complete : function() {
alert('ajax request completed');
}
});
I think you have a bug on your code on success
$.ajax({
url : 'js/foobar.php',
type : 'POST',
precessData : false,
contentType : 'text/xml',
data : xmlDocument,
success : function( data ) {
alert('success');
},
error : function() {
alert('failed to send ajax request');
},
complete : function() {
alert('ajax request completed');
}
});
use $.parseXML to manipulate XML , you are treating the xml as if it is html
http://api.jquery.com/jQuery.parseXML/
use this:
data : { xml: xmlDocument }
Post values need a key
Related
I am trying to send form data using ajax. But there's an error in ajax operation and only "error" callback function is executed.
Here's what I tried:
$("#issue_submit").click(function (e) {
console.log("clicked on the issue submit");
e.preventDefault();
// Validate the form
var procurementForm = $("#it_procuremet_form");
if($(procurementForm).valid()===false){
return false;
}
// Show ajax loader
appendData();
var formData = $(procurementForm).serialize();
// Send request to save the records through ajax
var formRequest = $.ajax({
url: app.baseurl("itprocurement/save"),
data: formData,
type: "POST",
dataType: "json"
});
formRequest.done(function (res) {
console.log(res);
});
formRequest.error(function (res, err) {
console.log(res);
});
formRequest.always(function () {
$("#overlay-procurement").remove();
// do somethings that always needs to occur regardless of error or success
});
});
Routes are defined as:
$f3->route('POST /itprocurement/save', 'GBD\Internals\Controllers\ITProcurementController->save');
Also I added :
$f3->route('POST /itprocurement/save [ajax]', 'GBD\Internals\Controllers\ITProcurementController->save');
I tried returning a simple string to the ajax call at the controller class.
ITProcurementController.php :
public function save($f3)
{
echo 'Problem!';
return;
$post = $f3->get('POST');
}
But only 'error' callback is executed. I cannot locate what is wrong. Please Help.
You are specifying that you expect json back:
// Send request to save the records through ajax
var formRequest = $.ajax({
url: app.baseurl("itprocurement/save"),
data: formData,
type: "POST",
// Here you specify that you expect json back:
dataType: "json"
});
What you send back is not json:
echo 'Problem!';
return;
This is an unquoted string, which is not valid json.
To send valid json back, you would need:
echo json_encode('Problem!');
return;
You could also remove the dataType attribute, depending on your needs.
i have a problem using ajax with a php file.
Used Code:
function deleteImage() {
$.ajax({
type : 'GET',
url : '../includes/deleteImage.php',
contentType : 'application/x-www-form-urlencoded',
data : {
method : "deleteImage",
id : "1"
},
success : function(msg) {
console.log(msg);
},
failure : function(msg) {
console.log(msg);
}
});
}
It doesn't work and the Chrome Console is showing me the following error:
GET http://localhost/MyPage/WebContent/includes/deleteImage.php?method=deleteImage&id=1
Okay, it looks like a missing file.
But when leaving the id parameter out, the request works without a problem.
I tried with different parameter names and with a plain xmlhttprequest without jquery.
The same error code is shown like above.
An other request with the same structure is working without a problem.
(http://localhost/MyPage/WebContent/includes/jsListener.php?method=showMainSiteEditor&id=4)
My local server is XAMPP and i'm testing in Google Chrome.
Please can you share error message and deleteImage.php code
still you can try some like:
pass direct data string
data :'method=deleteImage&id=1'
instead of
data : {
method : "deleteImage",
id : "1"
}
and use full URL too.
your code working perfect on my end with both post and get method try to give full url in method
function deleteImage() {
$.ajax({
type : 'GET',
url: "includes/ajax_response.php",
contentType : 'application/x-www-form-urlencoded',
data : {
method : "deleteImage",
id : "1"
},
success : function(msg) {
alert(msg);
console.log(msg);
},
failure : function(msg) {
console.log(msg);
}
});
}
and ajax_response.php
if($_REQUEST['method']=='deleteImage')
{
echo $_REQUEST['method'].$_REQUEST['id'];
}
Ok I am banging my head against my desk.
I am posting to a method in my php script and I am returning a json array
public function test()
{
return json_encode($this->runResults() );
exit;
}
}
echo of above (echo json_encode($this->runResults() ) will give you this below
[
{"code":"123456","date_created":"2012-07-09","date_expires":null},{"code":"3453432","date_created":"2012-07-09","date_expires":null},
{"code":"3sdf324","date_created":"2012-07-09","date_expires":null},
{"code":"weewr22","date_created":"2012-07-09","date_expires":"2012-07-19"}
]
now in my javascript I have this
$.ajax({
url : 'test',
type : 'POST',
data : {
data1: adataval,
data2: bdataval
},
success : function(data) {
alert(data.length);
},
error : function() {
}
});
and this alerts out in 1000s as it reads every single character..where as I was hoping that the length should have been 4. so then I change the above ajax to this
$.ajax({
url : 'test',
type : 'POST',
datatype: 'json'
data : {
data1: adataval,
data2: bdataval
},
success : function(data) {
alert(data.length);
},
error : function() {
}
});
as you can see I added datatype: 'json'. but then I started getting
Uncaught Error: NOT_FOUND_ERR: DOM Exception 8
what am I doing wrong?
Try this PHP Script
public function test()
{
echo json_encode($this->runResults());
}
Update :
also in ajax method
use dataType not datatype
alert( $.parseJSON(data).length );
Also, in your script, you should set the content-type to json: header('Content-type: application/json');
i am sending an ajax request on a mouse over event and I am receiving the desired response.
But when i send again hover on the element whose request was sent, the request is sent again.
i do not want to send the request again, rather i want the page to use the response previously received.
Who to do it?? here is a sample code. - > this function is being called on mouse over, do not want to send request again on the same mouse over element.
function showImage(val)
{
$("#DIV").html('<IMAGESOURCE="../adsd/ajax_loader.gif">');
$.ajax({
type : "get",
cache : false,
url : "blabla.php?imgID="+val,
data : $(this).serializeArray(),
success: function(data) {
document.getElementById("DIV").innerHTML = data;
}
});
};
Set a variable to a value when the response is received and check for that variable before send ing the request.
var response = false;
function showImage(val)
{
$("#DIV").html('');
if (response == false) {
$.ajax({
type : "get",
cache : false,
url : "blabla.php?imgID=" + val,
data : $(this).serializeArray(),
success: function(data)
{
document.getElementById("DIV").innerHTML = data;
response = true;
}
});
} else {
// What to do if the request was sent before
}
};
What I think is you need to use jQuery.data() on mouseover do
if(!jQuery.data(dom, 'sent')){
//take action
jQuery.data(dom, 'sent', true);// do it on success
}
Here a sample use case:
I request a simple form via an ajax request. I want to submit the result to the same page that I requested. Is there a way to access the URL of that request in the resulting request's javascript?
Below is some code that accomplishes what I want via javascript AND PHP. The downside to this is that I have to include my javascript in the same file as myajaxform.php. I'd rather separate it, so I can minify, have it cached etc.
I can't use location.href, b/c it refers to the window's location not the latest request.
frm.submit(function () {
if (frm.validate()) {
var data = frm.serialize();
jQuery.ajax({
url : '<?= $_SERVER['PHP_SELF'] ?>',
type : 'POST',
data : data,
dataType: "html",
success : function (data) {
}
});
}
return false;
});
If there's not a way to access it via javascript directly, how would you solve this problem so that the javascript can go in it's own file? I guess that I could in the original ajax request's success handler, create some sort of reference to the URL. Thoughts? Maybe something using the jQuery data method?
You can store the url to submit to in the action attribute of the form, and then set the url to frm.action:
jQuery.ajax({
url : frm.action,
type : 'POST',
data : data,
dataType: "html",
success : function (data) {
}
});
Forgive me if I totally misinterpret your question, as I find it somewhat confusing. What about
frm.submit(function () {
if (frm.validate()) {
var data = frm.serialize();
jQuery.ajax({
url : window.location.href,
type : 'POST',
data : data,
dataType: "html",
success : function (data) {
}
});
}
return false;
});