I'm trying to create a simple AJAX call for testing, but have encountered a problem. I have nested in my AJAX call a success function which should pop an alert message but it doesn't. Checking firebug, the POST is successful and responds with "A20" (without quotations). Is there something wrong in my code?
index.php (view)
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="init.js"></script>
<script src="jquery-1.10.2.min.js"></script>
</head>
<body>
<button id="your_button">Push me</button>
</body>
</html>
init.js
$(function() {
$('#your_button').bind("click", function() {
var json_data = {"category": "A", "size": "20"};
$.ajax({
url: "posted.php",
dataType: "json",
type: "POST",
cache: false,
data: {"data": json_data},
success: function (data) {
if (!data.error) {
alert('k');
} else {
alert('error!');
}
}
});
});
});
posted.php
$category = $_POST['data']['category'];
$tsize = $_POST['data']['size'];
echo ($category);
echo ($size);
Try this -
$(function() {
$('#your_button').bind("click", function() {
var json_data = {"category": "A", "size": "20"};
$.ajax({
url: "posted.php",
dataType: "json",
type: "POST",
cache: false,
data: json_data,
success: function (data) {
if (!data.error) {
alert('k');
} else {
alert('error!');
}
}
});
});
});
Posted.php
$category = $_POST['category'];
$tsize = $_POST['size'];
//echo ($category);
//echo ($tsize);
echo json_encode($_POST);
Your want json data but you were not echoing json data
this is not right:
data: {"data": json_data}
do like this:
data: {data: json_data}
You need to set proper headers in your PHP and send a valid json response from PHP file. Add these lines to your PHP
header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');
and echo back some valid json from it like echo '{"auth":"true","error":"false"}';
First you are using two jquery libraries, remove any one of them.
Second replace data: {"data": json_data}, with data: json_data,.
Third on posted.php use $category = $_POST['category'] and $tsize = $_POST['size'];.
Hope it will help you.
Related
I am having trouble with my JSON payload. The success function does not fire.
Thanks in advance for any help that can be provided.
JLS
I get the value in the console so I know the query works okay but it is not in a key/value pair it just echos "VALUE" and does not triggers success.
//JS file ***UPDATED***
$(document).ready(function(){
// code to get all records from table via select box
$("#school").change(function() {
var id = $(this).find(":selected").val();
var dataString = 'school='+ id;
$.ajax({
url: 'cif_submit.php',
dataType: "json",
data: dataString,
cache: false,
success: function(data) {
if(data) {
alert(data);
}
}
});
})
});
//Here is the php ***UPDATED***
if($_REQUEST['school']) {
$stmt = $conn->prepare("SELECT streetname FROM schoolinfo WHERE fullschoolname = :schoolname");
$stmt->execute (array(':schoolname' =>$_REQUEST['school']));
while($mydata = $stmt->fetch()) {
echo json_encode($mydata);
} }
}
The JSON RESPONSE is:
{"streetname":"Colbeck Road, PO Bag 7200","0":"Colbeck Road, PO Bag 7200"}
I think changing the schooldata to data will fix the issue.
Don't forget that change() event gets called when you unfocus the input.
https://api.jquery.com/change/
Tried with this code and worked perfectly.
JS
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<body>
<input id="school" type="text">
<script>
$(document).ready(function(){
// code to get all records from table via select box
$("#school").change(function() {
var id = $(this).find(":selected").val();
var dataString = 'school='+ id;
$.ajax({
url: 'a.php',
dataType: "json",
data: dataString,
cache: false,
success: function(schooldata) {
if(schooldata) {
alert('success');
//$("#streetname").text(schooldata.streetname); TRIED THIS NO JOY
//$("#streetname").hide(); TRIED THIS NO JOY
}
}
});
})
});
</script>
</body>
</html>
PHP
if($_REQUEST['school']) {
$datas = array();
$datas[] = array('streetname' => 'test');
foreach ($datas as $data) {
$data = $data['streetname'];
//$streetname = trim(json_encode($data), '"');
//echo json_encode($data);
echo json_encode($data, true);
}
}
I have a form that collect user info. I encode those info into JSON and send to php to be sent to mysql db via AJAX. Below is the script I placed before </body>.
The problem now is, the result is not being alerted as it supposed to be. SO I believe ajax request was not made properly? Can anyone help on this please?Thanks.
<script>
$(document).ready(function() {
$("#submit").click(function() {
var param2 = <?php echo $param = json_encode($_POST); ?>;
if (param2 && typeof param2 !== 'undefined')
{
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: param2,
cache: false,
success: function(result) {
alert(result);
}
});
}
});
});
</script>
ajaxsubmit.php
<?php
$phpArray = json_decode($param2);
print_r($phpArray);
?>
You'll need to add quotes surrounding your JSON string.
var param2 = '<?php echo $param = json_encode($_POST); ?>';
As far as I am able to understand, you are doing it all wrong.
Suppose you have a form which id is "someForm"
Then
$(document).ready(function () {
$("#submit").click(function () {
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: $('#someForm').serialize(),
cache: false,
success: function (result) {
alert(result);
}
});
}
});
});
In PHP, you will have something like this
$str = "first=myName&arr[]=foo+bar&arr[]=baz";
to decode
parse_str($str, $output);
echo $output['first']; // myName
For JSON Output
echo json_encode($output);
If you are returning JSON as a ajax response then firstly you have define the data type of the response in AJAX.
try it.
<script>
$(document).ready(function(){
$("#submit").click(function(){
var param2 = <?php echo $param = json_encode($_POST); ?>
if( param2 && typeof param2 !== 'undefined' )
{
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
dataType: "json",
success: function(result){
alert(result);
}
});}
});
});
</script>
It's just really simple!
$(document).ready(function () {
var jsonData = {
"data" : {"name" : "Randika",
"age" : 26,
"gender" : "male"
}
};
$("#getButton").on('click',function(){
console.log("Retrieve JSON");
$.ajax({
url : "http://your/API/Endpoint/URL",
type: "POST",
datatype: 'json',
data: jsonData,
success: function(data) {
console.log(data); // any response returned from the server.
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" value="POST JSON" id="getButton">
For your further readings and reference please follow the links bellow:
Link 1 - jQuery official doc
Link 2 - Various types of POSTs and AJAX uses.
In my example, code snippet PHP server side should be something like as follows:
<?php
$data = $_POST["data"];
echo json_encode($data); // To print JSON Data in PHP, sent from client side we need to **json_encode()** it.
// When we are going to use the JSON sent from client side as PHP Variables (arrays and integers, and strings) we need to **json_decode()** it
if($data != null) {
$data = json_decode($data);
$name = $data["name"];
$age = $data["age"];
$gender = $data["gender"];
// here you can use the JSON Data sent from the client side, name, age and gender.
}
?>
Again a code snippet more related to your question.
// May be your following line is what doing the wrong thing
var param2 = <?php echo $param = json_encode($_POST); ?>
// so let's see if param2 have the reall json encoded data which you expected by printing it into the console and also as a comment via PHP.
console.log("param2 "+param2);
<?php echo "// ".$param; ?>
After some research on the google , I found the answer which alerts the result in JSON!
Thanks for everyone for your time and effort!
<script>
$("document").ready(function(){
$(".form").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$(".the-return").html(
"<br />JSON: " + data["json"]
);
alert("Form submitted successfully.\nReturned json: " + data["json"]);
}
});
return false;
});
});
</script>
response.php
<?php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "test": test_function(); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test_function(){
$return = $_POST;
echo json_encode($return);
}
?>
Here's the reference link : http://labs.jonsuh.com/jquery-ajax-php-json/
I believe I have the right syntax but am missing something important. Been searching on here for a while but can't figure out why the POST variable is not being detected. Basically my .ajax is firing because my test statement has been changing due to the value but some reason can't receive variable via $_POST (i.e. my echo in php echo that it is not firing) Also the native file and php that I am sending it to are the same file blankFormTemplate.php but don't think that should be an issue.
$(document).ready(function()
{
var $selectedContexts = [];
$('.allContextField').change(function(){
//alert($(this).val());
hideField = $(this).val();
$('#'+hideField).remove();
$.ajax
({
type: "POST",
url: "blankFormTemplate.php",
data: addedContext=hideField,
cache: false,
success: function(addedContext)
{
$('#test').html($('#test').html()+hideField);
}
});
});
});
in my PHP blankFormTemplate.php:
<?php
if(isset($_POST['addedContext']))
{
echo 'hello';
}
else
{
echo 'why';
}
?>
Any help would be greatly appreciated.
Thanks,
Your javascript
$(document).ready(function()
{
$('.allContextField').change(function(){
hideField = $(this).val();
$('#'+hideField).remove();
});
if (hideField.trim()) {
$.ajax
({
type: "POST",
url: "blankFormTemplate.php",
data: (addedContext:hideField},
cache: false,
success: function(msg)
{
$('#test').html(msg);
}
});
}
});
Your PHP
<?php
if(isset($_POST['addedContext']))
{
echo 'hello';
}
else
{
echo 'why';
}
?>
I have a php function return a string value which will put into html file.
function getDirectionInfo($routeNumber) {
//some code here
$dirinfo = "<p> some text </p>";
return $dirinfo;
}
if (isset($_POST['getDirectionInfo'])) {
getDirectionInfo($_POST['getDirectionInfo']);
}
So in jQuery, I have a following function
$(".onebtn").click(function(){
$("#directioninfo").empty();
var routeNumber = $(this).text();
$.ajax({
url: "./systemView_Function.php",
type: "POST",
data: {"getDirectionInfo": routeNumber},
success: function(data) {
console.log("HIHIHIHI");
$("#directioninfo").append(data);
}
});
})
Now console.log prints the "HIHIHIHIHI", but jQuery does not append the data to html. Anyone know how to get the return value of php function when calling from jQuery?
Instead of return use:
echo json_encode($dirinfo);
die;
It's also good idea to add dataType field to your $.ajax() function params set to json, to make sure, that data in your success function will be properly parsed.
You just need to send the response back using echo
Use var routeNumber = $(this).val(); to get the button value
PHP:
<?php
function getDirectionInfo($routeNumber) {
//some code here
$dirinfo = "<p> routeNumber". $routeNumber." </p>";
return $dirinfo;
}
if (isset($_POST['getDirectionInfo'])) {
echo getDirectionInfo($_POST['getDirectionInfo']);
}else{
echo "not set";
}
AJAX & HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$(".onebtn").click(function(){
$("#directioninfo").empty();
var routeNumber = $(this).val();
console.log("routeNumber = " + routeNumber);
$.ajax({
url: "systemView_Function.php",
type: "POST",
data: {"getDirectionInfo": routeNumber},
success: function(data) {
console.log("data = " + data);
$("#directioninfo").append(data);
}
});
})
});
</script>
</head>
<body>
<div id="directioninfo"></div>
<input type="button" value="12346" class="onebtn" />
</body>
</html>
Thank you for everyone. I have just found that I made a very stupid mistake in jQuery. I should use var routeNumber = parseInt($(this).text()); instead of var routeNumber = $(this).text(); So the following code work to get the return value of php function when calling from jQuery.
in php
function getDirectionInfo($routeNumber) {
//some code here
$dirinfo = "<p> some text </p>";
echo json_encode($dirinfo);
}
if (isset($_POST['getDirectionInfo'])) {
getDirectionInfo($_POST['getDirectionInfo']);
}
in jQuery
$(".onebtn").click(function(){
$("#directioninfo").empty();
var routeNumber = parseInt($(this).text());
$.ajax({
url: "./systemView_Function.php",
type: "POST",
data: {"getDirectionInfo": routeNumber},
dataType: "JSON",
success: function(data) {
$("#directioninfo").append(data);
}
});
})
I am developing one website where i insert data through ajax in Json format to php page then after decoding it send to mysql database,but if my string contains < > || & ' " characters then my web page gives php error.so how should i proceed further. It doesn't allow for inserting some special characters ..
var obj = {"comment": commentText, "postID": postID};
var commentData = 'commentData=' + JSON.stringify(obj);
$.ajax({
type: "POST",
url: addNewCommentsUrl,
datatype: 'json',
data: commentData,
cache: false,
beforeSend: function() {
// $(document.body).off('click','.postComment');
},
success: function(result) {
commentBox.val("");
commentHolder.append(result);
// jQuery("#all-posts").masonry('reloadItems');
jQuery('#all-posts').masonry('layout');
var count = parseInt(parent.find("#commentContainer").text());
parent.find("#commentContainer").html(++count);
// $(document.body).on('click','.postComment');
}
});// end of ajax
at php side
$recievedData = $_POST['commentData'];
$recieveddatajson = json_decode($recievedData);
$lastCommentID = $recieveddatajson->{'commentID'};
$parentPostID = $recieveddatajson->{'postID'};
Okay, I see what you are doing. You don't need to do that. Here's a cut down version of your problem, showing you how to achieve ajax post:
test.php
<?php
// Handle Post
if (count($_POST))
{
echo "You posted\r\n";
print_r($_POST);
exit();
}
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({
type: "POST",
url: "test.php",
data: { "comment": "hello world", "postID": 1234 },
// data: { "comment": commentText, "postID": postID },
success: function(result) {
alert("Server Said:\r\n" + result);
}
});
});
</script>
Outputs:
So when the request occurs, data fields and their values are available in php like this:
$comment = isset($_POST['comment']) ? $_POST['comment'] : '';
$postID = isset($_POST['postID']) ? $_POST['postID'] : '';
Hope this helps.