Get JSON from Javascript to PHP - javascript

I have a javascript function that sends JSON to my server:
$("#sendRoute").live('click', function(){
trackCoords_str = JSON.stringify(trackCoords);
final_time_m_str = JSON.stringify(final_time_m);
final_time_s_rounded_str = JSON.stringify(final_time_s_rounded);
aver_speed_km_h_rounded_str = JSON.stringify(aver_speed_km_h_rounded);
total_km_rounded_str = JSON.stringify(total_km_rounded);
$.ajax({
url: "http://test.whirlware.biz/server/",
type: "POST",
data: {
route : trackCoords_str,
timeInMinutes: final_time_m_str,
timeInSeconds: final_time_s_rounded_str,
averageSpeed: aver_speed_km_h_rounded_str,
distance: total_km_rounded_str,
},
dataType: "json"
});
});
And mix of PHP and JS code that receive and display my JSON data
<?php
$route = $_POST['route'];
$timeInMinutes=$_POST['timeInMinutes'];
$timeInSeconds=$_POST['timeInSeconds'];
$averageSpeed=$_POST['averageSpeed'];
$distance=$_POST['distance'];
$trackCoords = json_decode($route, false);
$total_km_rounded = json_decode($timeInMinutes, false);
$final_time_m = json_decode($timeInSeconds, false);
$final_time_s_rounded = json_decode($averageSpeed, false);
$aver_speed_km_h_rounded = json_decode($distance, false);
echo $trackCoords['coordsarray'];
echo $total_km_rounded;
echo $final_time_m;
echo $final_time_s_rounded;
echo $aver_speed_km_h_rounded;
?>
<script type="text/javascript">
var total_km_rounded = '<?php echo $total_km_rounded ?>';
document.write('Растояние: ' + total_km_rounded);
var final_time_m = '<?php echo $final_time_m ?>';
document.write('Растояние: ' + final_time_m);
var final_time_s_rounded = '<?php echo $final_time_s_rounded ?>';
document.write('Растояние: ' + final_time_s_rounded);
var aver_speed_km_h_rounded = '<?php echo $aver_speed_km_h_rounded ?>';
document.write('Растояние: ' + aver_speed_km_h_rounded);
</script>
But when I send JSON data my server don`t display it. Where did I make a mistake? Maybe I can receive JSON another way?

Try this, success: function(response) {alert('Success!');}, after the data, not inside the data
data: {
route : trackCoords_str,
timeInMinutes: final_time_m_str,
timeInSeconds: final_time_s_rounded_str,
averageSpeed: aver_speed_km_h_rounded_str,
distance: total_km_rounded_str
},
success: function(response) {alert('Success!');},

You should JSON.stringify an array like this(general convention):
//rough code
data['trackCoords_str'] = trackCoords;
data['final_time_m_str'] =final_time_m;
data['final_time_s_rounded_str'] = final_time_s_rounded;
data['aver_speed_km_h_rounded_str'] = aver_speed_km_h_rounded;
data['total_km_rounded_str'] = total_km_rounded;
$.ajax({
url: "http://test.whirlware.biz/server/",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
success: function(){ alert('success!'); },
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
alert(thrownError);
});
});

Related

Get value in textbox using ajax response

I want Broker Commsion on Selection of Admin with the help of Ajax Only.
<select id="user_id" onchange="funCom(this);" >
<option value="" >Select Broker </option>
<?php $aData=$oGeneral->get_records('tbl_user');
$aUsertDetails = $oGeneral->aAdmin;
$iUserDetails = $oGeneral->iAdmin;
for($i=0;$i<$iUserDetails;$i++){?>
<option value="<?=$aUsertDetails[$i]['fld_id']?>">
<?php echo $aUsertDetails[$i]['fld_name']; ?></option>
<?php }?>
</select>
<input type="text" id="comm" name="fld_commision" value="" onkeyup="sum()" required>
Funtion calling
function funCom(id){
id = id.value;
Token= "search-comm";
SendData= "Token="+Token+"&id="+id;
$.ajax({ url: 'Ajaxhandler.php',
dataType: 'text',
type: 'post',
async: false,
data: SendData,
success: function(data)
{
//var commision=stripHTML(data);
//$('#comm').val(commision); again not working
//$('#comm').text(data); Tried this but fail
$('#comm').val(data); //output is <body></body></html>7000
// i want only 7000 i have tried
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
} });
}
It is Ajaxhandler.php.
Here I am geting the commsion value which needs to put into textbox. The value is showing in <div> but I want in text box.
<?php
require('../configuration/configuration.php');
$oGeneral = new GeneralClass();
$oUser = new UserClass();
$token= $_REQUEST['Token'];
switch($token) {
case 'search-comm': $id=$_REQUEST['id'];
$oUser->project_commision($id);
$aUsertDetails = $oUser->aResults;
$iUsertDetails = $oUser->iResults;
$total=0;
for($i=0;$i<$iUsertDetails;$i++){
$total+= $aUsertDetails[$i]['fld_commsionprice'];
}
echo $total;
break;
}
?>
Change your datatype to json and try this.
Funtion calling
function funCom(id){
id = id.value;
Token= "search-comm";
SendData= "Token="+Token+"&id="+id;
$.ajax({ url: 'Ajaxhandler.php',
dataType: 'json',
type: 'post',
async: false,
data: SendData,
success: function(data)
{
//var commision=stripHTML(data);
//$('#comm').val(commision); again not working
//$('#comm').text(data); Tried this but fail
$('#comm').val(data.total); //output is <body></body></html>7000
// i want only 7000 i have tried
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
} });
}
is Ajaxhandler.php
$token= $_REQUEST['Token'];
switch($token)
{
case 'search-comm': $id=$_REQUEST['id'];
$oUser->project_commision($id);
$aUsertDetails = $oUser->aResults;
$iUsertDetails = $oUser->iResults;
$total=0;
for($i=0;$i<$iUsertDetails;$i++){
$total+= $aUsertDetails[$i]['fld_commsionprice'];
}
echo json_encode(array('total'=>$total));
break;
}
?>
try this code, I test in my computer and that works!
function funCom(id){
id = id.value;
Token= "search-comm";
SendData= "Token="+Token+"&id="+id;
$.ajax({ url: 'Ajaxhandler.php',
type: 'POST',
data: {Token:Token,id:id},
}).done(function( data ) {
$("#comm").val(data.total);
});
<?php
$token= $_REQUEST['Token'];
header('Content-type: application/json');
switch($token)
{
case 'search-comm':
$id=$_REQUEST['id'];
$oUser->project_commision($id);
$aUsertDetails = $oUser->aResults;
$iUsertDetails = $oUser->iResults;
$total=0;
for($i=0;$i<$iUsertDetails;$i++){
$total+= $aUsertDetails[$i]['fld_commsionprice'];
}
echo json_encode(array('total'=>$total));
die;
}
echo json_encode(array('total'=>""));
die;
?>

Sending PHP values with AJAX

I am trying to delete images with Ajax and all the php seems to work except when I try to send variables to another php document.
Php that shows and grabs neccessary values.
// show images
$image_display = "";
foreach(glob($pathimages.'*') as $filename){
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$name_only = basename($filename, ".".$ext);
$image_display .= "<img src=\"images/" .$targetID."/" .$name_only.".".$ext. "\" width=\"30\" />
<a onclick=\"DeleteImage('".$name_only."','".$ext."','".$targetID"'); return false;\" href=\"javascript:;\">X</a>
<br />";
}
.JS document, I get the sent and the success messages when pressing the X
function DeleteImage(name_only, ext, targetID){
$.ajax({
url: 'delete_imgs.php',
type: "POST",
data:{name_only:name_only,ext:ext,targetID:targetID},
beforeSend: function() {
alert("sent");
},
success: function(html) {
alert("Success")
},
error: function( x, status, error ) {
alert(x.status + status + error);
}
});
}
delete_imgs.php document
include('session_check.php');
$name_only = $_POST['name_only'];
$ext = $_POST['ext'];
$targetID = $_POST['targetID'];
$pathimages = "images/$targetID/";
unlink($pathimages . $name_only .".". $ext);
echo "Deleted";
Any thoughts are more than welcome since I have banged my brain out of my head by now ...!
Cheers!
Try with async:false
function DeleteImage(name_only, ext, targetID){
$.ajax({
url: 'delete_imgs.php',
type: "POST",
async : false,
data:{name_only:name_only,ext:ext,targetID:targetID},
beforeSend: function() {
alert("sent");
},
success: function(html) {
alert("Success")
},
error: function( x, status, error ) {
alert(x.status + status + error);
}
});
}
Maybe that can help

jquery ajax call in codeigniter

i have two function one is for delete and another for update . My delete function is working correctly but when i have written update function that is not working . Also update not working.
Here is the view
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script>
$(document).ready(function()
{
$('table#delTable td button.delete').click(function()
{
if (confirm("Are you sure you want to delete this row?"))
{
var id = $(this).parent().parent().attr('id');
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: "<?php echo base_url('Welcome/delete');?>",
data:'id='+id,
cache: false,
success: function()
{
parent.fadeOut('slow', function()
{$(this).remove();});
}
});
}
});
$('table#delTable tr:odd').css('background',' #FFFFFF');
});
function update(str){
var id=str;
var nm=$('#nm'+str).val();
var em=$('#em'+str).val();
var st=$('#st'+str).val();
var ph=$('#ph'+str).val();
var dp=$('#dp'+str).val();
var un=$('#un'+str).val();
var datas="id="+id+"&nm="+nm+"&em="+em+"&st="+st+"&ph="+ph+"&dp="+dp+"&un="+un;
$.ajax(
{
type: "POST",
url: "<?php echo base_url('Welcome/update');?>,
data:datas,
cache: false,
success: function(msg) {
alert(msg);
}
});
}
</script>
<button type="button" class="delete>Delete</button>
<button type="button" onclick="update(<?php echo $row['id']; ?>)">Save</button>
Controller
public function update(){
$id=$_POST['id'];
$userName=$_POST['nm'];
$tokens=explode("",$userName);
$fName=$tokens[0];
$lName=$tokens[1];
$userEmail=$_POST['em'];
$userUni=$_POST['un'];
$userState=$_POST['st'];
$userDept=$_POST['dp'];
$userPh=$_POST['ph'];
$array = array(
'first_name' => $fName,
'last_name' => $lName ,
'email' => $userEmail,
'phone_number' => $userPh,
'varsity_name' => $userUni,
'state' => $userState,
'dept_name'=> $userDept,
);
$this->load->model('Prime_Model');
$result=$this->Prime_Model->updateProfile($id,$array);
if($result){
return "Data has updated";
}
else{
return "Nothing";
}
}
You miss double quote after ?> below:
$.ajax({
type: "POST",
url: "<?php echo base_url('Welcome/update');?>", // here
data: datas,
cache: false,
success: function(msg) {
alert(msg);
}
});

Send Array of Json from Ajax to PHP

I try to send an array of json objects from the javascript to a Php code. Unable to get a response from the php file.
function getData() {
var jsonObject = [];
var genderMenu = document.getElementById("gender");
var levelMenu = document.getElementById("level");
jsonObject[0] = {
psid: document.getElementById("psid").value,
fName: document.getElementById("fname").value,
lName: document.getElementById("lname").value,
gender: genderMenu.options[genderMenu.selectedIndex].value,
};
for(var i = 1; i <= varCount; i++) {
if(document.getElementById("fName"+(i))) {
jsonObject[i] = {fName : document.getElementById("fName"+(i)).value,
lName: document.getElementById("lName"+(i)).value,
};
}
}
var jsonObjectString = JSON.stringify(jsonObject);
var result = "";
$.ajax({
type: 'POST',
url: '/inviteProcessing.php',
data: {myData: jsonObject},
success: function(response) {
if(response.success)
alert(response.message);
else
alert(response.message);
}
});
alert(jsonObject);
}
Php File has the following code
<?php
$input = $_POST['myData'];
$input_string = json_decode($input, true);
echo json_encode( array('success' => true, 'message' => $input_string) );
?>
Do u see any problem?
Prior to echoing your output, try...
header('Content-type: application/json');
echo $encodedjsonstring;
exit;
Please try below points.
First check if path of the php file is correct.
Then add below line in ajax call.
type: 'POST',
dataType: "json", //add dataType
url: '/inviteProcessing.php',
data: {myData: jsonObject},
try to put exit or die() at the end of php file

double json response

I don't know why this double json response are not successful:
[{"first_content":"content",...}][{"second_content":"content",...}]
So i am getting the message Oops! Try Again.
if(isset($_GET['start'])) {
echo get_posts($db, $_GET['start'], $_GET['desiredPosts']);
echo get_posts1($db, $_GET['start'], $_GET['desiredPosts']);
$_SESSION['posts_start']+= $_GET['desiredPosts'];
die();
}
var start = <?php echo $_SESSION['posts_start']; ?>;
var desiredPosts = <?php echo $number_of_posts; ?>;
var loadMore = $('#load-more');
loadMore.click(function () {
loadMore.addClass('activate').text('Loading...');
$.ajax({
url: 'profile.php',
data: {
'start': start,
'desiredPosts': desiredPosts
},
type: 'get',
dataType: 'json',
cache: false,
success: function (responseJSON, responseJSON1) {
alert(responseJSON);
loadMore.text('Load More');
start += desiredPosts;
postHandler(responseJSON, responseJSON1);
},
error: function () {
loadMore.text('Oops! Try Again.');
},
complete: function () {
loadMore.removeClass('activate');
}
});
});
What is the solution to get a double json response ? With one there is no problem
"Double JSON response" as you call them is basically invalid JSON. You should have something like so:
{"first_content":"content", "second_content":"content",...}
Or as a couple of people mentioned:
[{"first_content":"content",...}, {"second_content":"content",...}]
You probably need to modify some server side code, your get_posts function could return a PHP array instead of a JSON array. Example:
function get_posts(){
$array = array('content' => 'foo', 'title' => 'bar');
return $array;
}
Then in your profile.php:
if(isset($_GET['start'])) {
$posts = get_posts($db, $_GET['start'], $_GET['desiredPosts']);
$posts1 = get_posts1($db, $_GET['start'], $_GET['desiredPosts']);
echo array($posts, $posts1);
$_SESSION['posts_start']+= $_GET['desiredPosts'];
die();
}

Categories

Resources