Post data from ajax request empty in PHP - javascript

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"];

Related

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

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

Firebase Dynamic Link Creation With JavaScript

var object={
"longDynamicLink": "https://[APP_NAME].page.link/?link=[LINK_HERE]",
"suffix":{
"option":"SHORT"
}
}
$.ajax({
url: 'https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=[KEY_HERE]',
type: 'POST',
dataType: "json",
data: object,
success: function(response, textStatus, jqXHR) {
alert(response.shortLink);
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
The above code works if the "suffix" is deleted from the request. That makes an "UNGUESSABLE" url, but I want a short URL. As stated in the documentation at https://firebase.google.com/docs/dynamic-links/rest?authuser=0 I added the suffix option parameter, but it results with a 400 response. Any ideas why?
I haven't ever tried this but, ...
POST https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=api_key
var params = {
"longDynamicLink": "https://example.page.link/?link=http://www.example.com/&apn=com.example.android&ibi=com.example.ios",
"suffix": {
"option": "SHORT"
}
}
$.ajax({
url: 'https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=[KEY_HERE]',
type: 'POST',
data: jQuery.param(params) ,
contentType: "application/json",
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});

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

ReferenceError: onclick function is not defined

I've gotten a "ReferenceError: function is not defined on the saveRoute function". Everything seems right to me but i could not figure out the problem.
Here is the related codes.
<script type="text/javascript">
var array = routeobj;
function saveRoute(){
var json = JSON.stringify(array)
$.ajax({
url : "http://192.168.1.9:11123/runornot/drawtrack",
type: "POST",
dataType:'json'
data : {json:json}
{"routeJson": json },
console.log("hellohelloworldolr");
success: function(data, textStatus, jqXHR)
{ //data - response from server
console.log("checkin success"); },
error: function (jqXHR, textStatus, errorThrown)
{
}});}
</script>
and in the html
Save
<script type="text/javascript">
var array = routeobj;
function saveRoute(){
var json = JSON.stringify(array) // <--- best practice would require a semicolon here
$.ajax({
url : "http://192.168.1.9:11123/runornot/drawtrack",
type: "POST",
dataType:'json' // <--- missing a comma
// the structure doesn't make any sense starting here...
data : {json:json} // <--- should be a comma here?
// missing property name?
{"routeJson": json },
// is this supposed to be the body of a function?
console.log("hellohelloworldolr");
// things start making sense again here...
success: function(data, textStatus, jqXHR)
{ //data - response from server
console.log("checkin success"); },
error: function (jqXHR, textStatus, errorThrown)
{
}});}
</script>

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

Categories

Resources