jQuery ajax not passing post data to php page - javascript

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;
});

Related

post in ajax with php get me undefined index

i want to send/pass data from the client to server by (ajax to php) but when i try this code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
type: 'post',
url: 'loo.php',
data: { data: 'some data' },
success: function(response,w) {
console.log(w);
}
});
</script>
<?php
echo $_POST['data'];
?>
in my browser i got success print out which mean that the javascript code is working fine i guess , by in php i got Undefined index
p.s my file name is loo.php all the code is in the same file
edit: i have tried to separate my files like this:
my loo.php file:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
type: 'post',
url: 'test.php',
data: {data: 'some data'},
success: function (response, w) {
console.log(w);
}
});
</script>
my test.php file:
<?php
echo $_POST['data'];
?>
still got undefined index
p.s. i navigate Manual to test.php file after i run loo.php file
You get this error because when loading the page the POST request has not yet been sent. So show the submitted data only if it exists, otherwise, show the JavaScript code.
<?php
if (isset($_POST['data'])) {
die($_POST['data']);
}
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
type: 'post',
url: 'loo.php',
data: {data: 'some data'},
success: function (response, w) {
console.log(w);
}
});
</script>
Try this.
<?php
$data = json_decode(file_get_contents('php://input'), true);
echo $data['data'];
?>
Try this
Html file
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="data_value"></div>
<script type="text/javascript">
$( document ).ready(function() {
$.ajax({
type: 'post',
url: 'loo.php',
data: { data: 'some data' },
success: function(response,w) {
$("#data_value").html(response);
}
});
});
PHP file (loo.php)
<?php
print_r($_POST);
?>
try to change the handler this way:
if(isset($_POST['data'])){
function return_data() {
die(json_encode($_POST['data'])));
}
return_data();
}
Answer after you edit the question:
$_POST is the array sent by the HTTP Post request. so if the request to the page named test.php or whatever is not HTTP POST Request the $_POST array will be empty. but the $_GET array may have some data if you sent them.
and navigation to a page is a get request to that page unless you used a form with method="post".
so what you are doing with ajax call is correct. but navigating to test.php manually without a form with post method is not gonna fill the $_POST array.
because when you make the Ajax call, it is done, it just makes the post-call correctly and everything is ok but when you navigate to that page it is a get request and it won't fill the $_POST array.
to do so, you don't need ajax at all. you can have this form
<form method="POST" action="test.php">
<input type="text" name="data" value="some data" />
<input type="submit" value="submit" />
</form>
so either you use ajax and handle whatever you want to handle in the ajax success method. or use form and send the request to the page and handle it there.
the answer to the question before the edit
If they are in the same file it won't work like that, because when the file loads the $_POST['data'] is not exists at all, and after you run the ajax call, it exists within that call, not in your browser window.
so you can check if $_POST['data'] exists so you are sending it from ajax call so you can return it and use it inside your ajax success function.
conclusion:
you cannot put them in the same file and expect ajax will load before the actual php.
it will first load the whole file then it will run the ajax.
the undefined index is from the server before you even see the HTML page.
A solution could be:
File with your html and ajax functions index.html
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
type: 'post',
url: 'loo.php',
data: { data: 'some data' },
success: function(response,w) {
// use the response here
console.log(w);
}
});
</script>
and another with your logic loo.php
<?php
header("Content-Type: text/plain"); // if you want to return a plain text
// if you want to return json it could be header('Content-type: application/json');
echo isset($_POST['data'])? $_POST['data']: ''
?>

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]);
}
}

jquery ajax request not working on remote server

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);

AJAX to PHP without page refresh

I'm having some trouble getting my form to submit data to my PHP file.
Without the AJAX script that I have, the form takes the user through to 'xxx.php' and submits the data on the database, however when I include this script, it prevents the page from refreshing, displays the success message, and fades in 'myDiv' but then no data appears in the database.
Any pointers in the right direction would be very much appreciated. Pulling my hair out over this one.
HTML
<form action='xxx.php' id='myForm' method='post'>
<p>Your content</p>
<input type='text' name='content' id='content'/>
<input type='submit' id='subbutton' name='subbutton' value='Submit' />
</form>
<div id='message'></div>
JavaScript
<script>
$(document).ready(function(){
$("#subbutton").click(function(e){
e.preventDefault();
var content = $("#content").attr('value');
$.ajax({
type: "POST",
url: "xxx.php",
data: "content="+content,
success: function(html){
$(".myDiv").fadeTo(500, 1);
},
beforeSend:function(){
$("#message").html("<span style='color:green ! important'>Sending request.</br></br>");
}
});
});
});
</script>
A couple of small changes should get you up and running. First, get the value of the input with .val():
var content = $("#content").val();
You mention that you're checking to see if the submit button isset() but you never send its value to the PHP function. To do that you also need to get its value:
var submit = $('#subbutton').val();
Then, in your AJAX function specify the data correctly:
$.ajax({
type: "POST",
url: "xxx.php",
data: {content:content, subbutton: submit}
...
quotes are not needed on the data attribute names.
On the PHP side you then check for the submit button like this -
if('submit' == $_POST['subbutton']) {
// remainder of your code here
Content will be available in $_POST['content'].
Change the data atribute to
data:{
content:$("#content").val()
}
Also add the atribute error to the ajax with
error:function(e){
console.log(e);
}
And try returning a var dump to $_POST in your php file.
And the most important add to the ajax the dataType atribute according to what You send :
dataType: "text" //text if You try with the var dump o json , whatever.
Another solution would be like :
$.ajax({
type: "POST",
url: "xxxwebpage..ifyouknowhatimean",
data: $("#idForm").serialize(), // serializes the form's elements.
dataType:"text" or "json" // According to what you return in php
success: function(data)
{
console.log(data); // show response from the php script.
}
});
Set the data type like this in your Ajax request: data: { content: content }
I think it isnt a correct JSON format.

Passing Php variable it Ajax

Hi I'm trying to pass a php variable from produto.php to another file descProduto.php it ajax but without success. Please someone can tell me what I'm doing wrong? The ajax is working but I can't get the value on descProduto.php
This is where I click produto.php
<img class="btn-details" src="plus.png" data-idproduto="'.$idproduto.'"/>
My ajax ( diferent file ajax.js)
$(function(){
$(".btn-details").on('click', function(){
var idproduto = $(this).data('idproduto');
$.ajax({
type: "POST",
url: "descProduto.php",
async: false,
dataType: "html",
data: {'idproduto': idproduto},
success: function(result){
console.log("success");
},
error: function(){
console.log("error");
}
});
return false;
});
});
Where I get the variable descProduto.php
if(isset($_POST['idproduto'])){
$idproduto = $_POST['idproduto'];
echo $idproduto;
}
Thanks
Why using AJAX ? .You can't use for this matter.just use session
In page1.php
<?php
session_start();
$_SESSION['var'] = 'foo'
In Page2.php
echo $_SESSION['var']; //foo
First of all check whether your $idproduto actually prints on produto.php (Developer Tools/ FireBug/ View Source).
Then console.log(idproduto) before sending the ajax post to see whether it sets correctly.

Categories

Resources