Send javascript array to php using json - php

This question might be repetitive but i got confused reading all posts relating to this.(sincere apologies!) Basically, I want to send a javascript array to a php file and inturn write the array to a text file . I learnt the best way to go about it is using JSON and AJAX. My code is displays "success" for the ajax part, and also creates a file (php code),but an empty text file.
$('#tabletomodify').on('change','.street',
function (event)
{
event.preventDefault();
var row=( $(this).closest('tr').prop('rowIndex') );
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
var ideSelected= this.id;
var values = [valueSelected];
for ($i=3;$i<row;$i++)
{
var dv="selectstate"+$i;
var dv1=document.getElementById(dv).value;
var sl="selectstreet"+$i;
var sl1=document.getElementById(sl).value;
var po="selectbuilding"+$i;
var po1=document.getElementById(po).value;
var concat=dv1+sl1+po1;
values.push(concat);
}
JSON = JSON.stringify(values);
$.ajax({
url: "get_buildings.php",
type: 'POST',
data: JSON ,
success: function(){
alert("Success!")
}
});
PHP Code:-
<?php
$json = $_POST['JSON'];
$p = json_decode(JSON);
$file = fopen('test.txt','w+');
fwrite($file, $p);
fclose($file);
echo 'success?';
?>

Two flaws:
a) You're not sending your data correctly - it's lacking a field name:
data: {data: JSON}
^^^^---this will be the key in PHP's $_POSt
b) You're using invalid constants in PHP and not even decoding what MIGHT have been the passed in data. You should have:
$p = json_decode($_POST['data']);
^^^^--matching what you have in the `data` field in Javascript.

Related

Take Multiple values from the php file using AJAX

I have a Jquery AJAX function which sends values to PHP file and the date from the PHP file is appended to the div content.
$( document ).ready(function() {
var valueSelected = $( "#sort_id option:selected" ).val();
var arr = Array();
var arr = <?php echo json_encode($details); ?>;
var details = JSON.stringify(arr);
var wash = <?php echo json_encode($_GET['wash']); ?>;
var params = Array();
var params = <?php echo json_encode($params); ?>;
var params = JSON.stringify(params);
$.ajax({
type: 'post',
url: 'sort.php',
data: {
data : details,
wash : wash,
params :params},
error : function(data){console.warn(xhr.responseText)},
success: function (data) {
$('#content').html(data).fadeIn("slow");
var jsonText = httpObject.responseText;
var jsonObject= eval('('+jsonText+')');
var count_array=jsonObject.count_array;
var count_array=jsonObject.count_sorted_array;
jQuery("label[for='private_count']").html(count_array);
jQuery("label[for='sorted_count']").html(count_sorted_array);
}
});
Now, I need to take some computed value from the PHP script and use it in the PHP file which is calling this AJAX function.
If I give the datatype:"JSON" in the above code, it is not displaying the results in the content div.
My PHP file contains the following code to be taken into jquery variable along with the content to be displayed in content division.
$count_array = sizeof($sorted_array);
$data = array(
'count_array' => $count_array,
'count_sorted_array' => $count_sorted_array,
);
echo json_encode($data);
You can create an array at PHP level where you put the HTML in a cell within it indexed by html and keep the other data:
$data = array(
'html' => '<p>....</p>',
'count_array' => $count_array,
'count_sorted_array' => $count_sorted_array,
);
Then make the AJAX as datatype:"JSON" and catch the html with data.html in order to put it in the content div

Bringing back several variables into ajax form POST success as jQuery variables

I am very new to ajax.
What I am trying to do here is bringing back some variables from a PHP file that I've wrote mainly to process a HTML form data into MySql db table.
After some research I concluded that I need to use json (first time) and I must add the part dataType:'json' to my ajax.
My problem is that after adding this part, I am no more able to submitting the form!
Can anyone please let me know what am I doing wrong here?
I just need to process the PHP code and return the three mentioned variables into a jquery variable so I can do some stuff with them.
Thank you in advance.
AJAX:
var form = $('#contact-form');
var formMessages = $('#form-messages');
form.submit(function(event) {
event.preventDefault();
var formData = form.serialize();
$.ajax({
type: 'POST',
url: form.attr('action'),
data: formData,
dataType: 'json', //after adding this part, can't anymore submit the form
success: function(data){
var message_status = data.message_status;
var duplicate = data.duplicate;
var number = data.ref_number;
//Do other stuff here
alert(number+duplicate+number);
}
})
});
PHP:
//other code here
$arr = array(
'message_status'=>$message_status,
'duplicate'=>$duplicate,
'ref_number'=>$ref_number
);
echo json_encode($arr);
The way you have specified the form method is incorrect.
change
type: 'POST',
to
method: 'POST',
And give that a try. Can you log your response and post it here ? Also, check your console for any errors.
If your dataType is json, you have to send Json object. However, form.serialize() gives you Url encoded data. (ampersand separated).
You have to prepare data as json object :
Here is the extension function you can add:
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
Credit goes to : Difference between serialize and serializeObject jquery

Undefined index in PHP post with AJAX

In my local machine, I am trying to save data from a json to my mysql database, I am using Wampserver.
In my html page (saveInfo.php), I have this jquery code:
<script type="text/javascript">
var jsObj = {"user_id":5, "login":"hsm"};
var jsonobj = JSON.stringify(jsObj);
$.ajax({
type: "POST",
url: "json_handler.php",
data: { 'jsonobj':jsonobj },
success: function(){
alert('success');
window.location = "http://localhost/quranMapping/php/json_handler.php";
}
});
</script>
In the other side, I have my server-side php code (json_handler.php) like that:
<?php
$input = file_get_contents('php://input');
$input = $_POST['jsonobj'];
$result = json_decode($input);
echo $result->user_id;
?>
But when I run that code, I get this error:
You should remove this:
var jsonobj = JSON.stringify(jsObj);
and change
data: { 'jsonobj':jsonobj },
to
data: jsObj,
On the php side to decode the data just use
$user_id = isset($_POST["user_id"])?$_POST["user_id"]:"";
$login = isset($_POST["login"])?$_POST["login"]:"";
Also there is no need to do
$input = file_get_contents('php://input');
Since the form is being posted with an object as data the value will be application/x-www-form-urlencoded so it don't be valid json.

Get json value on any php page

I am creating json object but can't access its value in php.I am trying to access json object in php and assign that object to php variable.My js code is
var arr= [];
var data={ "tab" : 'system' };
jObjArr = arr.push(data);
var JSONstr = JSON.stringify(jObjArr);
what i am missing ?
I try to get tab value on that page in php.
Try to pass simple object rather than sending an array:
function send_me() {
//var arr = [];
var data = { "tab": 'system' };
//jObjArr = arr.push(data);
//var JSONstr = JSON.stringify(data);
$.ajax({
url: "a_blank.php",
type:"post",
data: data,
success: function (response) {
alert(response);
}
});
}
On php page side simply get as:
if($_SERVER["REQUEST_METHOD"]=="POST")
{
print_r($_POST['tab']);
die();
}

How to extract information from array of Input element in PHP?

I trying to use contact form using J Query ,PHP AJAX but here in the below code the form information is gathered and send it to the server using for LOOP and Array of inouts of ofrm is created . i am new to this kind of coding please help me to extract this value in PHP so that i can use this element to add in to my database or send mail contain form inputs .
function signUpClick(){
var form = $("#form_main")[0];
var objData = {};
for(var i=0;i<form.length;i++){
var input = form[i];
objData[input.name] = "";
if(input.className == "writable")
objData[input.name] = input.value;
}
$("#loader").show();
$("#error_message").hide();
//send contact form using ajax
$.ajax({
url: "contact.php",
global: false,
type: "POST",
data:objData,
success: function(response){
$("#loader").hide();
if(response == "__ok__")
showSentMessage();
else
showErrorMessage(response);
},
error:function(){
$("#loader").hide();
showErrorMessage("Can't get the contact form");
}
});
}
On the PHP side you can manage the information as an array:
$objData = json_decode(file_get_contents('php://input'));
$objData will be the PHP array equivalent to the $objData on Javascript

Categories