0

Trying to send (with ajax,json) data from file No1 to file No2 and then from file No2 send data to file No1

Here is code in file No1

HTML

<div id="first_var">1 one</div>
<div id="second_var">2 two</div>
<div id="load"></div>

Ajax

$(document).ready(function(){
var one = $("#first_var").val();
var two = $("#second_var").val();
var dataString = 'one='+first_var+'&two='+second_var;

$.ajax({
type: "POST",
url: 'fileNo2.php',

data: dataString,
dataType: "json",

success: function(data) {
$('#load').html(data);
}
});

Here is file No2

$p_one = $_POST['p_one'];
$p_two = $_POST['p_two'];
$test = $p_one. '<br>test<br>'. $p_two;
echo json_encode($test);

As a result in <div id="load"></div> see only word test

If instead of data: dataString, use data : { p_one: 'test 1', p_two: 'test 2' }, then everything works.

Possibly incorrectly definied var one etc? Seems var one = $("#first_var").val(); val() can be used if <div id="first_var">1 one</div> would be input field. But if it is not input field? Simply text inside id="first_var....

Please, advice.

1 Answer 1

1

You just need to name the keys correctly in the data string. The PHP script is expecting "p_one" and "p_two", not "one" and "two".

var dataString = 'p_one='+first_var+'&p_two='+second_var;

Also, you need .text(), not .val() to get the inner text:

var one = $("#first_var").text();
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, sorry my negligence again... changed one example and have not paid enough attention. Now partly works. in <div id="load"></div> get [object HTMLDivElement] instead of 1 one and 2 two
@user2465936 maybe a couple more problems ... for one, you need .text() instead of "val".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.