I have this ajax function (refer below)
$.ajax({
url: "processor.php",
type:"POST",
data: { 'id' : "itemid, 'itemname' : itemname, 'itemdesc' : itemdesc" } ,
success:function(e){
if(($.trim(e) == "success")){
alert("success");
}else{
alert(e);
}
},error:function(){
alert("critical error");
}
});
assume that I already have the linked script of jquery and the content of those variables that has been declared on the data argument inside ajax function. Now I have a processor.php (refer below)
//this is the processor php
echo "success";
so base from above references, the ajax function submit a post request to processor.php and then the processor.php will respond "success" string as declared with the "echo success" but what happen is it doesn't get the success response instead the whole html tags on the current page is pop up (alert), why?? any ideas, clues, recommendation, suggestion would be greatly appreciated. Thank you.
PS: i know the response is not success but why it popup (alert) the whole html tags in the current page?
Try this i think your are passing parameter is wrong way.i just create an example change this code as per your requirement.
$.ajax({
url: "script.php",
type:"POST",
data: { id : itemid, itemname : itemname, itemdesc : itemdesc },
success: function(data, status, settings)
{
alert(The request URL and DATA);
}
,
error: function(ajaxrequest, ajaxOptions, thrownError)
{
alert("error");
}
});
there is syntax error in posted data and you probably have a redirect to new page instead of processor.php.
EDIT
Also make sure that processor.php returns only the word "success" and there is no more html tags in the source of page.
wrong syntax:
data: { 'id' : "itemid, 'itemname' : itemname, 'itemdesc' : itemdesc" }
suggested change:
data: { id : itemid, itemname : itemname, itemdesc : itemdesc }
I've been experienced that before, check your folder and file structure and if you're running server side script (such as php) or communicating with database, check your virtual host configuration.
Related
I'm trying to pass a simple string variable with an onclick event, the request is successful but I get an empty response on the console, and the xvar variable is no coming through so I get the "NO DATA" p tag. This is my first time using Ajax so I tried to make it very simple to start. Here's my code:
JS
var xvar = 'D';
$('.test').click( () => {
$.ajax({
data: { xvar : xvar },
type: "POST",
url: 'test.php',
success: function(data, textStatus, XMLHttpRequest)
{
console.log('Success: '+data)
},
error: function(XMLHttpRequest, textStatus, errorThrown){
console.log("The request failed."+errorThrown);
}
});
});
test.PHP
$xvar = (isset($_POST['xvar'])) ? $_POST['xvar'] : '<p>NO DATA</p>';
echo $xvar;
I'm using JQuery 3.5.1 that is included with Wordpress. I'll appreciate any feedback.
EDIT
I managed to get the response on test.php as seen
here:
But I when I try to render the value with print_r is not shown.
$res = $_POST;
print_r($res);
On the data of your Ajax, try to add the quotes in the key of the data. Like this:
data: { "xvar" : xvar },
I am working on a Java application using Struts 1.2. I am facing a blocking error when I make an AJAX call to a Struts action.
The struts action, getInfos.html, is called successfully but after that when I make the AJAX call I get the following error in the console:
Invalid Character/parsing error
The data variable is a correct JSON format. Why would it trigger this error?
I've gone through all the similar questions online but I don't know why it's triggering an invalid character error.
$.ajax({
type: "POST",
url: "getInfos.html",
dataType: "json",
async: false,
cache: false,
data: {
Code: "code1",
type: "type",
mand: "mand",
signature: "signature"
},
success: function(data) {
console.log('succes');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log('my error is : ' + errorThrown);
}
});
In the execute method that is handling the ajax request, i am calling the attributes using the request
final String code = (String) request.getAttribute("code");
final String signature = (String) request.getAttribute("signature");
final String type= (String) request.getAttribute("type");
/*
Making a call to a webservice using the attributes bellow,
using **response** Object
*/
if (reponse != null &&
(CodeReponseHttp.OK.equals(reponse.getCodeReponse()))) {
jsonObj.put(SUCCESS_CALL, true);
} else {
jsonObj.put(SUCCESS_CALL, false);
}
return new JsonResult(jsonObj);
But they are set to null; which means that the ajax data is not passed into the request, when I debug the execute method and I explicitly set values to these attributes everything works fine.
new JsonResult(jsonObj) is a generic class with a constructor that accepts a JSONObject
Like Rory McCrossan Comment it could be the response you got is not a json and your code expect a json response
When i comment dataType param it work fine
$.ajax({
type : "POST",
url : "getInfos.html",
//dataType : "json",
async: false,
cache: false,
data: JSON.stringify({
Code : "code1",
type : "type",
mand : "mand",
signature : "signature"}),
success : function(data){
console.log('succes');
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
console.log('my error is : ' + errorThrown);
}
});
The problem had been solved, after debugging, the response type was not a JSON since there is a redirection to an error page if an exception is thrown, the exception was thrown because the data attributes were null, and it turned out that they are parametres not attributes, so getting the parameters solved the problem.
request.getParameter("code");
thank you all for your collaboration.
Hi there is it possible to redirect to another page using ajax? I have this piece of code that I have been working on to try this.
<script type="text/javascript">
$(document.body).on('click', '#btnPrintPrev', function() {
$.ajax({
url: '/pdfdatacal',
data: {
dummydata: "This is a dummy data"
},
});
});
</script>
Now it should be able to carry data to another page and redirect there. Problem is it doesn't.
This is what I am using in my route
Route::get('/pdfdatacal', 'GenerateReportController#pdfdatacal');
Then in the controller
public function pdfdatacal(Request $request) {
return $request->data['dummydata'];
}
My expected result should be a blank page containing the value of dummydata but it doesn't do that in my code. How do I accomplish this?
first your ajax must be something like
$.ajax({
url: '/pdfdatacal',
method: 'post',
data: { dummydata: "This is a dummy data" },
dataType: "JSON",
success: function(response){
console.log(response); // just to check if the data is being passed
// do something you want if ever .
}
});
then in your routes
Route::post('/pdfdatacal', 'GenerateReportController#pdfdatacal');
in your controller
public function pdfdatacal(Request $request) {
return response()->json($request->dummydata);
}
hope it helps ..
Use
window.location.href = "http://yourwebsite.com/pdfdatacal";
In your success call
The idea is that you send data to your controller, it sends back a response, then you redirect from javascript to where you want.
$.ajax({
url: '/pdfdatacal',
type : 'GET',
data : {
dummydata: "This is a dummy data"
},
success : function(data) {
window.location.href = "http://yourwebsite.com/pdfdatacal";
}
});
But if your controller does nothing with the data you send, then you don't need to use ajax at all, simple redirect using javascript.
you could use window.location.assign('your URL here!'); in the success.
success : function(data) {
window.location.assign('your URL here!');
}
I have written a simple code. In order to avoid flooding a JSON server, i want to break up the JSON response in pieces. So my jquery code should be parsing one variable ("page") to the php page that handles the JSON Oauth Request. On success, it should append the DIV with the latest responses.
My code should be working, except for the fact that my ajax post is not being received by my php file.
Here goes
archief.html
$("#klik").click(function() {
console.log("fire away");
page = page + 1;
$("#archief").load("trytocombinenewageandgettagsendates.php");
console.log(page);
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: page,
success: function() {
console.log(page);
$.get("trytocombinenewageandgettagsendates.php", function(archief) {
$('#archief').append(archief);
});
},
error: function(err) {
alert(err.responseText);
}
});
return false;
});
The php file doesn't receive anything.
var_dump($_POST);
gives me array(0) { }.
Very strange, i'd really appreciate the help!
You are sending a string instead of key-value pairs. If you want to use $_POST you need to send key-value pairs:
...
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: { 'page': page },
success: function() {
...
If you send a single value or string, you would need to read the raw input.
Also, you are sending 2 GET requests and 1 POST request to the same file. Is that intentional? Note that only the POST request will have the $_POST variable set.
Thank you for your help and not letting me post "this still doens't work" posts :)
I made the mistake of loading the "unConsulted" php file [$.get("trytocombinenewageandgettagsendates.php"] upon success. Instead, i append the response of the PHP.
The working code below:
$("#klik").click(function() {
console.log("fire away");
page = page + 1;
//$("#archief").load("trytocombinenewageandgettagsendates.php");
console.log(page);
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: { 'page': page },
success: function(response){
$("#archief").append(response);
},
error: function(err) {
alert(err.responseText);
}
});
return false;
I'm trying to send from JavaScript, by using jQuery, via AJAX, a string that might contain one or more URL's.
That text will be recieved by a CodeIgniter controller.
I'm having some errors. Sometimes it's a 404 error or other times is a 406 error depending on the way I send the data.
Right now I send it like this:
var dsPost = encodeURIComponent(base64_encode(postContent));
$.ajax({
url: "/posts/createTextPost/" + dsPost,
type: "POST",
data: "userIdWall" + "=" + userIdWall,
success: function(data, textStatus, jqXHR) {
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
The base64_encode fn is the phpjs implementation.
In the CI controller I do this:
public function createTextPost($dsPost) {
$dsPost = base64_decode(urldecode($dsPost));
}
The thing is, the data can be saved to the database but I can't understand why the 404 error.
Any ideas?
Thanks.
base64_encode() function sometimes add / in encoded string so the Codeigniter action method behaving like second paramameter
In case Encoded String like: qwqw221#1223/dds*(ewfd)
than issue with ci
string part after "/" char behaving like 2nd param
'*' is not allowed char
So you should use GET query string instead of CI param
Like
url: "/posts/createTextPost/?crypt=" + dsPost
And get query sting in CI controller action
public function createTextPost() {
$dsPost = base64_decode(urldecode($this->input->get("crypt")));
}
I would recommend to add the dsPost to your data in the AJAX call, instead of adding it as a parameter to the url:
$.ajax({
url: "/posts/createTextPost/",
type: "POST",
data: { "dsPost": dsPost, "userIdWall", userIdWall },
success: function(data, textStatus, jqXHR) {
// Yippie!
},
error: function (jqXHR, textStatus, errorThrown) {
// Bhuhuhu....
}
});
...and then update your CI controller to work with the posted object instead of the input parameter:
public function createTextPost() {
$dsPost = base64_decode( urldecode( $this->input->post('dsPost') ) );
userIdWall = $this->input->post('userIdWall');
}
You have to send the content through ajax data like below.
$.ajax({
//double check your url setting in this way in case you have diffrent setting for index.php then remove the index.php
url: "<?=base_url()?>.index.php/posts/createTextPost/",
type: "POST",
data: {
"dsPost": dsPost,
"userIdWall", userIdWall
},
success: function(data, textStatus, jqXHR) {
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
then in your controller
public function createTextPost() {
$dsPost = base64_decode( urldecode( $this->input->post('dsPost') ) );
$userIdWall=$this->input->post('userIdWall');
I hope it will help.
So, thanks for the ideas but the answer can be found here:
PHP/Apache Error:406 Not Acceptable
I quote the answer given there:
Your website is generating error if any user input item is starting
with either http:// or https:// .
When I try with a link starting with http:// I got a 406 Not
Acceptable :
http://onkore.us/?blah=http://www.google.com
It is fine when I try this :
http://onkore.us/?blah=www.google.com