correct JSON format from Jquery to PHP - php

I'm working on a project coding PHP-AJAX-Jquery and JSON and need to send the information of a form that has three input fields to a php file that will store the info of the three fields in the database.
my problem is that I need(I have because of project spec) to use Jquery-AJAX and JSON and I think I'm passing in a malformed JSON string to the PHP file, this is the js that is supposed to handle the call:
$(document).ready(function(){
$('#ID_formulario').on('submit',function(e) {
e.preventDefault();
var nombre = $('input#ID_nombre');
var email = $('input#ID_email');
if(validaForm(nombre, email)){
var url = $(this).attr('action');
var data = $(this).serializeArray();
var type = $(this).attr('method');
alert(data);
$.ajax({
url:url,
data:data,
type:type,
cache: false,
contentType: "application/x-www-form-urlencoded",
dataType: 'json',
beforeSend: function () {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="imagen.gif" align="absmiddle"> <span class="loading">Realizando peticion...</span>');
},
error: function(){
alert("error peticiĆ³n ajax");
},
success: function(datos){
$('#result').empty().html(respuesta). fadeIn('slow').delay(5000).fadeOut();
$('#ID_formulario')[0].reset();
$('input#ID_nombre').focus();
$("#flash").hide();
//$("#display").after(html);
//$("#result").append(data);
}
});
}
});
});
my questions are: how to send the info of the three fields in a valid JSON format to the php file? is there any jquery function that helps? or is serializeArray() enough?
It's okay to use success: function(datos) or should I replace it to .done(function)) ?
thanks in advance.

You dont need to send anything as JSON to PHP. Just send it with type: POST and read it in PHP. Then return it as JSON to read in Javascript. You just read the $_POST in PHP. I believe you've mistaken your project specs and you need to RETURN data from PHP as JSON.
This is one of my projects:
$("document").ready(function(){
$(".js-ajax-php-json").submit(function(){
var data = {
"action": "product"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php",
data: data,
success: function(data) {
$(".the-return").html(
// Read returned JSON. Exammple
"<div class='data-row'><strong>TYPE</strong> " + data["title"]+ "</div>";
);
}
});
return false;
});
});
In PHP you take the POST and read data.
response.php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "product": sendValues();
break;
}
}
}
// Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
// Do everything with $_POST's here
function sendValues(){
$return = $_POST;
$return["title"] = 'Something';
$return["json"] = json_encode($return);
echo json_encode($return); // Return JSON formatted data to Javascript.
}

Related

I have arrays stored in a json object, I send them using ajax call to the server side, how to access the data?

$scope.addQunatity = function(){
var url="../php/mainPageFacture.php";
// store data from user in the js arrays
var quan_cls_crt=[$("#quan_cls_crt").val(),$("#quan_cls_crt2").val()];
var quan_piece=[$("#quan_piece").val(),$("#quan_piece2").val()];
var itemName=[$("#designList").val(),$("#designList2").val()];
var dechargementNote=[$("#dechargementNote").val(),$("#dechargementNote2").val()];
var itemIds=[78,75];
var func="addQunatity";
var data = {"function": func,
"quan_cls_crt":quan_cls_crt,
"itemId":itemIds,
"dechargementNote":dechargementNote,
"quan_piece":quan_piece};
data = JSON.stringify(data);
var options = {
type : "get",
url : url,
data: {data:data},
dataType: 'json',
async : false,
cache : false,
success : function(response,status) {
debugger;
$scope.getAllItemNames();
alert("success");
},
error:function(request,response,error){
alert("Error: " + error + ". Please contact developer");
}
};
$.ajax(options);
}
Here is my php code that will receive the Json object
function addQunatity(){
$quan_cls_crt = $_GET["quan_cls_crt"];
$quan_piece = $_GET["quan_piece"];
$itemId=$_GET['itemId'];
$dechargementNote=$_GET['dechargementNote'];
}
I expect to receive the json arrays and store them in php variable in order to use the in the query later on, but i have no idea how to access the arrays in the json object
You don't have to stringify the data, just send it as it is - the json data type causes jQuery to JSON-encode it for you. Don't make another object.
var data = {"function": func,
"quan_cls_crt":quan_cls_crt,
"itemId":itemIds,
"dechargementNote":dechargementNote,
"quan_piece":quan_piece};
var options = {
type : "get",
url : url,
data: data,
dataType: 'json',
async : false,
cache : false,
success : function(response,status) {
debugger;
$scope.getAllItemNames();
alert("success");
},
error:function(request,response,error){
alert("Error: " + error + ". Please contact developer");
}
};
$.ajax(options);
}
<?php
$received_data = file_get_contents('php://input');
$data = json_decode($received_data);
//Here now you can access
$variable_name = $data['keyname']; //this means instead of $_GET or $_POST or $_REQUEST
?>
You can access received json data to php using the file_get_contents('php://input'); method..
Dont stringify the data. Use your same code and remove the stringify line.
var url="../php/mainPageFacture.php";
// store data from user in the js arrays
var quan_cls_crt=[$("#quan_cls_crt").val(),$("#quan_cls_crt2").val()];
var quan_piece=[$("#quan_piece").val(),$("#quan_piece2").val()];
var itemName=[$("#designList").val(),$("#designList2").val()];
var dechargementNote=[$("#dechargementNote").val(),$("#dechargementNote2").val()];
var itemIds=[78,75];
var func="addQunatity";
var data = {"function": func,
"quan_cls_crt":quan_cls_crt,
"itemId":itemIds,
"dechargementNote":dechargementNote,
"quan_piece":quan_piece};
var options = {
type : "get",
url : url,
data: {data:data},
dataType: 'json',
async : false,
cache : false,
success : function(response,status) {
debugger;
$scope.getAllItemNames();
alert("success");
},
error:function(request,response,error){
alert("Error: " + error + ". Please contact developer");
}
};
$.ajax(options);
}
In the PHP side, like you have done -
$quan_cls_crt = $_GET["quan_cls_crt"];
$quan_piece = $_GET["quan_piece"];
$itemId=$_GET['itemId'];
$dechargementNote=$_GET['dechargementNote'];
And to access each of the values from array you can simply do that with $quan_cls_crt[0] or $quan_cls_crt[1]

AJAX call is not working as expected

I am trying to send form data using ajax. But there's an error in ajax operation and only "error" callback function is executed.
Here's what I tried:
$("#issue_submit").click(function (e) {
console.log("clicked on the issue submit");
e.preventDefault();
// Validate the form
var procurementForm = $("#it_procuremet_form");
if($(procurementForm).valid()===false){
return false;
}
// Show ajax loader
appendData();
var formData = $(procurementForm).serialize();
// Send request to save the records through ajax
var formRequest = $.ajax({
url: app.baseurl("itprocurement/save"),
data: formData,
type: "POST",
dataType: "json"
});
formRequest.done(function (res) {
console.log(res);
});
formRequest.error(function (res, err) {
console.log(res);
});
formRequest.always(function () {
$("#overlay-procurement").remove();
// do somethings that always needs to occur regardless of error or success
});
});
Routes are defined as:
$f3->route('POST /itprocurement/save', 'GBD\Internals\Controllers\ITProcurementController->save');
Also I added :
$f3->route('POST /itprocurement/save [ajax]', 'GBD\Internals\Controllers\ITProcurementController->save');
I tried returning a simple string to the ajax call at the controller class.
ITProcurementController.php :
public function save($f3)
{
echo 'Problem!';
return;
$post = $f3->get('POST');
}
But only 'error' callback is executed. I cannot locate what is wrong. Please Help.
You are specifying that you expect json back:
// Send request to save the records through ajax
var formRequest = $.ajax({
url: app.baseurl("itprocurement/save"),
data: formData,
type: "POST",
// Here you specify that you expect json back:
dataType: "json"
});
What you send back is not json:
echo 'Problem!';
return;
This is an unquoted string, which is not valid json.
To send valid json back, you would need:
echo json_encode('Problem!');
return;
You could also remove the dataType attribute, depending on your needs.

How to send json to php via ajax?

I have a form that collect user info. I encode those info into JSON and send to php to be sent to mysql db via AJAX. Below is the script I placed before </body>.
The problem now is, the result is not being alerted as it supposed to be. SO I believe ajax request was not made properly? Can anyone help on this please?Thanks.
<script>
$(document).ready(function() {
$("#submit").click(function() {
var param2 = <?php echo $param = json_encode($_POST); ?>;
if (param2 && typeof param2 !== 'undefined')
{
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: param2,
cache: false,
success: function(result) {
alert(result);
}
});
}
});
});
</script>
ajaxsubmit.php
<?php
$phpArray = json_decode($param2);
print_r($phpArray);
?>
You'll need to add quotes surrounding your JSON string.
var param2 = '<?php echo $param = json_encode($_POST); ?>';
As far as I am able to understand, you are doing it all wrong.
Suppose you have a form which id is "someForm"
Then
$(document).ready(function () {
$("#submit").click(function () {
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: $('#someForm').serialize(),
cache: false,
success: function (result) {
alert(result);
}
});
}
});
});
In PHP, you will have something like this
$str = "first=myName&arr[]=foo+bar&arr[]=baz";
to decode
parse_str($str, $output);
echo $output['first']; // myName
For JSON Output
echo json_encode($output);
If you are returning JSON as a ajax response then firstly you have define the data type of the response in AJAX.
try it.
<script>
$(document).ready(function(){
$("#submit").click(function(){
var param2 = <?php echo $param = json_encode($_POST); ?>
if( param2 && typeof param2 !== 'undefined' )
{
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
dataType: "json",
success: function(result){
alert(result);
}
});}
});
});
</script>
It's just really simple!
$(document).ready(function () {
var jsonData = {
"data" : {"name" : "Randika",
"age" : 26,
"gender" : "male"
}
};
$("#getButton").on('click',function(){
console.log("Retrieve JSON");
$.ajax({
url : "http://your/API/Endpoint/URL",
type: "POST",
datatype: 'json',
data: jsonData,
success: function(data) {
console.log(data); // any response returned from the server.
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" value="POST JSON" id="getButton">
For your further readings and reference please follow the links bellow:
Link 1 - jQuery official doc
Link 2 - Various types of POSTs and AJAX uses.
In my example, code snippet PHP server side should be something like as follows:
<?php
$data = $_POST["data"];
echo json_encode($data); // To print JSON Data in PHP, sent from client side we need to **json_encode()** it.
// When we are going to use the JSON sent from client side as PHP Variables (arrays and integers, and strings) we need to **json_decode()** it
if($data != null) {
$data = json_decode($data);
$name = $data["name"];
$age = $data["age"];
$gender = $data["gender"];
// here you can use the JSON Data sent from the client side, name, age and gender.
}
?>
Again a code snippet more related to your question.
// May be your following line is what doing the wrong thing
var param2 = <?php echo $param = json_encode($_POST); ?>
// so let's see if param2 have the reall json encoded data which you expected by printing it into the console and also as a comment via PHP.
console.log("param2 "+param2);
<?php echo "// ".$param; ?>
After some research on the google , I found the answer which alerts the result in JSON!
Thanks for everyone for your time and effort!
<script>
$("document").ready(function(){
$(".form").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$(".the-return").html(
"<br />JSON: " + data["json"]
);
alert("Form submitted successfully.\nReturned json: " + data["json"]);
}
});
return false;
});
});
</script>
response.php
<?php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "test": test_function(); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test_function(){
$return = $_POST;
echo json_encode($return);
}
?>
Here's the reference link : http://labs.jonsuh.com/jquery-ajax-php-json/

How to handle json response from php?

I'm sending a ajax request to update database records, it test it using html form, its working fine, but when i tried to send ajax request its working, but the response I received is always null. where as on html form its show correct response. I'm using xampp on Windows OS. Kindly guide me in right direction.
<?php
header('Content-type: application/json');
$prov= $_POST['prov'];
$dsn = 'mysql:dbname=db;host=localhost';
$myPDO = new PDO($dsn, 'admin', '1234');
$selectSql = "SELECT abcd FROM xyz WHERE prov='".mysql_real_escape_string($prov)."'";
$selectResult = $myPDO->query($selectSql);
$row = $selectResult->fetch();
$incr=intval($row['votecount'])+1;
$updateSql = "UPDATE vote SET lmno='".$incr."' WHERE prov='".mysql_real_escape_string($prov)."'";
$updateResult = $myPDO->query($updateSql);
if($updateResult !== False)
{
echo json_encode("Done!");
}
else
{
echo json_encode("Try Again!");
}
?>
function increase(id)
{
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
success: function (response) {
},
complete: function (response) {
var obj = jQuery.parseJSON(response);
alert(obj);
}
});
};
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
dataType: 'json',
success: function (response) {
// you should recieve your responce data here
var obj = jQuery.parseJSON(response);
alert(obj);
},
complete: function (response) {
//complete() is called always when the request is complete, no matter the outcome so you should avoid to recieve data in this function
var obj = jQuery.parseJSON(response.responseText);
alert(obj);
}
});
complete and the success function get different data passed in. success gets only the data, complete the whole XMLHttpRequest
First off, in your ajax request, you'll want to set dataType to json to ensure jQuery understands it is receiving json.
Secondly, complete is not passed the data from the ajax request, only success is.
Here is a full working example I put together, which I know works:
test.php (call this page in your web browser)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// Define the javascript function
function increase(id) {
var post_data = {
'prov': id
}
$.ajax({
'type': 'POST',
'url': 'ajax.php',
'data': post_data,
'dataType': 'json',
'success': function (response, status, jQueryXmlHttpRequest) {
alert('success called for ID ' + id + ', here is the response:');
alert(response);
},
'complete': function(jQueryXmlHttpRequest, status) {
alert('complete called');
}
});
}
// Call the function
increase(1); // Simulate an id which exists
increase(2); // Simulate an id which doesn't exist
</script>
ajax.php
<?php
$id = $_REQUEST['prov'];
if($id == '1') {
$response = 'Done!';
} else {
$response = 'Try again!';
}
print json_encode($response);

Posting data to php file

I have the following variable in Javascript. I want to know how to pass this data to a PHP so that I can display the contents of the data once redirected.
postData = {
'dates_ranges': datesAndRanges,
'action':'build',
'output_type': output_type,
'form_html': formHtml,
'width': formBuilder.width(),
'rules':validationRules,
'theme': theme,
};
Use JQuery post method to pass data to PHP file:
$.post("/path/to/script.php", postData, function(result) {
// work with result
});
In PHP use $_POST global to get the variables:
print $_POST['dates_ranges'];
print $_POST['action'];
// ...
using jquery it goes easy & clean like this:
$.post('script.php', postData, function(response){
// process/display the server response
});
you can use:
$.post("YOUR_URL", postData, function(response) {
// handle with response
});
OR:
$.ajax({
url: YOUR_URL,
data: postData,
type: 'post',
success: function(response) {
// handle with response
}
});
And In your PHP file:
if(isset($_POST) && !empty($_POST)) {
$d = $_POST;
echo $d['date_range']; // and so more
}

Categories