Using Ajax and JSON to display PHP echo message in HTML - javascript

Ive been trying to connect my PHP file to my HTML file using Javascript/jQuery and json. When the user inputs a number into the input box in the form and submits it, the PHP file should multiply the number by two and send it back to the user.
However when I press the submit button it takes me to the php page instead of displaying the information (processed in the php file) in HTML.
This is my HTML form:
<div id="formdiv">
<form action="phpfile.php" method="get" name="form1" id="form1" class="js-php">
Mata in ett nummer: <input id="fill1" name="fill1" type="text" />
<input type="submit" id="submit1" name="submit1" value="submit">
</form>
This is my Javascript file
$(".js-php").submit(function(e){
var data = {
"fill1"
};
data = $(this).serialize() + $.param(data);
$.ajax({
type:"GET",
datatype:"json",
url:"phpfile.php",
data: data,
success: function (data){
$("#formdiv").append("Your input: "+data)
alert (data);
}
})
e.preventDefault();
});
PHP file:
$kvantitet = $_GET['fill1'];
$y = 2;
$work = $kvantitet * $y;
$bork = $work * $kvantitet;
echo json_encode($work) ."<br>";
echo json_encode($bork);

There are a few things you could do a bit differently here to make this work:
Currently, using both .serialize and $.param your data variable contains something like this:
someurl.php?fill1=1&0=f&1=i&2=l&3=l&4=1&5=%3D&6=1
If you use only .serialize you will get something easier to work with:
?fill1=5
On the PHP side, currently your code outputs something like this:
4<br>8
By adding your values to an array you can get a response back that you can work with:
$result = array();
$kvantitet = $_GET['fill1']; // Lets say this is 5
$y = 2;
$work = $kvantitet * $y;
$bork = $work * $kvantitet;
//add the values to the $result array
$result = array(
"work" => $work,
"bork" => $bork
);
echo json_encode($result);
Which will output:
{"work":4,"bork":8}
Back on the JS side you can then handle the data in your success callback:
$(".js-php").submit(function(e){
data = $(this).serialize();
$.ajax({
type:"GET",
datatype:"json",
url:"phpfile.php",
data: data,
success: function (data){
// *data* is an object - {"work":4,"bork":8}
$("#formdiv").append("Your input: "+data)
console(data);
}
});
// Use return false to prevent default form submission
return false;
});
One way to access the properties in your object is by using dot notation:
data.work //Outputs 4
data.bork //Outputs 8
But here is a really great answer on processing / accessing objects and arrays using JavaScript.
Here is a Fiddle containing your (working) jQuery

You are expecting JSON Data but what you send back is not JSON
Try output the following in your PHP File:
$data['work'] = $work;
$data['bork'] = $bork;
echo json_encode( (object)$data );
Use console.log to inspect incoming data on the AJAX call then handle it according to how you want.

I think you need &
data = $(this).serialize()+'&'+$.param(data);
and as #leonardo_palma mentioned in comments maybe you need to use e.preventDefault(); in the beginning of submit function
and I prefer to use
$(document).on('submit','.js-php',function(){/*code here*/});

Related

Decoding javascript array in PHP

I've been trying to decode a Javascript array in PHP for several days now with no luck.
I basically have a PHP while loop that loops through all products in my SQL database and it spits out a checkbox on each row to allow users to select 1 or more product to action via a PHP script.
My HTML & form is:
<div class="error_box"><?php echo $_SESSION['newdata']; ?></div>
<div class="error_box"><?php echo $_SESSION['errordata']; ?></div>
<form>
<input type='submit' value='Bulk update products -->' id='bulk-change-products' onClick='updateProduct()'>
<input type='checkbox' name='products[]' id='serialized' value='$product_no' onclick='serialize()'>
</form>
My Javascript code:
window.serialize = function serialize() {
var values = [].filter.call(document.getElementsByName('products[]'), function(c) {
return c.checked;
}).map(function(c) {
return c.value;
});
console.log(values);
$('#result').html(values);
}
function updateProduct(values){
$.ajax({
url: "https://tech-seo.co.uk/ecommerce/products/bulk_process_products.php",
method: "POST",
data: {array:values},
success: function(res){
}
})
}
Console log shows the data correctly e.g.
(2) ["1", "2"]
0: "1"
1: "2"
length: 2
My php code after posting with AJAX:
session_start();
$getArray = json_decode($_POST['data']);
// checking if data exists
if ($getArray != null ){
$_SESSION['newdata'] = "Success!";
}else{
// either of the values doesn't exist
$_SESSION['errordata'] = ">>>>>> There was an error <<<<<<<";
}
I always get '>>>>>> There was an error <<<<<<<' when I select the products and click the submit button.
Any help is appreciated.
Thanks.
Stan.
You're not passing the values array when you call updateProduct() from the onclick attribute. It needs to get the values itself.
function updateProduct() {
var values = $("input[name='products[]']:checked").map((i, el) => el.value).get();
$.ajax({
url: "https://tech-seo.co.uk/ecommerce/products/bulk_process_products.php",
method: "POST",
data: {
products: values
},
success: function(res) {
}
})
}
If you pass the array in the data: option, you don't need to use json_decode() in PHP. jQuery will send the parameters using the URL-encoded format that PHP decodes into an array in the $_POST element.
$getArray = $_POST['products'];

Is it possible to assign a php variable to a jquery var and then refresh that jquery variable

Is it possible to assign a php variable to a jQuery variable and then use a function to refresh the jQuery var every 30 seconds?
Also, could you use that variable in a html input?
<input type="text" value="jquery value that will refresh every 30 seconds with PHP variable">
If this is possible how and where can you learn to do this?
Try something like this. Just change backend url. This backend should only output the value.
<input id="input" type="text" value="" />
<script>
setInterval(function(){
$.get( "/value.php", function( data ) {
$('#input').val( data );
});
},30000);
</script>
Your value.php file will look something like
<?php
$value = 1;
echo $value;
exit;
If you need to return more values then one, you can use JSON, then
<input id="input" type="text" value="" />
<script>
setInterval(function(){
$.get( "/value.php", function( data ) {
$('#input').val( data.first_value );
}, "json");
},30000);
</script>
Your value.php file will look something like
<?php
$first_value = 1;
$second_value = "Some string";
echo json_encode(array(
'first_value' => $first_value,
'second_value' => $second_value
));
exit;
This script only sends data to fiddle servers which in turn send it back. It then update the value of the input.
It's just a little example but it might help you to get the idea:
var data_sent = 1;
setInterval(function () {// Set interval to retrieve info every 1s.
$.ajax({
url: "/echo/json/",// URL provided by jsfiddle to try AJAX. It just echoes back.
type: 'POST',// jsfiddle imposes that you use POST for that url.
data: {
json: JSON.stringify(data_sent)// Send data, it'll be echoed by jsfiddle script, the format is also imposed by jsfiddle.
},
success: function (data) {
$("#myInput").val(data);// Put the data received in the input
data_sent += 1;// change the data so that you send new one to the server next time.
}
})
}, 1000);

Save form data using AJAX to PHP

How can I save the form data in a file or a local db (maybe using AJAX) which send the data via form action to an external db?
The source code for my form is here: http://jsbin.com/ojUjEKa/1/edit
What changes (if any) should I make to the code?
EDIT:
Right. So I'm able to store the data into localStorage using AJAX and want to send the data stored across to a file called backend.php. Here's my html file: http://jsbin.com/iSorEYu/1/edit
and here's my backend.php file: http://jsbin.com/OGIbEDuX/1/edit
The AJAX is working absolutely fine to store the fields in localStorage but things go wrong when it tries to send the data across to backend.php. I receive the following errors:
[24-Jan-2014 08:40:34 America/Chicago] PHP Notice: Undefined index: data in /home4/private/public_html/marketer/backend.php on line 7
[24-Jan-2014 08:40:34 America/Chicago] PHP Warning: Invalid argument supplied for foreach() in /home4/private/public_html/marketer/backend.php on line 10
[24-Jan-2014 08:40:58 America/Chicago] PHP Notice: Undefined index: data in /home4/private/public_html/marketer/backend.php on line 7
[24-Jan-2014 08:40:58 America/Chicago] PHP Warning: Invalid argument supplied for foreach() in /home4/private/public_html/marketer/backend.php on line 10
What's the issue here?
LocalStorage would be your best bet. I would suggest using storejs as their API is straight forward, easy to use, and x-browser.
You could then trigger the form values to be stored on the "blur" event of each field.
$('input').on('blur', function (e) {
var el = e.target;
store.set(el.attr('name'), el.val());
});
When you are ready to submit to the server, you could use something like the following:
$('#formID').on('submit', function (e) {
e.preventDefault();
$.post('/my/save/route', store.getAll(), function () { ... });
});
You of course could do all of this without storejs and use vanilla JS to interact with the native LocalStorage API.
PHP:
<h1>Below is the data retrieved from SERVER</h1>
<?php
date_default_timezone_set('America/Chicago'); // CDT
echo '<h2>Server Timezone : ' . date_default_timezone_get() . '</h2>';
$current_date = date('d/m/Y == H:i:s ');
print "<h2>Server Time : " . $current_date . "</h2>";
$dataObject = $_POST; //Fetching all posts
echo "<pre>"; //making the dump look nice in html.
var_dump($dataObject);
echo "</pre>";
//Writes it as json to the file, you can transform it any way you want
$json = json_encode($dataObject);
file_put_contents('your_data.txt', $json);
?>
JS:
<script type="text/javascript">
$(document).ready(function(){
localStorage.clear();
$("form").on("submit", function() {
if(window.localStorage!==undefined) {
var fields = $(this).serialize();
localStorage.setItem("eloqua-fields", JSON.stringify( fields ));
alert("Stored Succesfully");
$(this).find("input[type=text]").val("");
alert("Now Passing stored data to Server through AJAX jQuery");
$.ajax({
type: "POST",
url: "backend.php",
data: fields,
success: function(data) {
$('#output').html(data);
}
});
} else {
alert("Storage Failed. Try refreshing");
}
});
});
</script>

getting undefined index error in php

I just want receive the array and print it which is sent by jquery.post()
my HTML-JS
<input type="submit" id="myButton" />
<script type="text/javascript">
var arr = new Array();
arr[0] = "Ding";
arr[1] = "Dong";
arr[2] = "Bong";
var json_string= JSON.stringify(arr); // convert it into a json string.
//and sending the data to server. temp.php.
$("#myButton").click(function(){
$.post('temp.php' , {json : json_string },function(data){
location.href = "temp.php";
});
});
</script>
I have checked by alert() that data sending is successful. After button click page is also redirecting to temp.php
My php page temp.php
<?php
$json_string = $_POST['json']; //geting the post request. //this is line 3
$array_items = json_decode($json_string); //converting json string to a php array.
echo $array_items[0]; //just to print 1st element of array
?>
It should print Ding. But I am getting error
Undefined index: json in C:\wamp\www\phpJSarray\temp.php on line 3
What is my mistake in temp.php page ? Please help me out.
call this javascript on your onclick or on form submit however u like.
var arr = new Array();
arr[0] = "Ding";
arr[1] = "Dong";
arr[2] = "Bong";
var json_string = JSON.stringify(arr); // convert it into a json string.
$("#data").val(json_string);
$("#form1").submit(); //and sending the data to server. temp.php.
HTML:
<form action="temp.php" id="form1" method="POST">
<input type="hidden" id="data" name="data">
</form>
temp.php
$dataArray = json_decode($_POST['data']);
The $.post is doing an AJAX call on the current page... which has no apparent effect because once it finishes, the location.href = "temp.php"; is redirecting you to temp.php.
If you'd like to make a POST to temp.php, you could just do it through a normal form. Use jQuery to set the value of a hidden input element to json_string if desired (or better, let jQuery change the form data to JSON).
<script>
$(document).ready(function() {
$("#myButton").on( 'click', function () {
$.ajax({
type: 'post',
url: 'temp.php',
data: {
arr1: "Ding",
arr2: "Dong",
arr3: "Bong",
},
success: function( data ) {
console.log( data );
}
});
});
});
</script>
You'd then call it by doing $_POST['arr1'];. I hope this solves your problem.
After you send your data via AJAX to temp.php and it returns a successful response, redirect to temp.php with an empty POST happens. Thats why you get no data after redirect.
You should also check whether array element exists in temp.php:
<?php
if (isset($_POST['json'])) {
$json_string = $_POST['json'];
$array_items = json_decode($json_string);
echo $array_items[0];
}
?>

How to access Javascript array in PHP file and printing array values in Javascript

I have first PHP file where I have form and it's action is directing me to next php file. The code snippet is as below:
<form name="drugForm" action="drug_form2.php" onsubmit="return validateForm()" method="post">
In function validateForm (javascript) I am checking whether text area is filled and at least a checkbox is checked. And I am creating array, here in javascript, to get checkbox values. The js code is below:
function validateForm()
{
var x=document.forms["drugForm"]["dname"].value;
var y=document.drugForm.drug;
var y_array = [];
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
else if (Boolean(x))
{
for(k=0;k<y.length;k++)
{
if(y[k].checked)
{
var arr_val = y[k].value;
y_array.push(arr_val);
//alert(arr_val);
}
}
for(m=0;m<y.length;m++)
{
if(y[m].checked)
{
for(l=0;l<y_array.length;l++)
{
alert("This is array " + y_array[l]);
}
dataString = y_array ; // array?
var jsonString = JSON.stringify(dataString);
$.ajax({
type: "POST",
url: "drug_form2.php",
data: {data : jsonString},
cache: false,
success: function(){
alert("OK");
}
});
//alert("The array length is " + y_array.length);
//return true;
}
}
alert("Check one checkbox at least");
return false;
}
}
Here, from this function I want send array to php, for this reason I referred following link but it didn't work:
Send array with Ajax to PHP script
Now, my queries are as following:
Why am I not able to print array value inside second for loop? and
How can I access javascript array in PHP file?
I have PHP file too to check whether array values are printing properly, but it is not giving those values. Below is second PHP file to get javascript array in PHP file:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$data = json_decode(stripslashes($_POST['data']));
// here i would like use foreach:
foreach($data as $d){
echo $d;
}
echo "Its in form2 and working fine";
?>
</body>
</html>
Am I including ajax function at right place?
You can just append each item in your javascript array into a string seperated by a unique character/s. As for my experience, it's easier than passing it as an array. Then pass the string to PHP.
In your PHP code, use the string method explode to create an array out of the string. Then go with the rest of your code logic.
if javascript array is simple array,than change it to csv and passed it has string.
In php serverside just explode that string you will again get array in php.
javscript
$.ajax({
type: "POST",
url: "drug_form2.php",
data: {data : y_array.join(',')},
cache: false,
success: function(){
alert("OK");
}
});
php
$array= explode(",", $_POST['data']);

Categories

Resources