jquery ajax request not working on remote server - javascript

This is the first time i am trying to upload my work on a webhost from localhost.I have an ajax request to submit a form and get somre response from the server.But the success method is not triggering ,instead error method is triggering.Though it is working fine on localhost but for some reason it is not working on remote server.I think it is the url in the ajax request which is not getting the file though it is fine on localhost.What might be the reason for this and how i can fix this?
i checked all the sql related with this ajax request.ALl working fine .
my domain name is :ezphp.tk
my question is is attaching the file location in the url is enough like i did or i had to treat it with something like http://mydomain/filepath.....
ajax submission :
$.ajax('../includes/verifyanswer.php',{
data:{
'answer_body': CKEDITOR.instances.content.getData(),
'userpost_post_id': <?php echo $postid;?>,
'users_user_id': <?php echo $userdata->user_id; ?>
},
type:"POST",
dataType:'json',
success:function(response){
alert('bal');
var obj=response;
alert(obj[0].answer_body);
$('#mainanswer').hide();
$('#answerform').hide();
$('#answerthisquestion').show();
var str="<div class='styleanswer' >"+obj[0]['answer_body']+"</div><div class='customcmntholder'></div><span id='customcomment' class='cmnt' onclick='letmecomment(event);'>Add a Comment...</span><form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='post' name='cmntform'> <textarea data-id="+obj[0]['answer_id']+" class='customcmntform' placeholder=' add a comment......' ></textarea></form><hr>";
$('#answerwrapper').append(str);
$('#answerwrapper pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
},
error:function(response){
alert('there are some errors');
}
});
verifyanswer.php file is :
require_once '../core/init.php';
$answer=$_POST['answer_body'];
$post_id=$_POST['userpost_post_id'];
$answerer=$_POST['users_user_id'];
if(isset($answer,$post_id,$answerer)){
if(!empty($answer) && !empty($post_id) && !empty($answerer)){
$db=DB::getInstance();
$result=$db->post_and_fetch("CALL login.post_and_fetch_ans(?,?,?)",array($answer,$post_id,$answerer))->result();
echo json_encode($result);
}
}

I think your problem is ajax cross domain.
You can set in php file by code:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
Or reference here to resolve it

first, you needs to check what exactly error you get from your ajax request, is this caused by cors or something else
change your jquery error function like below:
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
if you using shared hosting for your website, then you need to allow your web is can access from all origin using this, there are several ways to allow cross origin:
in your resuested php file: added header to allow your acces origin using this : header("Access-Control-Allow-Origin: *");
or you can config all your web using .httaccess
for more info about cors enable, you can visit here enable-cors.org

On your first php page when you call the ajax function try either of these two method:
<!-- This is your form -->
<form name="yourForm" id="yourForm" method="post" action="http://yourdomain.com/includes/verifyanswer.php" novalidate >
<input type="submit" />
</form>
This is method to call ajax after form submission:
$('#yourForm').on('submit',(function(e) {
e.preventDefault();
var formData = $(this).serialize();
$.ajax({
type:'POST',
url: $(this).attr('action'),
dataType: "json",
data:formData,
processData: false,
success:function(data){
alert(data);
},
error: function(data){
alert('there are some errors');
}
});
}));
This is to call ajax through your custom function:
function testFunction()
{
var yourparam1 = "abc";
var yourparam2 = "123";
$.ajax({
type: "POST",
url: "http://yourdomain.com/includes/verifyanswer.php",
dataType: "json",
data: {
param1 : yourparam1,
param2 : yourparam1
},
success: function(data) {
alert(data);
},
error: function(data){
alert('there are some errors');
}
});
}
Add this line on top of your php page from where you are getting ajax json data:
// PHP headers (at the top)
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
$output = "Hello world";
echo json_encode($output);

Related

Where do PHP echos go when you are posting to a page?

This might be a dumb question. I'm fairly new to PHP. I am trying to get a look at some echo statements from a page I'm posting to but never actually going to. I can't go directly to the page's url because without the post info it will break. Is there any way to view what PHP echos in the developer console or anywhere else?
Here is the Ajax:
function uploadImage(image) {
var data = new FormData();
data.append("image", image);
imgurl = 'url';
filepath = 'path';
$.ajax({
url: imgurl,
cache: false,
contentType: false,
processData: false,
data: data,
type: "post",
success: function(url) {
var image = $('<img class="comment_image">').attr('src', path + url);
$('#summernote').summernote("insertNode", image[0]);
},
error: function(data) {
console.log(data);
}
});
}
And here is the php file:
<?php
$image = $_FILES['image']['name'];
$uploaddir = 'path';
$uploadfile = $uploaddir . basename($image);
if( move_uploaded_file($_FILES['image']['tmp_name'],$uploadfile)) {
echo $uploadfile;
} else {
echo "Unable to Upload";
}
?>
So this code runs fine but I'm not sure where the echos end up and how to view them, there is more info I want to print. Please help!
You already handle the response from PHP (which contains all the outputs, like any echo)
In the below code you have, url will contain all the output.
To see what you get, just add a console.log()
$.ajax({
...
success: function(url) {
// Output the response to the console
console.log(url);
var image = $('<img class="comment_image">').attr('src', path + url);
$('#summernote').summernote("insertNode", image[0]);
},
...
}
One issue with the above code is that if the upload fails, your code will try to add the string "Unable to upload" as the image source. It's better to return JSON with some more info. Something like this:
// Set the header to tell the client what kind of data the response contains
header('Content-type: application/json');
if( move_uploaded_file($_FILES['image']['tmp_name'],$uploadfile)) {
echo json_encode([
'success' => true,
'url' => $uploadfile,
// add any other params you need
]);
} else {
echo json_encode([
'success' => false,
'url' => null,
// add any other params you need
]);
}
Then in your Ajax success callback, you can now check if it was successful or not:
$.ajax({
...
dataType: 'json', // This will make jQuery parse the response properly
success: function(response) {
if (response.success === true) {
var image = $('<img class="comment_image">').attr('src', path + response.url);
$('#summernote').summernote("insertNode", image[0]);
} else {
alert('Ooops. The upload failed');
}
},
...
}
If you add more params to the array in your json_encode() in PHP, you simply access them with: response.theParamName.
Here is a basic example...
HTML (Form)
<form action="script.php" method="POST">
<input name="foo">
<input type="submit" value="Submit">
</form>
PHP Script (script.php)
<?php
if($_POST){
echo '<pre>';
print_r($_POST); // See what was 'POST'ed to your script.
echo '</pre>';
exit;
}
// The rest of your PHP script...
Another option (rather than using a HTML form) would be to use a tool like POSTMAN which can be useful for simulating all types of requests to pages (and APIs)

jQuery ajax not passing post data to php page

I try to get post data from using alert() and its worked problem is that data is not passing to php page result is always {"success":false,"result":0}
What I want is send password to php page and hash it using password_hash() and return result
$('#spass').on('submit',function(){
var that=$(this),
contents=that.serialize();
alert(contents);
$.ajax({
url:'passwordhashing.php',
dataType:'json',
data:contents,
success:function(data){
alert(JSON.stringify(data));
console.log(data);
}
});
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="spass" >
<h4>Change Your Password</h4>
<input type='password'name="passc" >
<!--<input type='password' name="cpass" id="cpass"> -->
<input type="submit">
</form>
**this my php code**
<?php
header('Content-type: text/javascript');
$json=array(
'success'=>false,
'result'=>0
);
if(isset($_POST['passc']) && !empty($_POST['passc'])) {
$pass=password_hash($_POST['passc'],PASSWORD_DEFAULT);
$json['success']=true;
$json['result']=$pass;
}
echo json_encode($json);
?>
You can test that your data has not actually been passed to a PHP page.
In the PHP code, do the following: echo $ _POST ['YOUR_VARIABLE'].
Check the INSPECT_ELEMENT / NETWORK browser to make sure you actually send data to the correct link. Your link may be relative, so you may be sending data to the wrong link.
So, try to put the entire link in the ajax url
$ .ajax ({
url: 'HTTP: //WHOLE_LINK_IN_HERE.COM/passwordhashing.php',
});
SET method in Ajax: type: "POST"
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
**i used $.post() instead of using $.ajax() and it fix my problem**
$('#spass').on('submit',function(){
var that=$(this),
contents=that.serialize();
alert(contents);
$.post({
url:'passwordhashing.php',
dataType:'json',
data:contents,
success:function(data){
alert(JSON.stringify(data));
console.log(data);
}
});
return false;
});

Header PHP not working after AJAX call from Javascript

so, this is probably a dumb question, but is it possible to execute the header function in a php file if I'm getting a response with AJAX?
In my case, I have a login form that gets error codes from the PHP script (custom error numbers hardcoded by me for testing) through AJAX (to avoid reloading the page) and alerts the associated message with JS, but if the username and password is correct, I want to create a PHP cookie and do a redirect. However I think AJAX only allows getting data, right?
This is my code:
JS
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
var responseCode = parseInt(response);
alert(codes[responseCode]);
}
});
PHP
if(empty($user)){
echo 901;
}else{
if(hash_equals($user->hash, crypt($password, $user->hash))){
setCookie(etc...); //this is
header('admin.php'); //what is not executing because I'm using AJAX
}else{
echo 902;
}
}
Please sorry if the question doesn't even make sense at all but I couldn't find a solution. Thanks in advance!
EDIT: I did not include the rest of the code to avoid complicating stuff, but if you need it for giving an anwser I'll add it right away! (:
You're right, you can't intermix like that. The php would simply execute right away, since it has no knowledge of the javascript and will be interpreted by the server at runtime, whereas the js will be interpreted by the browser.
One possible solution is to set a cookie with js and redirect with js as well. Or you could have the server that receives the login request set the cookie when the login request succeeds and have the js do the redirect after it gets a successful response from the server.
You can't do like that because ajax request process in backed and return the particular response and if you want to store the cookies and redirect then you should do it in javascript side while you get the response success
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
var responseCode = parseInt(response);
alert(codes[responseCode]);
window.location = "admin.php";
}
});
if(empty($user)){
setCookie(etc...); //this is
echo 901;
}else{
if(hash_equals($user->hash, crypt($password, $user->hash))){
echo response// what every you want to store
}else{
echo 902;
}
}
If the ajax response satisfies your condition for redirection, you can use below:
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
var responseCode = parseInt(response);
alert(codes[responseCode]);
window.location="%LINK HERE%";
}
});
It's kind of ironic that you use ajax to avoid loading the page, but you'll be redirecting in another page anyway.
test sending data in json format:
Javascript
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
if(response.success){
window.location="%LINK HERE%";
}else{
var responseCode = parseInt(response.code);
alert(responseCode);
...
}
}
});
PHP
header("Content-type: application/json");
if(empty($user)){
echo json_encode(['success' => false, 'code' => 901]);
}else{
if(hash_equals($user->hash, crypt($password, $user->hash))){
echo json_encode(['success' => true, 'data' => response]);
}else{
echo json_encode(['success' => false, 'code' => 902]);
}
}

codeigniter or PHP - how to go to a URL after a specific AJAX POST submission

I am successfully inserting data into my database in codeigniter via a an ajax post from javascript:
//JAVASCRIPT:
$.ajax({
type: "POST",
url: submissionURL,
data: submissionString,
failure: function(errMsg) {
console.error("error:",errMsg);
},
success: function(data){
$('body').append(data); //MH - want to avoid this
}
});
//PHP:
public function respond(){
$this->load->model('scenarios_model');
$responseID = $this->scenarios_model->insert_response();
//redirect('/pages/view/name/$responseID') //MH - not working, so I have to do this
$redirectURL = base_url() . 'pages/view/name/' . $responseID;
echo "<script>window.location = '$redirectURL'</script>";
}
But the problem is that I can't get codeigniter's redirect function to work, nor can I get PHP's header location method to work, as mentioned here:
Redirect to specified URL on PHP script completion?
either - I'm guessing this is because the headers are already sent? So as you can see, in order to get this to work, I have to echo out a script tag and dynamically insert it into the DOM, which seems janky. How do I do this properly?
Maybe you can 'return' the url in respond function and use it in js
PHP :
public function respond(){
// code
$redirectURL = base_url() . 'pages/view/name/' . $responseID;
return json_encode(['url' => $redirectURL]);
}
JS :
$.ajax({
type: "POST",
url: submissionURL,
data: submissionString,
dataType: 'JSON',
failure: function(errMsg) {
console.error("error:",errMsg);
},
success: function(data){
window.location = data.url
}
});
you have to concatenate the variable. That's all.
redirect('controller_name/function_name/parameter/'.$redirectURL);

Codeigniter ajax CSRF problem

I've made a simple autoload function that loads content when you scroll down on a website. However, there seems to be a few problems when i enable CSRF protection in Codeigniter.
I'm not using a form, so i don't know how i can send the token from A to B when i'm doing my post request as you scroll.
My JavaScript
if (location.href == baseurl) {
$(window).scroll(function(){
if ($(window).scrollTop() > $('body').height() / 2) {
if(doScroll == 1) {
$.post(baseurl + 'ajax/images',{'id' : ID}, function(data) {
$("#wrapper_content").append(data);
if(data == 'Det finnes ikke flere bilder i databasen, WTF!? Send inn forslag ASAP!') {
doScroll = 0;
}
ID++;
});
}
}
});
}
Since Codeigniter expects a TOKEN on all POST request i can't get this to work when CSRF i enabled. Any suggestions?
Error when CSRF is Enabled
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
If i turn CSRF off, everything works great...
You might like to try this code I've used. It works great:
<script type="text/javascript">
$(function(){
$('.answerlist').each(function(e){
$(this).click(function(){
var valrad = $("input[#name=answer]:checked").val();
var post_data = {
'ansid': valrad,
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
};
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>online/checkanswer",
data: post_data,
success: function(msg){
/// do something
}
});
});
});
});
</script>
As others say - you have to post the CSFR token name and its value with the AJAX request parameters. Here is a simple solution to append it automatically to every AJAX request.
Here is what I put on my main view, so this code is on every page before loading the other javascript files:
<script>
var csfrData = {};
csfrData['<?php echo $this->security->get_csrf_token_name(); ?>']
= '<?php echo $this->security->get_csrf_hash(); ?>';
</script>
<!-- ... include other javascript files -->
</body>
</html>
And here is a part of a javascript file that I include on every page:
$(function() {
// Attach csfr data token
$.ajaxSetup({
data: csfrData
});
});
If you want, you can echo both the token name and the hash somewhere appropriate. Something like this.
echo $this->security->get_csrf_token_name()
and
echo $this->security->get_csrf_hash()
Or, you could use form_open() as usual and use the hidden input that is generated for you from your javascript. Disabling the CSRF-functionality is the wrong way to go.
Having reviewed my situation I believe the best option is to use CSRF but reset the token on each attempt. Otherwise the ideas expressed earlier about re-using the cookie token would allow an attacker to resubmit data hundreds of times using the same token which defeats the object of the point.
As such I have created the following function:
public function resetCSRF(){
$this->security = null;
$_COOKIE[$this->config->item('csrf_cookie_name')] = null;
load_class('Security', 'core');
$this->security->csrf_set_cookie();
return $this->security->get_csrf_hash();
}
If for example an ajax based login form fails - call this function in your PHP and then on the javascript side that receives the failure (this solution uses Jquery and a getCookie function from w3schools) would then simply call:
$('input[name="csrf_test_name"]').val(getCookie('csrf_cookie_name'));
Basically what you need to do is get the expected csrf value from the cookie (named 'ci_csrf_token' by default), then post it along with your other data.
You would need to modify this line:
$.post(baseurl + 'ajax/images',{'id' : ID}, function(data) {
to:
$.post(baseurl + 'ajax/images',{'id' : ID,'ci_csrf_token' : $.cookie('ci_csrf_token')}, function(data) {
Might need to install the cookie addon (I'm not really sure; I use mootools). Here is more information: http://aymsystems.com/ajax-csrf-protection-codeigniter-20.
Previous suggestions work great, but rather than using a variable that you can apply in every data-post, I find it simpler to use the ajax-setting to automatically apply this token to every post:
$(document).ajaxSend(function(elm, xhr, s){
if(s.data){
s.data += '&';
}
s.data += '<?php echo $this->security->get_csrf_token_name(); ?>=<?php echo $this->security->get_csrf_hash(); ?>';
});
(works with jquery-1.9.1. I'm not sure about other jquery-versions)
The only problem with a few of the above answers is that a csrf token is only valid for one request, so if you make a post request via ajax and do not refresh the page you will not have the current csrf token for your next ajax post request. This is my solution:
In your CodeIgniter Controller:
$data = array('data'=> 'data to send back to browser');
$csrf = $this->security->get_csrf_hash();
$this->output
->set_content_type('application/json')
->set_output(json_encode(array('data' => $data, 'csrf' => $csrf)));
$data = the data to return to the browser
$csrf = new csrf token to be used by the browser for next ajax post request
Obviously you can output this in other ways but JSON is used mostly with ajax calls. Also include this token in every post response to be used for the next post request
Then in your next ajax request (javascript):
var token = data.csrf;
$.ajax({
url: '/next/ajax/request/url',
type: 'POST',
data: { new_data: 'new data to send via post', csrf_token:token },
cache: false,
success: function(data, textStatus, jqXHR) {
// Get new csrf token for next ajax post
var new_csrf_token = data.csrf
//Do something with data returned from post request
},
error: function(jqXHR, textStatus, errorThrown) {
// Handle errors here
console.log('ERRORS: ' + textStatus + ' - ' + errorThrown );
}
});
Also remember that where I've got csrf_token:token replace crf_token with the name of your token found in application/config/config.php on line that states $config['csrf_token_name'] = 'csrf_token';

Categories

Resources