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'];
}
Related
I have a voting function which submits a user vote using AJAX and updates the DB without having to refresh the page. All good so far. But I also want to retrive the updated values from the DB and update this on the page.
I've nested a second AJAX request inside my first request. This second request calls on the file new_values.php which gets the latest values and puts them into an array and returns as JSON like below
$new_vals = array(
'new_total' => $new_total,
'poll_option_1_val' => $poll_option_1_val,
'poll_option_2_val' => $poll_option_2_val,
);
echo json_encode($new_vals);
Below is the Ajax request - the first request works just fine to update the DB but the inner AJAX request isn't working. In the below example I try to use alert to show new_total value but nothing happens
$(function () { // SUBMIT FORM WITH AJAX
$('#poll-form').on('submit', function (e) { //on form submit
e.preventDefault(); // prevent default behaviour
if($("form")[0].checkValidity()) { // check if the form has been validated
$.ajax({ // submit process
type: 'post',
url: 'vote-process.php',
data: $('form').serialize(),
success: function () {
$('#vote_submitted').modal('show');
$("input").attr("disabled", "disabled");
$("textarea").attr("disabled", "disabled");
$("#vote_button").attr("disabled", "disabled");
$("#vote_button").text("Vote submitted");
$.ajax({
url : 'new_values.php',
type : 'POST',
data : data,
dataType : 'json',
success : function (result) {
alert(result['new_total']);
},
error : function () {
alert("error");
}
});
},
error: function() {
$('#error').modal('show');
}
});
return false;
} else { // if the form is not valid
console.log("invalid form");
}
});
});
This has been driving me crazy. Any help would be very much appreciated!
Second Ajax data:data will give you this issue need to pass proper parameter
$.ajax({
url : 'new_values.php',
type : 'POST',
data : {data_return:'yes'},
dataType : 'json',
success : function (result) {
alert(result['new_total']);
},
error : function () {
alert("error");
}
});
What is data in the second ajax request ? data : data ? data is not defined so javascript maybe stop to execute entire code especially if use 'use strict'
I am trying to make a post request in my plugin, but I am not sure if it is reaching the desired function or not. I try to echo, return value but nothing seems to work. Here is my jquery
$.post({
url: "http://localhost/tutorials/wordpress/wp-admin/admin-post.php",
type: "POST",
cache: false,
data: {
action: "add_order"
// parameters:parameters,
//orderAddress : orderAddress,
//order : order
},
success: function(response) {
console.log(response);
secondStep.hide();
pricing.hide();
$('.thirdStep').show();
}
});
My function on the WordPress server end is this
function prefix_admin_add_order() {
echo 2; // or return 2;
}
Just trying to return anything from the function and trying to console log it in the response. But it doesn't work. Any pointers?
Your Php file must be as a page template and you must address it like this :
http://yourdomain.com/ajax
and in your jquery you must put this url
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 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
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;
});