jquery ajax sending json to php error - php

Okay so here is my ajax request:
$("#scoreForm").submit(function(e){
e.preventDefault();
var nickName = $('#nickName').val();
var gameScore = parseInt($('#gameScore').text());
var result = { 'result' : '{ "nick":"'+nickName+'", "score":'+gameScore+' }' };
//var result = { "nick":nickName, "score":gameScore };
$.ajax({
url: "http://localhost:8888/snake/addScore.php",
type: "POST",
data: result,
//dataType: "jsonp",
success: function(data){
alert("siker");
},
error: function(jqXHR, textStatus, errorThrown) {
alert("bukta " + textStatus);
//console.log(data);
}
});
return false;
});
and my php process code:
$json_decoded = json_decode($_POST['result'],true);
//$nick = $_GET['nick'];
//$score = $_GET['score'];
$mysqli = new mysqli("localhost", "root", "root", "snake",8889);
//$mysqli->query("INSERT INTO scores(nickName,score) VALUES('".$nick."', ".$score.")");
$mysqli->query("INSERT INTO scores(nickName,score) VALUES('".$json_decoded['nick']."', ".$json_decoded['score'].")");
echo "true";
Now i got the data inserted into the database, but ajax still firing error event. i read that if i set the dataType to jsonp it will go trough , but then i get parse error, how do i get past that?

Wehn you access the $_POST variables in your php script, you need to refer to them the way they are packaged with the JSON object:
$_POST['nick']
$_POST['score']
If you want to refer to the items as $_POST['result'] and use your json decoding approach, youll need to package it this way:
var result = { result : { "nick":nickName, "score":gameScore } };

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]

codeigniter ajax getting the value of json from model

I am having trouble how to get the returned json from my controller to my view. The passing of the data is already okay, but i dont know how to decode or get the specific values of the json encoded.
All i want is to store my specific values of json to a variable for further use. Something like this :
$project_name = val.($json['project_name');
Here is my code from my view :
function showprojectdetails(projectSelected) {
var studentId = null;
$.ajax({
url : "<?php echo site_url('manager/projects/ProjDetails/')?>/" + projectSelected,
type: "GET",
dataType: "JSON",
success: function(data) {
$json = json_decode(data, true);
alert($json['project_code'];);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error get data from ajax');
}
});
}
my Controller :
function ProjDetails($project_title) {
$data = $this->project->getProjDetails($project_title);
echo json_encode($data);
}
My model :
function getProjDetails($project_title) {
$this->db->from('project');
$query = $this->db->query('SELECT * from project where project_code = "'.$project_title.'" ');
return $query->row();
}
You dont need to decode the value in js. json_encode would convert array into json string. So what you get in view is already json. You simply needs to use it.
This will show you the json string in console.
console.log(data)
use
data['project_code']
You should combine PHP function
json_encode($your_json_string);
with JS
JSON.parse(response);
As in:
function showprojectdetails(projectSelected) {
var studentId = null;
$.ajax({
url : "<?php echo site_url('manager/projects/ProjDetails/')?>/" + projectSelected,
type: "GET",
dataType: "JSON",
success: function(data) {
var json = JSON.parse(data);
//do the magic you wanted to do like alert(json);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error get data from ajax');
}
});
}

AJAX call returning empty object from json_encode

I'm making an AJAX call to a fairly simple PHP function. The response should be a JSON object to be manipulated, but my response is always an empty object.
Relevant Code:
index.html's AJAX Call:
$( function() {
$('#dates').on('submit', function (e) {
var start_time = new Date().getTime();
e.preventDefault();
var submitData = $('#dates').serialize();
console.log(submitData);
$.ajax({
type:'POST',
url:'inflow.php',
data:$('#dates').serialize(),
dataType: 'json',
beforeSend: function(){
$('#loading').show();
},
success: function(data) {
console.log(data);
$('#loading').hide();
},
error:function(xhr, desc, err){
alert('You tried to send an AJAX request, but something went wrong.\n Please Contact the NASR WebDev Team');
console.log(xhr);
console.log("Details: " + desc +"\nError: "+ err);
}
});
});
});
inflow.php's array creation and echo:
<?php
$msqlStart = $_POST['start_date'];
$msqlEnd = $_POST['end_date'];
$inflowQuery=
"SELECT
COUNT,
QUEUE_ID,
QUEUE_GROUP,
INFLOW_DATE,
LINE_OF_BUSINESS
FROM
ticket_inflow.inflow
WHERE
ROUTE_STATUS = 'Inflow'
AND inflow_date between ? and ?";
$connect = new mysqli($host, $user, $password, $database);
if ($connect->connect_error){
die("Failed to Connect:.".$connect->connect_errno.": ".$connect->connect_error);
}
if(!($statment = $connect->prepare($inflowQuery))){
die('Error in Preparation Error Number:%d Error: %s');
}
if(!$statment->bind_param('ss', $msqlStart, $msqlEnd)){
die ('Error in Binding');
}
if(!$statment->execute()){
die('Error In Execution');
}
$statment->bind_result($inflowCount, $inflowQueue, $inflowQG, $inflowDate, $inflowLOB);
$a_json = array();
$jsonRow = array();
While($statment->fetch()){
$UID = 0;
$jsonRow['UID'] = $UID++;
$jsonRow['count'] = utf8_encode($inflowCount);
$jsonRow['inflow_date'] = utf8_encode($inflowDate);
$jsonRow['queue'] = utf8_encode($inflowQueue);
$jsonRow['queue_group'] = utf8_encode($inflowQG);
$jsonRow['lob'] = utf8_encode($inflowLOB);
array_push($a_json, $jsonRow);
}
$jsonReturn = json_encode($a_json);
echo $jsonReturn;
?>
If I go directly to inflow.php and pass it parameter's identical to what the page passes it, I get what appears to be a nice JSON object, however when I look at the response Chrome Developer's Tools I get:
[]
And nothing more.
You are sending form data, not json;
$.ajax({
type:'POST',
url:'inflow.php',
data:$('#dates').serialize(),
//contentType: "application/json",<-- remove this
dataType: 'json',

fetch data from JSON in PHP

I have a JSON code that send a form to on PHP file and I want to use data in PHP
the code is:
// add button .click
$('a.add').click(function(){
$('#loader').show();
var url = "/yadavari/test.php?";
var json_text = JSON.stringify($("form[name='add']").serialize(), null, 2);
var datas = JSON.parse(json_text);
ajx = $.ajax({
url: url,
type: 'post',
data: datas,
dataType: 'json',
success: function(r) {
$('#loader').hide();
if(r.r != 0){
alert("ok");
jsmsalert($('#alert_add'),'success',r.m);
apendtable(r.r);
$("tr").removeClass("odd");
$("tr.viewrow:odd").addClass("odd");
$("tr.editrow:odd").addClass("odd");
$('td[colspan="7"]').remove();
}
else{
jsmsalert($('#alert_add'),'error',r.m,0);
}
},
error: function(request, status, err) {
$('#loader').hide();
jsmsalert($('#alert_add'),'error','error msg');
alert( "ERROR: " + err + " - " );
}
Now I want to fetch data from this JSON code in my PHP page.
I searched but every body just said that $string='{"name":"John Adams"}'; and so.
But I dont know that how can I have this $string in my PHP.
You should have something like:
<?php
echo $_POST["INPUTNAME"];
?>
Care about this, it suffers from security injection.
You need to call the php json_decode function on the returned string. This will convert it into an associative array:
$json2array = json_decode($json_text);
echo $json2array['name']; // "John Adams"

Multi Delete using checkbox

I am learning Cakephp and I've been trying to delete multiple (checked) record using checkbox, but still not success. here's my jQuery :
var ids = [];
$(':checkbox:checked').each(function(index){
ids[index] = $(this).val();;
alert(ids[index]);
});
//alert(ids);
var formData = $(this).parents('form').serialize();
$.ajax({
type: "POST",
url: "tickets/multi_delete",
data:"id="+ids,
success: function() {
alert('Record has been delete');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
}
});
and here is code in controller :
function multi_delete() {
$delrec=$_GET['id'];
//debuger::dump($del_rec);
foreach ($delrec as $id) {
$sql="DELETE FROM tickets where id=".$id;
$this->Ticket->query($sql);
};
}
anybody will help me please. thank
you could try a .join(',') on the array of IDs and then an explode() on the server side to get the array of IDs passed to the script.
e.g.
var idStr = ids.join(',');
pass it (idStr) to the ajax call
$.ajax({
type: "POST",
url: "tickets/multi_delete",
data: {id:idStr},
//more code cont.
on the server side:
$ids = explode(',',$_POST['ids']);
OR
check the jquery.param() function in the jquery docs. Apply and to the IDS array and then pass it to $.ajax({});
Note: You are using POST and not GET HTTP METHOD in the code you provided
use json encode and decode for serialized data transfer
Since JSON encoding is not supported in jQuery by default, download the JSON Plugin for jQuery.
Your javascript then becomes:
$.ajax({
type: "POST",
url: "tickets/multi_delete",
data: { records: $.toJSON(ids) },
success: function() {
alert('Records have been deleted.');
},
});
In the controller:
var $components = array('RequestHandler');
function multi_delete() {
if (!$this->RequestHandler->isAjax()) {
die();
}
$records = $_POST['records'];
if (version_compare(PHP_VERSION,"5.2","<")) {
require_once("./JSON.php"); //if php<5.2 need JSON class
$json = new Services_JSON();//instantiate new json object
$selectedRows = $json->decode(stripslashes($records));//decode the data from json format
} else {
$selectedRows = json_decode(stripslashes($records));//decode the data from json format
}
$this->Ticket->deleteAll(array('Ticket.id' => $selectedRows));
$total = $this->Ticket->getAffectedRows();
$success = ($total > 0) ? 'true' : 'false';
$this->set(compact('success', 'total'));
}
The RequestHandler component ensures that this is an AJAX request. This is optional.
The corresponding view:
<?php echo '({ "success": ' . $success . ', "total": ' . $total . '})'; ?>
Wish you luck!

Categories