Im a beginner in AJAX & javascript, so please bear with me.
I want to pass a variable ( document.getElementById('txtSearch').value
) from my AJAX to a PHP so i tried to code something like this :
$("#btnSearch").click(function() {
var keyword = "";
alert(document.getElementById('txtSearch').value);
$.ajax({
url: BASE_URL + 'index.php/jwm/search', //This is the current doc
type: "POST",
dataType:'json', // add json datatype to get json
data: ({keyword: document.getElementById('txtSearch').value}),
error : function(jq, st, err) {
console.log(arguments);
alert(st + " : " + err);
},
success: function(data){
alert(data);
}
});
});
However, i got an error : parse error syntax error unexpected token <
and sometimes the error change a little bit to be like this : parse error syntax error unexpected token T
.
EDIT This is my PHP code :
function search() {
$keyword = $_POST['keyword'];
echo "TEST : $keyword";
$result = $this->jwm_m->getDataByKeyword('msmall', $keyword);
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header('Content-type: application/json', true);
echo json_encode($result);
}
This is what my console get :
arguments: null
caller: null
length: 0
name: ""
My goal is to passing document.getElementById('txtSearch').value
, please help me out.
Thanks for your help :D
A couple of things to note about your updated question, in the PHP code:
You mentioned that you get an error parse error syntax error unexpected token T
. This is probably because of the echo "TEST : $keyword";
in PHP, which causes the response to be invalid JSON.
You're setting the headers after echo "TEST : $keyword";
, this will throw a PHP warning similar to Cannot modify header information - headers already sent by...
So remove the echo "TEST : $keyword";
line and try sending the request again. This time, keep the network panel of your developer tools open and check the data being sent/received. If you're still having issues, update your question with the server response & request body. The more information you provide, the more likely it is that you'll get a good solution.
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.