Home  >  Article  >  Backend Development  >  Why is My Javascript POST Not Working: How Do I Send a Javascript Array to PHP?

Why is My Javascript POST Not Working: How Do I Send a Javascript Array to PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 15:48:02724browse

Why is My Javascript POST Not Working: How Do I Send a Javascript Array to PHP?

Javascript POST not working: Sending Javascript Array to PHP

Despite numerous attempts, you've encountered a challenge in passing a JavaScript array to a PHP script via POST. Seeking assistance to resolve this issue, you present the following code:

JavaScript:

function sendToPHP() {
$.post("index.php", { "variable": toSearchArray });
}

PHP:

<?php 
    $myval = $_POST['variable'];
    print_r ($myval);
    ?>

Issue Resolution:

You may be facing an issue due to a misunderstanding of how AJAX (Asynchronous JavaScript and XML) operates. While jQuery simplifies AJAX usage, it requires a proper understanding of the process.

In your case, the sendToPHP() function triggers a POST request to the index.php page with the variable parameter set to the toSearchArray. However, it's crucial to define an AJAX success handler function to capture the server's response.

Example using index.php:

<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $('#btn').click(function(){
        var txt=$('#txt').val();
        if(txt == ''){
            alert("Enter some text");
        } else {
            $.post('catcher.php', {'text':txt}, function(data){
                $('#response').text(data.message);
            }, 'json');
        }
    });
});
</script>
</head>
<body>
<input type="text" id="txt">
<input type="button" id="btn">
<pre id="response" style="overflow:auto;width:800px;height:600px;margin:0 auto;border:1px solid black;">

Example using catcher.php:

<?php
if(!empty($_POST)){
    $output = array();
    $output['message'] = "Success!";
    echo json_encode($output);
}

This example demonstrates how to trigger an AJAX call, send data to a PHP script, and receive a response, allowing you to display the response in the designated #response element on the page. Remember, when sending an array, simply replace the textbox value retrieval with sending the array.

The above is the detailed content of Why is My Javascript POST Not Working: How Do I Send a Javascript Array to PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn