From one php file I need to pass two ajax variables to two independent javascript files in the same isset condition

67

In php file:

if(isset($_POST["my_first_variable"]))
{
   if(empty($_POST["my_first_variable"]))
   {
      //This $rtrn variable I need to return to another ajax function in 
      another javascript file

      $rtrn["my_return_second_variable"]="First variable is empty";
      echo json_encode($rtrn);
   }
}

From first javascript file I send input data variable to php, where I check If that value is not empty and correct , If it is I need to send returning data to another javascript file that tells that input is empty or incorrect to disable submit button on main page.

986

Answer

Solution:

PHP cannot arbitrarily send data to some random file. It sends data back to the file which requested it.

You need your Javascripts to communicate with each other:

myscript.php

if(isset($_POST["my_first_variable"]))
{
   if(empty($_POST["my_first_variable"]))
   {
      //This $rtrn variable I need to return to another ajax function in 
      another javascript file

      $rtrn["my_return_second_variable"]="First variable is empty";
      echo json_encode($rtrn);
   }
}

first.js

$(function(){
    $.ajax({
        url: 'www.example.com/myscript.php', // Send a request with POST data to this file
        type: 'POST', // Send as a POST and not GET
        data: { 'my_first_variable' : '' }, // Make sure this data is set but empty to satisfy the logic in myscript.php
        dataType: 'json', // We expect to receive JSON data
        success: function( data ){
            doSomething( data ); // Send this data to second.js
        }
    });
});

second.js

function doSomething( incomingData ){
    alert( incomingData[ 'my_return_second_variable' ] );
}

Make sure to load both of these files and it should work.


For the sake of anyone using Google, some common search phrases could be:

  • How to send data from one JS file to another?
  • How can PHP split which JS files receive data?
  • Pass data from one Js file to another.

People are also looking for solutions to the problem: php - Form submission shows up a blank entry in mysql

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.