ajax and json object encode and decode into and from php script - javascript

i have created a simple html file with a fixed json object. I want to take the object to the php file text.php, encode it, decode it, print it in the php file, and then print it back in the html file.
html file:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<script>
var key=45;
var value=65;
var rated = {"key" : key , "value" : value};
var rated_encoded = JSON.stringify(rated);
$.ajax({
type: "POST",
url: "text.php",
dataType:"json",
data: {
"rated" : rated_encoded
},
//success: function(data) {
//document.write(data);
//}
});
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("text.php");
});
});
</script>
<div id="div1"><h6>Result</h6></div>
<button>Get External Content</button>
</body>
</html>
text.php code:
<?php
if(isset($_POST["rated"])){
$rated_json = $_POST["rated"];
$JSONArray = json_decode($rated_json, true);
if($JSONArray !== null){
$key = $JSONArray["key"];
$value = $JSONArray["value"];
}
echo json_encode($rated_json);
}
?>
the
echo json_encode($rated_json);
in the last line of text.php is not working. I don't know if we can't print encoded stuff or something. In place of that line, even if i type echo "hello";, it's not printing in the php file. If there is any way i can print the $JSONArray variable in text.php, that would be great. It would be better if i can encode the json object in the html file itself, send to the php script, decode it there and then send back and print in the html file. Sorry if this question is not worded properly or is very basic. Also, please go slow and explain the code.

You need add contentType: "application/json; charset=UTF-8",
$.ajax({
type: "POST",
url: "text.php",
dataType:"json",
contentType: "application/json; charset=UTF-8",
data: {
"rated" : rated_encoded
},
//success: function(data) {
//document.write(data);
//}
});
the dataType option is just for parsing the received data.
If still not working, add this: processData: false

Related

Ajax not able to post javascript variable to php

I want to post values of a JavaScript variable to a PHP page, and then use those values there.
I get back a new HTML page, which I did not want to happen. Also, it is showing the error message produced by:
echo"some error";
What am I missing? I don't understand why this happens?
Here is my html file try.html
<html>
<head>
<title>try</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<a id="button" href="try.php" target="_blank">send data</a>
<script>
var sum2= 2010;
$('#button').click(function() {
var val1=sum2;
$.ajax({
type: 'POST',
url: 'try.php',
data: { text: val1 },
dataType: 'script' // I am not sure about what I write here script,json,html?
});
});
</script>
</body>
</html>
And this is my PHP file try.php
<?php
if(isset($_POST['text']))
{
$text = $_POST['text'];
echo $text;
}
else {
echo"some error";
}
?>
In try.php if you echo something which in turn will comeback to try.html.
If you just want to post the data to try.php and echo there the just use form and submit. You dont need ajax in that.
Ajax is to send the data/receive back without reloading the existing page. The response will be seen in the current page itself.
<html>
<head>
<title>try</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<a id="button" href="try.php">send data</a>
<script>
var sum2= 2010;
$('#button').click(function() {
var val1=sum2;
var json_params = {
text: val1
};
var json_data = JSON.stringify(json_params);
$.ajax({
type: 'POST',
url: 'try.php',
data: json_data,
dataType: "html",
success: function(response)
{
alert(response);
}
});
});
</script>
</body>
</html>
In the try.php page you can place this code
<?php
if (isset($_POST)){
$data = json_decode(file_get_contents('php://input'));
print_r($data);
}
else{
echo "not set";
}
?>
Firstly, remove script from data-type.
This is how you can pass the data to php file:
$('#button').click(function() {
var val1=sum2;
$.ajax({
type: 'POST',
url: 'try.php',
data: { text: val1 },
});
});
dataType - The type of data that you're expecting back from the
server. Here you don't want anything in return then it's fine. If you
are expecting anything like json or something, you can specify it.
If You want anything in response, you can handle in this manner
$('#button').click(function() {
var val1=sum2;
$.ajax({
type: 'POST',
url: 'try.php',
data: { text: val1 },
});
success: function (data) {
//Your success handler code
},
});
success - A callback function to be executed when Ajax request
succeeds.
Firstly remove href from link. By this it is directly redirecting to try.php
<a id="button" href="javascript:void(0);" target="_blank">send data</a>

How can I pass Javascript array to a PHP array on button click?

I am having trouble passing a Javascript array to a PHP array on the same page when the submit button is pressed. I have seen discussion of JSON.stringify and json_encode on other posts, but I am not sure how to use those functions with my code.
JS:
<script>
var kegs = [];
var textarea = document.getElementById("your_textarea");
$("#kegId").on('keyup', function (e) {
if (e.keyCode == 13) {
kegs.push($(this).val());
$("#kegId").val("");
textarea.value = kegs.join("\n");
};
});
</script>
PHP:
if (!isset($_POST['btn-addkegs'])) {
//I want to set the Javascript array 'kegs' to a php variable here
Using Ajax will do it for you! I wrote this code that sends an array to PHP on the same page. Once you get the array in PHP you can do whatever you want with it :).Just copy and paste this file and called it index.php to see the result. This will totally help you!
<?php
$data = array();
if(isset($_POST['myArray']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH'])){
$data = 'You array is: ' . $_POST['myArray'];
echo json_encode($data);
die();
}
?>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div id = "random"></div>
<script type = "text/javascript">
$(document).ready(function() {
var arr = [2,4,5,6,7];
var myArray = JSON.stringify(arr);
$.ajax({
url: "index.php",
method: "POST",
dataType: "json",
data: {myArray: myArray},
success: function (result) {
alert("result: " + result);
console.log(result);
$("#random").html(result);
}
});
});
</script>
</body>
</html>
This can be achieved by using ajax(), its syntax is:
$.ajax({
url: 'process.php', // file where data processing is done
type: 'POST',
data: {
var1 :val1,
var2 :val2
// parameter set
},
success: function(response){ // response from process.php
// do your stuff here
}
});
Read more about ajax
As you are using the jquery
var jsArray = makeJavascriptArrayhere //
$.ajax({
url: urlToPhpFile, // file where data processing is done
type: Method,
data:jsArray,
success: function(response){ // response from process.php
// do your stuff here
}
});
now in your php file
var_dump($_POST); //see on network liner tabs

Including JS file in html page errors

I have this JavaScript code inside an html and PHP page. But I've been told that it will works only if I had an internet connection, so the solution was to make a .JS file and include this file inside the page like that:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript" src="/clinic form/appoint/dropscript.js">
</script>
Now I got an error while testing the page offline.
The JS file is taken from this link:
multiple java script in one page error
And the final code is:
$(document).ready(function(){
$("#Date").change(function(){
var seldate =$(this).val();
display_data(seldate);
});
// This is the function...
function display_data(seldate) {
$("#scheduleDate").html(seldate);
var dataString = 'seldate='+ seldate;
$.ajax({
type: "POST",
url: "getdata.php",
data: dataString,
cache: false,
success: function(data) {
$("#Schedule").html(data);
}
});
}
// Now here is the real code for retaining your Date...
/*<?php
if (!empty($_GET['date'])) {
?>
display_data('<?php echo $_GET["date"]; ?>')
<?php
}
?>*/
document.getElementById('Date').value = '<?php echo #$_GET["date"]; ?>';
});
$(document).ready(function(){
$("#Name").change(function(){
var selname =$(this).val();
display_name(selname);
});
// This is the function...
function display_name(selname) {
$("#scheduleName").html(selname);
var dataString = 'selname='+ selname;
$.ajax({
type: "POST",
url: "getdatabyname.php",
data: dataString,
cache: false,
success: function(data) {
$("#Schedule").html(data);
}
});
}
});// JavaScript Document
P.S. I am totally new to JS and I am experimenting.
Go to https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js, hit CTRL+S, move saved file to your project's directory and then include it as you did with dropscript.js.
Also do the same with the font if you need it. Include it into your CSS file using #font-face. More information: https://developer.mozilla.org/en-US/docs/Web/CSS/#font-face

pass js variable to php using ajax on the same page

this is my html code:
<form id="form" action="javascript:void(0)">
<input type="submit" id="submit-reg" value="Register" class="submit button" onclick="showtemplate('anniversary')" style='font-family: georgia;font-size: 23px;font-weight: normal;color:white;margin-top:-3px;text-decoration: none;background-color: rgba(0, 0, 0, 0.53);'>
</form>
this is my javascript code:
function showtemplate(temp)
{
$.ajax({
type: "POST",
url: 'ajax.php',
data: "section="+temp ,
success: function(data)
{
alert(data);
}
});
}
this is my ajax.php file:
<?php
$ajax=$_POST['section'];
echo $ajax;
?>
The above html and javascript code is included in a file named slider.php. In my index file i have included this slider.php file and slider.php is inside slider folder. So basically index.php and slider.php are not inside the same folder.
Javascript code alerts the data properly. But in my php code (ajax.php file) the value of $_POST['section'] is empty. What is the problem with my code. I tried googling everything and tried a few codes but it still doesn't work. Please help me out
Try this instead:
$.ajax({
type: "POST",
url: 'ajax.php',
data: { 'section': temp},
success: function(data)
{
alert(data);
}
});
It is quite possible that your server does not understand the string you have constructed ( "section="+temp ). When using ajax I prefer sending objects since for an object to be valid it requires a certain format.
EDIT1:
Try this and let me know if it doesn't work either:
$.post('ajax.php', {'section': temp}, function(data}{
alert(data);
});
Add jquery plugin(jQuery library) ,then only ajax call works
for eg
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
check your input data , whether it contain '&,/' charators,then use encodeURIComponent()
for Ajax Call Eg:
var gym_name = encodeURIComponent($("#gym_name").val());
$.ajax({
type: "POST",
url: "abc.php",
data:string_array,
success: function(msg) {
console.log(msg);
}
});
In abc.php
<?php
$id = $_POST['gym_name'];
echo "The id is ".id;
?>
Give a try to the following (although I cannot work out why #Grimbode's answer is not working):
$("#submit-reg").on( "click", function() {
$.ajax({
type: "POST",
url: 'ajax.php',
data: {'section': 'anniversary'},
success: function(data)
{
alert(data);
}
});
});
Note: I don't know what your underlying code is doing. However, I would suggest not using HTML element properties to handle events for numerous reasons, but separate the JS/event handling appropriately (separate js file(s) (recommended) or inside <script> tags). Read more...

Pass PHP array to external jQuery $.ajax

Basically what I want to do is get an array that has t.php, and alert it with JavaScript with the response of t.php.
The problem is that the variable doesn't exist in this file...
So, how you can pass this variable to JS?
I tried with 'return':
return $sqlData = $q->query_array_assoc();
But doesn't work.
Here is my $.ajax code:
<script type="text/javascript">
$(document).ready(function(){
$('#brand').change(function(e){
console.log(e);
$.ajax({
method: "GET",
url: "t.php",
data: { type: 1, brand: this.value }
})
.done(function(msg){
$('#debug').html(msg);
var pArray = <?php echo json_encode($sqlData);?>
for (var i = 0; i < pArray.length; i++) {
alert(pArray[i]);
};
});
});
</script>
Note: I sent
data: { type: 1, brand: this.value }
To validate a switch statement in the .php file, but there isn't problem with that. I get the data from the database and fetch in the variable $sqlData;
So the array has data, the problem is get it with $.ajax
in your php file, you need to echo instead of return
echo json_encode($q->query_array_assoc());
in javascript code:
$.ajax({
method: "GET",
url: "t.php",
data: { type: 1, brand: this.value },
success: function(data) {
$('#debug').html(data);
// if you want to use it as array
var json_data = JSON.parse(data);
}
});
Make 2 files please, a "t.php" file and a "t.html" file and add my code there. Run the code and see response. You just have to work with the response to get the values se perated by comma "," !!!
/******************** UPDATED ***********************/
//t.php
<?php
$a = array();
$a[]=1;
$a[]=2;
$a[]=3;
echo "$a[0],$a[1],$a[2]";
?>
//t.html
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
function fun(){
$.ajax({
method: "GET",
url: "t.php",
data: { },
dataType: "html", //expect html to be returned
success: function(response){
//$("#debug").html(response); //Outputs the html of php file into #dialog div
alert(response);
document.getElementById("debug").innerHTML = (response); //Outputs the html of php file into #dialog div
}
})
}
</script>
<button onclick="fun()">Call Ajax Fun</button>
<div id="debug"></div>
Did this help?

Categories

Resources