Ajax send request but php don't get any $_POST - javascript

jquery version: 3.6.0
php version: 8.1.4
Trying to pass POSt but php gets empty $_POST
index.html
<button onclick="func()">Click me</button>
<script>
function func()
{
var eventID = "test";
$.ajax({
url: "test.php",
method: "POST",
data: {'variable': eventID },
success: function (response) {
console.log(response)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
</script>
test.php
<?php
if (isset($_POST['variable']))
{
echo($_POST['variable']);
}
else
{
echo ("failure");
}
?>
edit:
PHP ReQuest
https://pastebin.com/ASjjxAm1
var_dump
failurearray(0) {
}
I tried every configuration. I think I'm losing my mind

Related

Send multiple parameters to PHP (Ajax)

I'm stuck here when passing or sending multiple parameters on Ajax. It only works when I pass one. Here the Ajax code:
$.ajax({
type: "POST",
url: "dataCartas.php",
data: {valorXY: valorXY,
CentroX: CentroX},
success: function(msg){
// return value stored in msg variable
console.log(valorXY + CentroX)
}
});
And the PHP code:
$valorXY = $_POST['valorXY'];
$CentroX = $_POST['CentroX'];
include "configX.php";
if ($conn){
$sql="EXEC sp_InsertaComID #ComID = '".$valorXY."', #DR =
'".$CentroX."'";
if ($rs=sqlsrv_query($conn,$sql)){
}else{
echo (print_r(sqlsrv_errors(), true));
}
}else{
die(print_r(sqlsrv_errors(), true));
}
Sorry for my bad english :(
You can serialize a form
$.ajax({
type: 'post',
url: 'include/ajax.php',
data: $('#form').serialize(),
success: function (response) {
// do something
},
error: function(jqxhr,textStatus,errorThrown){
console.log(jqxhr);
console.log(textStatus);
console.log(errorThrown);
}
});
you can also use form data https://stackoverflow.com/a/8244082/3063429

php sending values to ajax faild error

I Am trying to send value from ajax to php and retrieve it just to test that everything is work, when i click in a button to test i got error and alert('Failed') Appears , how can i fix it in order to get success? thanks
Ajax :
var a = "test";
$.ajax({
url: "search.php",
dataType: "json",
data: a ,
success: function(data) {
alert('Successfully');
},
error: function(data) {
alert('Failed');
}
})
PHP :
<?php
$pictures = "img1";
echo json_encode($pictures);
?>
I refined your code slightly and it works.
var a = "test";
$.ajax({
type: 'POST',
url: 'search.php',
data: 'a=' + a,
dataType: 'json',
cache: false,
success: function (result) {
alert('Successful');
},
error: function (result) {
alert('Failed');
}
});
If you're requesting a JSON, use the $.getJSON from jQuery, it's aready parse the JSON into a JSON object for you.
Seems that you're not return an actual JSON from server, maybe this is what is causing the error.
If you're seeing the 'Failed' message probably the problem is a 500 error which is a server error.
Try this code above.
Javascript:
var a = "test";
$.getJSON("search.php", {
a: a
}, function (json) {
console.log(json);
});
PHP:
<?php
$pictures = ["img1"];
echo json_encode($pictures);
The only way to this not work, is if you have a huge mistake on you webserver configuration.
Your ajax is wrong, it should be:
var a = "test";
$.ajax({
type: "POST",
url: "search.php",
dataType: "json",
data: {a:a},
success: function(data) {
alert('Successfully');
},
error: function(data) {
alert('Failed');
}
});

Transfer data from Ajax to php

i am trying to send datas from ajax to php, but php doesnt show it. both scripts are on the same site: "testpage.php".
jQuery/Ajax:
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$("#button").click(function() {
var test = "bla";
$.ajax({
url: "testpage.php",
type: "post",
data: test,
success: function (response) {
alert("test ok");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
});
</script>
PHP:
<?php
if(isset($_POST["test"])) {
$test2 = $_POST;
echo $test2;
echo "Test";
}
?>
I do not see the result of PHP
use data: {test:test}, & alert your response to see your result.
success: function (response) {
alert(response);
},
Or Just append your response to html.
You need to use data: {test:sometext} if you want to do a POST request.
The PHP can't see the value in the post because you only send bla in the PHP body. You have to send test=bla. But jQuery can do it automatically by sending data : { test : test }.
$(document).ready(function() {
$("#button").click(function() {
var test = "bla";
$.ajax({
url: "testpage.php",
type: "post",
data: {
test : test
},
success: function (response) {
alert("test ok");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
});
You can use serialize() method into your $.ajax();
Something like:
$.ajax({
url: "testpage.php",
type: "post",
data: $("#myForm input").serialize(),
success: function (response) {
alert("test ok");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
Then try to accessing your post data by form input name.
var data = {
'test': "bla",
};
$.ajax({
type: "POST",
url: "testpage.php",
data: data,
dataType: "json"
}).done(function(response){
console.log(response);
}).fail(function(response){
console.log(response);
});

Jquery/php output custom error messagge

I have an Ajax autocomplete box on an input field of a form. In jquery, I have the following ajax settings
$.ajax({
type: "POST",
url: myUrl,
data: $("#id__form").serialize(),
success: function(data){
alert("do something");
},
error: function (xhr, textStatus, thrownError) {
alert(xhr.status+ " "+ thrownError+ " " + textStatus);
},
dataType: "json"
});
On the server side, I have this php code
$data = array('type' => 'error', 'message' => 'Error: '.$text);
header('HTTP/1.1 400 Bad Request');
header('Content-Type: application/json; charset=UTF-8');
die(json_encode($data));
All works fine both in case of success and in case of error. However, I didn't figure out how do I access from jquery the text I defined in php as $text
xhr.status is 400, textStatus is "error" and thrownError is "Bad Request", but no signs of what I defined as $text
What I am missing?
if you echo the $text variable in your file you can get to it from your javascript file.
php code:
echo $text;
change to javascript:
$.ajax({
type: "POST",
url: myUrl,
data: $("#id__form").serialize(),
success: function(data){
//do something with the data returned from php file
alert(data);//<---change to javascript code
},
error: function (xhr, textStatus, thrownError) {
alert(xhr.status+ " "+ thrownError+ " " + textStatus);
},
dataType: "json"
});
In your ajax post you defined a json call. In your php backend you defined a array, so you can access these params by key. Your array:
<?php
$arr = array();
$arr['message'] = 'What you like?';
$arr['errorCode'] = '12345';
die(json_encode($arr));
?>
In your case you will have access the data argument by adding the key, like data.message:
success: function(data){ alert(data.message); }
So, it have to look like that:
$.ajax({
type: "POST",
url: myUrl,
data: $("#id__form").serialize(),
success: function(data){
alert(data.message+' '+data.errorCode);
$('#someDivTag').html(data.message);
},
dataType: "json"
});
Got it, thanks to this article http://wingkaiwan.com/2012/10/21/deserialize-error-in-json-for-jquery-ajax/
The problem was that the variable data in the success callback handles automatically json, but I had to parse it in the error callback. This works:
error: function (xhr, ajaxOptions, thrownError) {
var error = JSON.parse(xhr.responseText);
alert(error.message);
}

Post data from ajax request empty in PHP

Here is my javascript code :
var json = JSON.stringify(data);
$.ajax({
data: {data : json },
type: 'POST',
url : 'test.php',
success: function( data, textStatus, jqXHR) {
alert(data);
alert(textStatus);
alert(jqXHR);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR);
alert(textStatus);
alert(errorThrown);
}
});
Here is my test.php :
var_dump($_POST);
success function returns correctly the data
array(1) {
["data"]=>
string(51) "["image_0","image_1","image_2","image_3","image_4"]"
}
But in my test.php var_dump() return an empty array..
array(0) { }
What I'm doing wrong ?
Why cant you simplify like
$.ajax({
data: JSON.stringify(data)
...
});
It's ok I understand my mistake. Sorry but I'am newbie in javascript.
In my test.php:
if(isset($_POST["data"])) {
$_SESSION["test"] = $_POST["data"];
}
echo $_SESSION["test"];

Categories

Resources