not able to pass array from JS to PHP with AJAX - javascript

Hello am trying to pass an array from my JS script file to another file called serverSide.php so i can print the array in that file and do something with it , am having no issue sending the data and getting a response using the AJAX/JSON the problem i am getting "Notice: Undefined index: theArray in C:\xampp\htdocs\Ajax test\serverSide.php on line 2" when i try to print_r the array i sent ?
**Here is my JS code **
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script
src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"></script>
</head>
<body>
<h1>Testing AJAX techniques</h1>
<script>
let myArray = [1,2,3];
console.log(myArray);
let myArray1 = JSON.stringify(myArray);
console.log(myArray1);
$.post({
method: 'POST',
url: 'serverSide.php',
data: {theArray: myArray1},
success: function(res) {
console.log(res);
}
})
</script>
</body>
</html>
And this is the serverSide.php file code where i try to print the array
<?php
$test = json_decode($_POST['theArray']);
print_r($test);
?>
Thank you for any help

Related

Ajax call with php

Im using $.ajax in javascript. I need to get the response from php file. The code in javascript is -
var datavalues = {
a: 12,
b: 54
};
$.ajax({
type: "POST",
url: 'http://localhost/example/test.php',
data: datavalues,
success: function(response)
{
console.log(response);
$('#label').html(response);
var responsevalue = response;
}
});
and the code in php file is -
$bt = rand(0, 99);
$bt = intval($bt);
echo $bt;
The issue is that it shows the value in the label but value is not coming fine in the responsevalue variable. I need integer value in the responsevalue variable.
Output of console.log(response); statement is -
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Page</title>
</head>
<body>
</body>
</html>68<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Page</title>
</head>
<body>
</body>
</html>
Here 68 should be the value of responsevalue variable.
I hope you are not confused with the above code.
Use jquery param
var datavalues = {
a: 12,
b: 54
};
$.ajax({
type: "POST",
url: 'http://localhost/example/test.php',
data: $.param(datavalues),
success: function(response)
{
console.log(response);
$('#label').html(response);
var responsevalue = response;
}
});
in PHP file echo $_POST['a'];
The answer is given by #ceejayoz in the comments. For reference Im posting his answer here
"#pareza If that's the response, your http://localhost/example/test.php does more than just echo $bt;. You need to stop it from outputting all that HTML around the value you want."

how to use ajax to put value from javascript variable into a php variable

I need to get the value of a javascript variable and put it into a mysql database. I am trying to use jquery ajax function in (test.html) to Post the variable to a separate PHP file (external.php). I'm not sure why it's not working, I would appreciate any insight. Here are my two files:
Here is test.html:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
</head>
<body>
<script>
$(document).ready(function () {
var longitude = "print a longitude";
$.ajax({
url: "external.php",
method: "POST",
data: { "longitude": longitude }
});
});
</script>
</body>
</html>
And here is external.php:
<?php
$longitude = $_POST['longitude'];
echo json_encode($longitude);
?>
The code below works perfectly fine for me:
The external.php file:
<?php
header('Content-Type: application/json');
$longitude = $_POST['longitude'];
echo json_encode($longitude);
?>
The test.html file:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
</head>
<body>
<script>
$(document).ready(function () {
var longitude = "print a longitude";
$.ajax({
url: "external.php",
method: "POST",
dataType: "json",
data: { "longitude": longitude },
success: function(data){
console.log(data);
}
});
});
</script>
</body>
</html>
Also, make sure you are not running your file as:
file:///C:/Users/XXX/Desktop/XAMPP/htdocs/test.html
If you run it like this you would get this error:
XML Parsing Error: no root element found
Location: file:///C:/Users/XXX/Desktop/XAMPP/htdocs/external.php
Line Number 5, Column 3:
What you need to do is run Apache and then run the file as:
http://localhost/test.html
Below is the screenshot of what I get:

OMDb API not working in javascript

I am using OMDb API to fetch Title, Year and Runtime of movie. These should appear on the page as soon as it loads.I used j query ajax for this. But it does not work.
As soon as the page loads it shows undefined written there. Where I am making the mistake??
I am new to j query ajax and API's so any help would be appreciated.Thanks in advance :)
<! doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Latest compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">< </script>
<script type="text/javascript">
window.onload=function()
{
$.ajax({
url: "http://www.omdbapi.com/?t=spiderman&y=&plot=full&r=json",
crossDomain: true,
dataType: "json",
success: fetch
});
}
//For fetching data on success
function fetch(e){
var result="";
$.each(e,function(value){
result+="<p>" +value.Title +"</p>";
result+="<p>" +value.Year +"</p>";
result+="<p>" +value.Runtime +"</p>";
});
$('#movie').html(result); //For storing result in html
}
</script>
</head>
<body>
<p id="movie"></p>
</body>
in order to get all returned values from the object, you need to get each property by key and value,the returned json looks like this:
{"Title":"Spiderman","Year":"1990","Rated":"N/A","Released":"N/A","Runtime":"5 min","Genre":"Short","Director":"Christian Davi","Writer":"N/A","Actors":"N/A","Plot":"N/A","Language":"German","Country":"Switzerland","Awards":"N/A","Poster":"N/A","Metascore":"N/A","imdbRating":"5.7","imdbVotes":"90","imdbID":"tt0100669","Type":"movie","Response":"True"}
so just call e.Title to get title or loop into object using $.each with key and value as arguments.
first argument is the property name(KEY) and second is the value.
$.each(e,function(key,value){
result+="<p>"+ key + " : " + value +"</p>";
});
<! doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Latest compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">< </script>
<script type="text/javascript">
window.onload=function()
{
$.ajax({
url: "http://www.omdbapi.com/?t=spiderman&y=&plot=full&r=json",
crossDomain: true,
dataType: "json",
success: fetch
});
}
//For fetching data on success
function fetch(e){
var result="";
//where keys are attribute names and values are their values
$.each(e,function(key,value){
result+="<p>"+ key + " : " + value +"</p>";
});
$('#movie').html(result); //For storing result in html
}
</script>
</head>
<body>
<p id="movie"></p>
</body>

Grabbing Values from a JSON API Responce, putting them into webpage

Today I have a question that may seem kinda simple the the rest of you. I'm just now learning how to use APIs/JSONs and I'm a little confused. I'm trying to simply grab the temperature from this openweathermap.org API response and displaying it in an html tag.
The javascript from what I know is grabbing the temperature and setting it as a var. I'm confused why I cannot use id="" to set text inside a tag. The code below is what I have so far. I thank you for your time.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script type="text/javascript">
var weather;
var temp;
$(document).ready(function() {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98&units=metric",
dataType: 'jsonp',
success: function(weather){
var temp = weather.main.temp;
}
});
</script>
</head>
<body>
<p id="temp"></p>
</body>
</html>
#ArunPJohny have already identified the errors: 1) missing }) and 2) use $('#temp') to get the HTML element. Also you don't need to declare weather because it is declared as an argument.
$(document).ready(function() {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98&units=metric",
dataType: 'jsonp',
success: function(weather) {
$('#temp').text(weather.main.temp);
}
});
});
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<p id="temp"></p>

Calling a jQuery function from a PHP file

I am having problems trying to activate a jQuery function from a PHP.
The following is my own test version.
index.php file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome to temp index</title>
<link rel="stylesheet" href="style.css" type="text/css" />
<script type="text/javascript" src="scripts/jquery-1.8.3.min[2].js"></script>
<script type="text/javascript">
$(document).ready(function() {
//posts info into the userinfo.php file
$.post('userinfo.php', { activate:"colourchange"}, function(data){
$('report').html(data);
});
//the function which is meant to be activated from the php file
function colourchange(){
document.body.style.backgroundColor = 'green';
};
});
</script>
</head>
<body>
<h1>hello</h1>
<div id="report">
</div>
</body>
</html>
PHP file I am attempting to call my jQuery function from
<?php
if( $_REQUEST["activate"])
{
$activate = $_REQUEST['activate'];
};
if($activate == 'colourchange')
{
// This is the code that I believe not to be working as this isn't
// activating the jQuery function to work. (The page background isn't changing colour)
echo "<script>colourchange(); </script>";
};
?>
Thank you to anyone who has an idea of what to do it is much appreciated.
I have now tried ...
<?php
require 'userinfo.php';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome to temp index</title>
<link rel="stylesheet" href="style.css" type="text/css" />
<script type="text/javascript" src="scripts/jquery-1.8.3.min[2].js"></script>
<script type="text/javascript">
function colourchange(){
document.body.style.backgroundColor = 'green';
};
$(document).ready(function() {
$.post('userinfo.php', { activate:"colourchange"}, function(data){
$('report').html(data);
});
});
</script>
</head>
<body>
<h1>hello</h1>
<div id="report">
</div>
</body>
</html>
and the PHP index file is ...
<?php
if( $_REQUEST["activate"])
{
$activate = $_REQUEST['activate'];
};
if($activate=='colourchange')
{
echo "colourchange();";
};
?>
I don't exactly understand why you are using PHP to execute a jQuery function at all - perhaps this is just an oversimplified example. Assuming your primary goal is to have the PHP response trigger a specific Javascript function (and perhaps allow for the PHP response to trigger several different responses) you'd do something like this:
First change the callback from
function(data){
$('report').html(data);
}
to something like:
function(data) {
if (data.indexOf("colourchange") >= 0) { // php page returned "colorchange" or a string containing "colourchange"
colourchange();
} else if (data.indexOf("moodchange") >= 0) {
moodchange(); /// etc... you can add more trigger functions here
}
}
And second... just have your PHP page return "colourchange" instead of an HTML snippet:
if($activate == 'colourchange')
{
echo "colourchange";
};
Does that help?
you could try this-- example call the jquery function on success
$.ajax({
url: //the url,
data: //the data,
type: "POST",
success: function(data){
if(data == "ok"){
colorChange();
}
}
});
here the data will be the success result returned by the php code..
you can call a function depending on the data returned

Categories