0

I'm trying to send a JavaScript variable to a PHP script, use the variable in my SQL statement, and then send the results back to JavaScript.

JavaScript:

// Sending a variable to PHP script
var variableToSend = '30';
$.post('myPHPscript.php', {variable: variableToSend});

// Using the variable from earlier, run PHP script to get results
var data_from_ajax;
$.get('http://www.mywebsite.com/myPHPscript.php', function(data) {
data_from_ajax = data;
});

// Display results on the document
var displayResult = document.getElementById('displayResult');
displayResult.innerHTML = data_from_ajax;

PHP:

<?php
// Connection stuff
$conn = new mysqli($servername, $username, $password, $dbname);

// Get the sent variable
$variable = $_POST['variable'];

// Run SQL statement
$sql = "
    SELECT column
    FROM myDatabase 
    WHERE id=$variable
";

$result = $conn->query($sql);

// Send results back to JavaScript 
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
    echo $row["column"]; 
}
?> 

The reason that JS is calling a PHP script is because I used an event listener in JS to determine the variable that I want to send. The variableToSend varies every time depending on what was clicked, but I have set it to some random number here.

I'm aware that the problem lies in sending variables to PHP scripts in the JavaScript, but I'm unsure how else I can do this, besides using .post and .get.

I also considered using an AJAX call, but I wasn't sure how that would work.

Thank you for any pointers.

1
  • you are already using 2 ajax calls. You should only be making one Commented Mar 18, 2017 at 22:39

2 Answers 2

1

You are already using ajax, twice, via $.post and $.get.

You only need to make the post request, and display the response:

// Sending a variable to PHP script via ajax post, and display the returned results
var variableToSend = '30';
$.post('http://www.mywebsite.com/myPHPscript.php', {variable: variableToSend}, function(responseFromPhp){

    $('#displayResult').html(responsefromPhp);
});
Sign up to request clarification or add additional context in comments.

1 Comment

I understand what you mean now by using ajax twice. Thank you!
1

The data you want will be returned on this post ajax call. To retrieve it specify success function.

$.post( "test.php", { name: "John", time: "2pm" })
    .done(function( data ) {
        alert( "Data Loaded: " + data );
    });

and also use some validation and escaping before use post values in mysql: http://php.net/manual/en/mysqli.real-escape-string.php

Comments

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.