简体   繁体   中英

Sending data to PHP using AJAX

I have searched my problem before posting this question, but failed to find a solution. I need to send a json string to php file but unable to do so, can some one please help with my problems below: I'm new to php and jquery and is struggling, Need your cooperation please.

I have a function that captures data on the text file:

function updateVal() {
var node_list = document.getElementsByTagName('input');
var c = 0;
var fieldName = [];
var fieldText = []
var ID = [];
for (var i = 0; i < node_list.length; i++) {
    var node = node_list[i];
    if (node.getAttribute('type') == 'text') {
        fieldName[c] = node.name;
        fieldText[c] = node.value;
        ID[c] = node.id;
        c++;
    }
}
var postData = {
    fieldName: fieldName,
    fieldText: fieldText,
    ID: ID
};
 var dataString = JSON.stringify(postData);


console.log(JSON.stringify(postData));
$.ajax({
        type: "POST",
        dataType: "json",
        url: "update.php",
        data: {myData:postData}
        })

//return JSON.stringify(postData);
}

My update.php is like this:

<?php
$json = $_POST['json'];
$result = json_decode($json);

echo $result;
echo $_POST['myData']);?>

On loading this: I'm getting the following error:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Moreover, I'm not sure if the data being sent to php or not. Can experts pls validate.

The 500 (internal server error) means something went wrong on the server's side. So check the apache error log for more details

you may find apache log here /var/log/apache2/

On client side (javascript code):

data: JSON.stringify(postData)

On server side (PHP code):

json_decode($_POST["data"])

u commented the closing braces of the function with the return statement. change this :

//return JSON.stringify(postData);}

to:

//return JSON.stringify(postData);
}

Also :

data: JSON.stringify(postData),

IN update.php

$json = $_POST['myData'];
$result = json_decode($myData);

var_dump($result);

来自@Tushar的评论帮助我解决了这个问题

contentType: 'application/x-www-form-urlencoded; charset=UTF-8', data: {json: JSON.stringify(postData)

发送Ajax请求到php页面获取数据

$.ajax({ method: "POST", // it may be Get url: "some.php", //page where you sent request data: { name: "John", location: "Boston" } //attibutes you want to take on that page }) .done(function( msg ) { // sucessfull reponse alert( "Data Saved: " + msg ); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM