Get data from PHP file using AJAX - javascript

I'm trying to get some data from a PHP file using AJAX but I get only an error:
Uncaught TypeError: Cannot read property 'protocole' of null
protocoleGenerator.php
<?php
$array = array(
'protocole' => '1029384756',
);
echo json_encode($array);
?>
script.js
function getDemoProtocol() {
$.ajax({
url: 'protocoleGenerator.php',
data: "",
dataType: 'json', //data format
success: function (data) {
var protocole = data['protocole'];
console.log("Prot: " + protocole);
}
});
}
What is wrong here?

I can't comment for now :( and write my suggestions as an answer. It seems like you have mistype in protocoleGenerator.php. May be end line looks like echo json_encode($aray);, in this case json_encode() returns pure null (if you have disable php notices). The success function receives null and can't get a property from this object. It's only my subjective suggestion. It may be wrong.
P.S: You can get value / call function as Object.my_fun(), or Object['my_func']() - for this particular case it doesn't matter how did you access to the variable. For example:
var o = {};
o.test = 'my test value';
o.fff = function() {return 'fff called.';};
console.log('dot-style:' + o.test);
console.log('arr-style:' + o['test']);
console.log('dot-style:' + o.fff());
console.log('arr-style:' + o['fff']());
Ok, I've got a minus. If assumed, that topic starter show us hard copy-paste of his code, here is no issues. My suggestion based on the error message - the "success function" gets HTTP/200 answer from the server with text "null". With empty or non-valid json response jquery-ajax calls an "error handler". I'm sure that it can't be caused by json_encode() behaviour - my example above prove it.
Another suggestion is specific server config, rewrites, redirects or something else. But I've exclude this suggestion.
Oh...
<?php
$array = array(1,2);
$аrray = array(3,4);
var_dump($array);
var_dump($аrray);
result looks like that:
array(2) {
[0] =>
int(1)
[1] =>
int(2)
}
array(2) {
[0] =>
int(3)
[1] =>
int(4)
}
Did you see the difference? I don't, but the second $array begins from cyrillic character.

I run your code in my localhost, it's working fine please check below code in your system, if you still get any error then post your whole code so I can check in my system.
index.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Json</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
function getDemoProtocol() {
$.ajax({
url: 'protocoleGenerator.php',
data: "",
dataType: 'json', //data format
success: function (data) {
var protocole = data['protocole'];
console.log(protocole);
alert(protocole);
console.log("Prot: " + protocole);
}
});
}
getDemoProtocol(); // Javascript method
// Jquery Method
$(function (){
$.ajax({
url: 'protocoleGenerator.php',
data: "",
dataType: 'json', //data format
success: function (data) {
console.log(data);
var protocole = data.protocole;
console.log("Prot: " + protocole);
}
});
});
</script>
</head>
<body>
</body>
</html>
protocoleGenerator.php
<?php
header('Content-Type: application/json');
$array = array(
'protocole' => '1029384756',
);
echo json_encode($array);
?>

This is because you are getting Error 404: not found. Check console (tick the log XHR requests checkbox).
The solution would be, changing this:
url: 'protocoleGenerator.php',
to this:
url: './protocoleGenerator.php',
Working example:
http://neolink.dyndns.org:81/stackoverflow/1.php
PS. This is weird that jQuery runs success function even when response was 404.
PS 2. If it won't work (it should!), give the full path instead (like http://blabla.com/1/3/45345/protocoleGenerator.php, as that may be server dependable)

Related

Sending POST parameters between PHP files using AJAX calls

I have a PHP file test.php that has a simple link, which after being clicked, calls an AJAX function to send data as POST parameters to another file testPHP.php. The second file then receives the POST parameters from the AJAX call and then alerts the contents inside the $_POST array. The issue I am facing is that in the second file, the $_POST array is empty (I checked that using print_r($_POST)), so I think that the data hasn't passed through.
These are the 2 files:
test.php
<a id="link" role="button" href="testPHP.php">Test</a>
<script type="text/javascript">
$("#link").click(function(e) {
e.preventDefault();
alert('function entered');
$.ajax({
url: "testPHP.php",
type: "POST",
data: {
parameter1: 'test',
parameter2: 'test2'},
success: function(msg) {
alert('wow' + msg);
}
});
alert('function end');
document.getElementById('#link').setAttribute('href','testPHP.php');
});
testPHP.php
if(isset($_GET))
{
echo "<script>alert('GET is there');</script>";
print_r($_GET);
}
if(isset($_POST))
{
echo "<script>alert('POST is there')</script>";
print_r($_POST);
}
if(isset($_POST['parameter1']))
{
echo "<script>alert('$_POST is set')</script>";
header('Location: HomePage.php');
}
else
{
echo "<script>alert('No post variable set')</script>";
}
What I have tried so far is to send a SUCCESS message if the AJAX call has been executed successfully, and it does alert me the Success message. I have also checked to see the contents of the $_POST array in the 2nd file to see if I am receiving data in a format other than a POST request (like a string that might have to be exploded to get the contents), but the $_POST array comes up empty.
This is the output I get when it redirects to the 2nd page:
Array() Array()
The $_POST and $_GET (for testing purpose) arrays come up empty.
I have also gone through the AJAX documentation, but can't get this simple POST data transfer to work. Can someone please help me with this issue so that I can understand how to properly send POST parameters and receive the data into $_POST['parameter1'] and $_POST['parameter2'] strings so I can process the data further.
Note: I have used the FORM's POST method using hidden form elements and that works fine, but I want to try this approach to better understand how AJAX works.
A slightly different version of the above which should help you solve your problem. For ease in debugging it is all one page but you can clearly see the script in operation once you click the button. Simply echoing javascript in the php code and hoping it will execute client side is not going to work - simply echo a message or a JSON object would be better.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
print_r( $_POST );
exit();
}
?>
<!doctype html>
<html>
<head>
<title>jQuery - ajax experiments</title>
<script src='//code.jquery.com/jquery-latest.js'></script>
</head>
<body>
<a id='link' role='button' href='#'>Test</a>
<script>
$('#link').click(function(e) {
e.preventDefault();
alert('function entered');
$.ajax({
url: location.href,
type: 'POST',
data: {
parameter1: 'test',
parameter2: 'test2'
},
success: function(msg) {
alert( 'wow' + msg );
}
});
alert('function end');
});
</script>
</body>
</html>
As 2 separate pages ( both in same directory otherwise edit page to the ajax target )
<!doctype html>
<html>
<head>
<title>jQuery - ajax experiments</title>
<script src='//code.jquery.com/jquery-latest.js'></script>
</head>
<body>
<a id='link' role='button' href='#'>Test</a>
<br /><br />
<script>
$('#link').click(function(e) {
e.preventDefault();
$.ajax({
url: 'jquery-ajax-target.php',
type: 'POST',
data: {
parameter1: 'test',
parameter2: 'test2'
},
success: function(msg) {
alert( 'wow' + msg );
}
});
});
</script>
</body>
</html>
And the ajax target, jquery-ajax-target.php
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
$parameter1=( isset( $_POST['parameter1'] ) ) ? $_POST['parameter1'] : false;
$parameter2=( isset( $_POST['parameter2'] ) ) ? $_POST['parameter2'] : false;
$_POST['modified']=array(
'p1'=>sprintf('modified %s', strrev( $parameter1 ) ),
'p2'=>sprintf('modified %s', strrev( $parameter2 ) )
);
$json=json_encode( $_POST );
echo $json;
exit();
}
?>
Here is my version. It will return a JSON response to your ajax which will be visible in your console for easy debugging.
Your main page:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="link" role="button" href="#">Test</a>
<script>
$(document).ready(function(){
$("#link").click(function(e) {
e.preventDefault();
console.log('function entered');
$.ajax({
url: "testPHP.php",
type: "POST",
dataType: 'json', //This tells your ajax that you are expecting a json formatted string as a response.
data: {
parameter1: 'test',
parameter2: 'test2'
},
success: function(msg) {
console.log(msg); //This will show the results as an object in your console.
}
});
console.log('Function End');
//document.getElementById('#link').setAttribute('href','testPHP.php'); //Why are you doing this. It's not needed.
});
});
</script>
Your testPHP.php page:
$results = array();
if(isset($_GET)){
$results[] = array(
'GET' => 'TRUE',
'getData' => $_GET
);
}
if(isset($_POST)){
$results[] = array(
'POST' => 'TRUE',
'postData' => $_POST
);
}
echo json_encode($results);
Here is an explanation of what is happening:
You make an initial call to your ajax by triggering some event. In your case it is the click of the link.
The click function leads to the actual ajax call which simply sends a post request to the testPHP.php.
The testPHP.php receives the post request and performs some sort of operation with the data that was provided by the ajax call.
The testPHP.php then sends back some sort of answer back to the ajax function. The data will be available in the success function.
You then get to decide how to use the data that was passed back from the testPHP.php page to the success function.
This is all done without your original page's code being refreshed.
You are not actually redirecting your user to another page.. You are just telling your page to goto another page and do some operation, which then gets reported back to the original page for you to do something with.
Hope it helps.
It does work after removing type attribute on script tag. I am using <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> before main script tag. It is working here. Also close the script tag. I hope I can help.
Also change the
document.getElementById('#link').setAttribute('href','testPHP.php');
to
document.getElementById('link').setAttribute('href','testPHP.php');
The problem with your code is that you are using javascript to change the attribute and in javascript once you used getElementById you no longer have to use # sign. try the following and it will work fine.
<?php
if(isset($_GET))
{
echo "<script>alert('GET is there');</script>";
print_r($_GET);
}
if(isset($_POST))
{
echo "<script>alert('POST is there')</script>";
print_r($_POST);
}
if(isset($_POST['parameter1']))
{
echo "<script>alert('$_POST is set')</script>";
header('Location: HomePage.php');
}
else
{
echo "<script>alert('No post variable set')</script>";
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<a id="link" role="button" href="index2.php">Test</a>
<script type="text/javascript">
$("#link").click(function(e) {
e.preventDefault();
alert('function entered');
$.ajax({
url: "testPHP.php",
type: "POST",
data: {
parameter1: 'test',
parameter2: 'test2'},
success: function(msg) {
alert('wow' + msg);
}
});
alert('function end');
document.getElementById('link').setAttribute('href','testPHP.php');
});
</script>
</body>
</html>
Furthermore it's a good practice to use the failed callback for the request.
error: function (xhr, status, error) {
alert(" Can't do because: " + error);
},

How do I return a variable from Javascript to PHP for using it for a query "onchange"?

JAVASCRIPT
$(document).ready(function() {
$("#p").change(function () {
var p_id = $(this).val();
console.log(p_id);
$.ajax({
url: "m/a/a.class.php",
method: "POST",
data: {pId: p_id},
success: function (data)
{
console.log(data); //<------ this gives me an empty output
alert("success!");
}
});
});
});
I am trying to get a the id of a selected value out of the selectpicker, when i change the selectpicker, i get the alert "success!" and in the console it shows the result, which is correct. When i want to use this result in PHP, which i am using ajax for, it gives me an odd output so i can't use the variable for the following sql statement.
What am i doing wrong? For you to understand i want to get the post input for product, so i can filter the next selectpicker by the id of "product", so i want to get dependant selectpicker "onchange". I already read many other questions, and it works in other examples when i use something like this in the success function:
success: function (data)
{
$('#state').html(data);
}
But this isn't working for my example here, because when i use the "$_POST['produkt_id']" it either gives me an empty query or it has a mistake in it, since it passes the data from my screenshot. Thanks in advance and feel free to ask questions.
UPDATE:
This is where I am trying to get the previous input.
case 'linie':
if(isset($_POST['pId'])) {
$t = $_POST['pId'];
$sql = 'SELECT id, bezeichnung '
. 'FROM l "
. 'LEFT JOIN ' .produkte p ON p.id=l.p_id '
. 'WHERE l.p_id =' . "$t" . 'AND l.deleted=0 AND p.deleted=0 '
. 'ORDER BY l.bezeichnung ';
break;
}
the error says it. PHP you're using is calling "include_once" and the file which you're trying to include, doesn't exist.
that makes the PHP to return a response with error in it, and the response - because of that error text - is not a valid JSON anymore.
In your ajax code you should put your url route path for file request it hink you put the file path of your project system that's why your ajax file could not find and include your file for ajax request execution
$.ajax({
url: "modules/ausschuss/ausschuss.class.php", //remove this
url: "full url for your file execution"
method: "POST",
data: {produkt_id: produkt_id},
success: function (data)
{
alert("success!");
}
});

How can get data from html form and javascript array using PHP and AJAX

I'm sending a HTML form and javascript array using AJAX post method. But I can't get my data in the PHP file.
$.post("addOrder.php", {
"form": $("#placeOrderForm").serialize(),
"array": array
}, function(responce) {});
Please read the docs clearly.
The update code:
$.post("addOrder.php",
$("#placeOrderForm").serialize(),
function(response) {
}
);
And in addOrder.php, print the posted array using.
echo '<pre>';print_r($_POST);echo '</pre>';
If you are using firebug, you will get the posted variables' array in response tab.
// You can access the values posted by jQuery.ajax
// through the global variable $_POST, like this:
$var = isset($_POST['var']) ? $_POST['var'] : null;
Can you try something like below:
var request = $.ajax({
url: "addOrder.php",
type: "POST",
data: {<data1> : <val1>},
dataType: "html"
});
request.done(function(msg) {
$("#log").html( msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
Looks like you passing argument is having issue.
In addForm.php try this:
var_dump($_POST)
This will enable you to inspect the form data posted.
Try something like this in your php file:
$params = array();
echo parse_str($_POST, $params);
Thanks everyone. I found my answer. I used "serializeArray" for sending form.
html
<form id="placeOrderForm">
<input name="po">
<input name="desc">
</form>
javascript
var array = [1,2];
$.post("addOrder.php",{
"form":$("#placeOrderForm").serializeArray(),
"array":array
}, function (responce) {});
php
$form_input_data_1 = $_POST['form'][0]['value']; // get po's data
$form_input_data_2 = $_POST['form'][1]['value']; // get desc's data
$array_index_1_data = $_POST['array'][0]; // get 1
$array_index_2_data = $_POST['array'][1]; // get 2

Not getting a response for an AJAX call to PHP (with JSON data)

I have a PHP running on a server, and i call to it via jQuery.Ajax() but it always return to the error portion of it.
If i call the PHP address directly from my browser, i get the response i need, it only breaks in the jQuery call.
The PHP (simply saying) is this:
<?php
if(isset($_GET['getcodenode']))
{
echo json_encode
(
array
(
'itens'=>
array
(
0=>array('id'=>100,'lb'=>'300','ds'=>'300 mm'),
1=>array('id'=>105,'lb'=>'400','ds'=>'400 mm')
)
)
);
die();
}
?>
And on the javascript side i call for it like this:
<html>
<head>
<script type="text/javascript">
function loadcall(data)
{
jQuery.ajax({
async:false,
method:'POST',
crossDomain:true,
dataType:'jsonp',
url:'http://example.com/ajax.php?getcodenode',
data:{'arg':data},
success:function(result){
var ret=JSON.parse(result);
var el=jQuery('#abc');
for(en in ret.itens)
{
el.Append('<div id="item_'+en.id+'">'+en.lb+', '+en.ds+'</div>');
}
},
error:function(result){alert('Error (loadcall)');}
});
}
</script>
</head>
<body>
<div id="abc"></div>
</body>
</html>
How to read JSON objects from PHP and display in browser?
There are lots of comments on your code:
While you already getting a json return from server; you don't to parse that. Its already a json object.
You can set async:true to get a promise data
The way you loop through objects you need to do that properly. see image how to get the object path correctly.
You can use $ token instead of jQuery token; unless you purposely need that.
I am not sure if this is the best approach; but it give the needed result as explained in your question.
The code is bellow tested with some comments:
<script type="text/javascript">
loadcall("test");
// as pointed you need to call the function so it runs
function loadcall(data) {
$.ajax({
async: true,
method: 'POST',
crossDomain: true,
dataType: 'json', //your data type should be JSON not JSONP
url: 'page.php?getcodenode',
data: {
'arg': data
},
success: function(result) {
console.log(result);
// see attached image how to get the path for object
var ret = result;
var el = $('#abc');
for (en in ret.itens) {
console.log(ret.itens[en].ds);
el.append('<div id="item_' + ret.itens[en].id +
'">' + ret.itens[en].lb + ', ' + ret.itens[en].ds + '</div>');
}
},
error: function(result) {
console.log(result);
}
});
}
</script>
Open you developer tool in your browser hit F12 (In Chrome, Firefox or Edge):
Go to Console tab and find the results.
Expand the results tell you get to the object you need.
Right click and `copy property path'.
Use the object path as needed in your code.
you need to call loadcall(data)
<html>
<head>
<script type="text/javascript">
function loadcall(data)
{
jQuery.ajax({
async:false,
method:'POST',
crossDomain:true,
dataType:'jsonp',
url:'http://example.com/ajax.php?getcodenode',
data:{'arg':data},
success:function(result){
var ret=JSON.parse(result);
var el=jQuery('#abc');
for(en in ret.itens)
{
el.Append('<div id="item_'+en.id+'">'+en.lb+', '+en.ds+'</div>');
}
},
error:function(result){alert('Error (loadcall)');}
});
}
loadcall('somethingData')
</script>
</head>
<body>
<div id="abc"></div>
</body>
</html>

jquery.ajax to PHP fails when I use ECHO in my PHP

this is the 1st time I try to use AJAX - my website needs to call a PHP during runtime when the user leaves a specific form field (VIN). I pass the value of this field to a PHP function for validation and processing. Then PHP should return 3 values for 3 different form fields.
This is my problem: I won't get the 3 values back into my javascript.
Each time when I use ECHO json_encode in my php the AJAX call crashes and the console shows "VM7190:1 Uncaught SyntaxError: Unexpected token Y in JSON at position 0(…)".
If I put any other simple ECHO in my PHP the AJAX call would return with an error.
If I remove each ECHO from my PHP the AJAX call returns as success but the returning data is NULL.
It would be so great if I could get a solution for this problem here.
If anybody would like to test the site - this is the url: mycarbio
Thank you very much.
This is my AJAX call:
function decode_my_vin(myvin) {
alert("in decode_my_vin");
dataoneID = '123';
dataoneKEY = 'xyz';
jQuery.ajax(
{
cache: false,
type: 'POST',
url: '/wp-content/themes/Impreza-child/vin-decoder.php',
dataType:'json',
data: {
'value1_VIN': myvin,
'value2_ID': dataoneID,
'value3_KEY': dataoneKEY,
'value4_Year': ' ',
'value5_Make': ' ',
'value6_Model': ' '
},
// async: false,
success: function(response) {
var obj = jQuery.parseJSON(response);
alert("success returned: " + obj);
document.getElementById("fld_7290902_1").value = "2015";
document.getElementById("fld_1595243_1").value = "Ford";
document.getElementById("fld_7532728_1").value = "Focus";
return;
},
error: function() { alert("error in der jquery"); }
});
}
And this is my PHP
<?php
header('Content-Type: application/json');
$resultYear = '2010';
$resultMake = 'Ford';
$resultModel = 'Focus';
$vinResult = array("Year: ", $resultYear, "Make: ", $resultMake, "Model: ", $resultModel);
echo json_encode($vinResult);
?>
This may not be your only problem, but you should try using an associative array when rendering the JSON:
$vinResult = array(
'Year' => $resultYear,
'Make' => $resultMake,
'Model' => $resultModel
);
Currently you are combining your property names and values.

Categories

Resources