How to pass value to another php using ajax..?

Since i’m new to ajax and dont know much about it… ive created 2 php files one is
six.php and another is six-cuf.phpBased on user inputs in six.php and clicks submit this will call the six-cuf.php using ajax and do the calculation.

But, when i executed and monitored the code thru network tab in chrome i came to know that the values were being passed to six-cuf.php , but it was not going inside the if condition inside the page hence it was not getting any response.

Whats wrong in my code…

Six.php

       <body>
       <div class="six">
   <form onsubmit="callphp()">
	  <label>CUF PERFORMANCE</label>
        <select id="select" name="options">
        <option>Select The Value</option>
        <option id="hourly" value="a">Hourly</option>
        <option id="daily" value="b">Daily</option>
        <option id="monthly" value="c">Monthly</option>
        <option id="yearly" value="d">Yearly</option> 
       </select><br/><br/>
	   
	    <label id="from"  style="display:none;">Enter starting Date and Time</label>
		<label id="start"  style="display:none;">Enter Starting Date</label>
	   <input id="dateInputone" name="dateipone" type="datetime-local" step="600" onblur="validate_time(this.value)" style="display:none;" >
	   <input id="dateIpone" name="dateone" type="date" style="display:none;">
	   
	   <label id="to"  style="display:none;">Enter Ending Date and Time</label>
	   <label id="end"  style="display:none;">Enter Ending Date</label>
	   <input id="dateInputtwo" name="dateiptwo" type="datetime-local" step="600" style="display:none;">
	   <input id="dateIptwo" name="datetwo" type="date" style="display:none;" >
	<br/><br/>
    
    <label for="Inverter">Inverter</label>
    <select name="ino" id="ino">
    <option>Select The Value</option>
	<option value="1">Inverter 1</option>
    <option value="2">Inverter 2 </option>
	<option value="3">Inverter 3</option>
	<option value="4">Inverter 4</option> 
	<option value="5">Inverter 5</option> 
	<option value="6">Inverter 6</option>
     </select><br/>

	
     <input type="submit"  value="submit" id="submit" name="submit" onclick="myFunction()">
	<br><br>
    </div>

below is script code in six.php

    <script>
 function callphp(){
 var dataa = {};
dataa.dateipone = jQuery("#dateInputone").val();
dataa.dateiptwo = jQuery("#dateInputtwo").val();
  dataa.ino = jQuery("#ino").val();
  dataa.options = jQuery("#select").val();
 dataa.dateone = jQuery("#dateIpone").val();
  dataa.datetwo = jQuery("#dateIptwo").val();
  dataa.submit = "submit";

    $.ajax({
        url : "six-cuf.php",
        type: 'POST',
        data : JSON.stringify(dataa),
        contentType : "application/json",
        success:function(data)
        {
            if(data){ 
              alert(data);   
              //console.log("Data from Server"+JSON.stringify(data));
            }
            else{
              console.log("Data is empty");
            } 
         },
         error: function(xhr) {
            alert('Error!  Status = ' + xhr.status + " Message = " + xhr.statusText);
            //console.log('Error!  Status = ' + xhr.status + " Message = " +  xhr.statusText);
        }
    });
}

</script>
</body>
</html>

Below is code of six-cuf.php

        include 'db.php';  
  if(isset($_POST["dateipone"],$_POST["dateiptwo"],$_POST["ino"],$_POST["options"],$_POST["dateone"],$_POST["datetwo"],$_POST["submit"]))
  {   
   $format = $_POST["options"];
   
   if($format == 'a')
   {   
    date_default_timezone_set('GMT');
    $fromdate = $_POST["dateipone"];
    $start =new Datetime('@'.strtotime( $fromdate));
    $todate = $_POST["dateiptwo"];
    $end =  new Datetime('@'.strtotime( $todate));
    $inverter = $_POST["ino"];
    $count = 1;
    $query = "SELECT timestamp, gridpowertotal FROM inverterlog where inverter = '" . $inverter . "' AND timestamp BETWEEN '" . $fromdate . "' AND '" . $todate . "'";
    
    if ($result = mysqli_prepare($con, $query))
    {
	   mysqli_stmt_execute($result);
	   mysqli_stmt_bind_result($result, $timestamp, $gridpowertotal);
	   $arr1= array();
	   $arr2=array();
	   $array_associate = array();
	   $hourArray = array();
	   
	   while(mysqli_stmt_fetch($result))
	   {
		     $obj =  new stdClass();
		     $obj->timestamp = $timestamp;
		     $obj->gridpowertotal = $gridpowertotal;
		     $array_associate[$timestamp]=$obj;
	   }
	   
		mysqli_stmt_close($result);
		mysqli_close($con);
		
		$interval = new DateInterval('PT10M');
		$daterange = new DatePeriod($start, $interval ,$end);
	    $sum = 0;
		foreach($daterange as $date){
			$index = $date->format("Y-m-d H:i:s");
			
			if($count%6 == 1) {
				$backupIndex = $index;
			}
			if($count%6==0) {
				$count++;
				if(array_key_exists($index,$array_associate) && $array_associate[$index]!=null){ 
					$sum = $sum+$array_associate[$index]->gridpowertotal;
				} 
				else {
					$sum = $sum+0;
					$obj2 =  new stdClass();
		            $obj2->timestamp = $index;
					$obj2->gridpowertotal = 0;
		           $array_associate[$index] = $obj2; 
				}
				$obj1 = new stdClass();
				$obj1->timestamp = $backupIndex;
				$obj1->sum  = $sum;
				array_push($hourArray,$obj1);
				$sum = 0;
			} else {
				if(array_key_exists($index,$array_associate) && $array_associate[$index]!=null) {
					$sum = $sum+$array_associate[$index]->gridpowertotal;
				} else {
					$sum = $sum+0;
					$obj2 =  new stdClass();
		            $obj2->timestamp = $index;
					$obj2->gridpowertotal = 0;
		           $array_associate[$index] = $obj2; 
				
				}
				$count++;
			}
			
		} 
		var_dump($hourArray);
		$narray = array_values($hourArray);
		
	       foreach($narray as $object){
			 array_push($arr1,$object->timestamp);
			 array_push($arr2,$object->sum); 
		   }
   }
  header('Content-type: application/json');
     echo json_encode(array('format'=>"Helllo"));  
   }
else
if($format == 'b')
{
    $fromdate = $_POST['dateone'];
	$todate = $_POST['datetwo'];
	$inverter = $_POST['ino'];
	$dayArray = array();
    $arr1 = array();
    $arr2 = array();
	$query = "SELECT DATE(`timestamp`) as timestamp, SUM(`gridpowertotal`) as gridpowertotal FROM inverterlog where inverter = '" . $inverter . "' AND DATE(`timestamp`) BETWEEN '" . $fromdate . "' AND '" . $todate . "' GROUP BY  DATE(`timestamp`)";
	if ($result = mysqli_prepare($con, $query))
    {
	   mysqli_stmt_execute($result);
	   mysqli_stmt_bind_result($result, $timestamp, $gridpowertotal);
	   while(mysqli_stmt_fetch($result))
	   {
		   array_push($dayArray,$timestamp,$gridpowertotal);
		   array_push($arr1,$timestamp);
		  array_push($arr2,$gridpowertotal);	
	   }
	    var_dump($nArray)."<br/>";
	    var_dump($arr1)."<br/>";
		var_dump($arr2)."<br/>";	   
	  }
	  
	mysqli_stmt_close($result);
    mysqli_close($con);	
}

else
if($format == 'c')
     {
	
	
   }
 
    } 
   ?>

Its not entering inside if() at the begining in the above code what is the mistake

What do you get if you var_dump($_POST) at the start of that code?

@droopsnoot…in which page ive used var_dump($_POST) at the start…in six-cuf.php.??

Yes, to see what’s coming into that code in the array. I’m not sure whether you’ll need to make a change to the calling code to see the contents of the var_dump, I haven’t done much Ajax, and the small amount I’ve done was a while ago.

How to pass value to another php using ajax

regarding my previous post…when i tried to decode the json.stringify data it returned error so used json_last_error to know the error it returned the following error

Syntax error, malformed JSON

can anyone verify my ajax code enclosed in javascript function and spot the error ive done.

     <script>
 function callphp(){
 var dataa = {};
 dataa.dateipone = jQuery("#dateInputone").val();
 dataa.dateiptwo = jQuery("#dateInputtwo").val();
dataa.ino = jQuery("#ino").val();
dataa.options = jQuery("#select").val();
dataa.dateone = jQuery("#dateIpone").val();
dataa.datetwo = jQuery("#dateIptwo").val();
dataa.submit = "submit";
alert("Hello")
$.ajax({
        url : "six-cuf.php",
        type: 'POST',
        data :JSON.stringify(dataa),
        contentType : "application/json; charset=utf-8",
        success:function(data)
        {
            if(data){ 
              alert(data);   
              //console.log("Data from Server"+JSON.stringify(data));
            }
            else{
              console.log("Data is empty");
            } 
        },
        error: function(xhr) {
            alert('Error!  Status = ' + xhr.status + " Message = " + xhr.statusText);
            //console.log('Error!  Status = ' + xhr.status + " Message = " +  xhr.statusText);
        }
    });
}

below is my six-cuf.php

      $data = json_decode($_POST['dataa']);
print_r($data);

switch (json_last_error()) {
    case JSON_ERROR_NONE:
        echo ' - No errors';
    break;
    case JSON_ERROR_DEPTH:
        echo ' - Maximum stack depth exceeded';
    break;
    case JSON_ERROR_STATE_MISMATCH:
        echo ' - Underflow or the modes mismatch';
    break;
    case JSON_ERROR_CTRL_CHAR:
        echo ' - Unexpected control character found';
    break;
    case JSON_ERROR_SYNTAX:
        echo ' - Syntax error, malformed JSON';
    break;
    case JSON_ERROR_UTF8:
        echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
    break;
    default:
        echo ' - Unknown error';
    break;
  }

for remaining complete code please go to the link ive shared

there is no dataa key in your POST data.

1 Like

@Dormilich…the javascript object value is being not posted to my another php page…?? If so can u just provide me with an example how to pass those values…im new to ajax and dont know much…itll be a help…thank u in advance…

Have a look at this post, someone with a similar issue and what appears to be a decent response: http://stackoverflow.com/questions/10955017/sending-json-to-php-using-ajax

It appears that what you really need to do is remove the contentType string. Then just var_dump($_POST) to see how the array is sent.

1 Like

@droopsnoot…thanks for sharing the post…just did exactly as u said gave me empty array like this Array()…thank u again…

Did you also note the part about assigning a name to the variable you pass to the php file?

data : { data: dataa },

I copied your code and ran it locally, if I add the above (and a refernce to jquery) and remove the contentType line, then I get results in the var_dump($_POST) in the php file.

This is my quick destination php file:

<?php
//var_dump($_POST);
echo "Inverter " . $_POST['data']['ino'];
echo " Performance " . $_POST['data']['options'];
?>
1 Like

It is, but not the way you assume it to be. see @droopsnoot’s explanation.

1 Like

@droopsnoot and @Dormilich …thanks a lot… resolved the issue…:relieved:

I would start by doing the following at the start of the destination file
var_dump($_POST);
Are all the input fields in the $_POST array there and holding the correct values
If not do
var_dump($_SERVER);
Look for the HTTP_REQUEST_METHOD and see if it is post
Two other questions are
Is the js script running?
Any error will stop it from running
Look at the console to check for js errors.
Add an alert(“js is up and running”); at the end of the script which will let you know that to has run.
When is the js script running?
If it runs before the page has loaded any statements that change the vanilla html will have run before the elements exist.
In a nutshell get six.php to send the correct data in the correct form. Test with the var_dump() statements at the start of six-cud.php.
When that is happening then work out how to store the data into the database.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.