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/
Related
I'm working on a project coding PHP-AJAX-Jquery and JSON and need to send the information of a form that has three input fields to a php file that will store the info of the three fields in the database.
my problem is that I need(I have because of project spec) to use Jquery-AJAX and JSON and I think I'm passing in a malformed JSON string to the PHP file, this is the js that is supposed to handle the call:
$(document).ready(function(){
$('#ID_formulario').on('submit',function(e) {
e.preventDefault();
var nombre = $('input#ID_nombre');
var email = $('input#ID_email');
if(validaForm(nombre, email)){
var url = $(this).attr('action');
var data = $(this).serializeArray();
var type = $(this).attr('method');
alert(data);
$.ajax({
url:url,
data:data,
type:type,
cache: false,
contentType: "application/x-www-form-urlencoded",
dataType: 'json',
beforeSend: function () {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="imagen.gif" align="absmiddle"> <span class="loading">Realizando peticion...</span>');
},
error: function(){
alert("error peticiĆ³n ajax");
},
success: function(datos){
$('#result').empty().html(respuesta). fadeIn('slow').delay(5000).fadeOut();
$('#ID_formulario')[0].reset();
$('input#ID_nombre').focus();
$("#flash").hide();
//$("#display").after(html);
//$("#result").append(data);
}
});
}
});
});
my questions are: how to send the info of the three fields in a valid JSON format to the php file? is there any jquery function that helps? or is serializeArray() enough?
It's okay to use success: function(datos) or should I replace it to .done(function)) ?
thanks in advance.
You dont need to send anything as JSON to PHP. Just send it with type: POST and read it in PHP. Then return it as JSON to read in Javascript. You just read the $_POST in PHP. I believe you've mistaken your project specs and you need to RETURN data from PHP as JSON.
This is one of my projects:
$("document").ready(function(){
$(".js-ajax-php-json").submit(function(){
var data = {
"action": "product"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php",
data: data,
success: function(data) {
$(".the-return").html(
// Read returned JSON. Exammple
"<div class='data-row'><strong>TYPE</strong> " + data["title"]+ "</div>";
);
}
});
return false;
});
});
In PHP you take the POST and read data.
response.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 "product": sendValues();
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';
}
// Do everything with $_POST's here
function sendValues(){
$return = $_POST;
$return["title"] = 'Something';
$return["json"] = json_encode($return);
echo json_encode($return); // Return JSON formatted data to Javascript.
}
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.
I have a problem that puzzles me. I have an ajax function that sends a json object, and I see the JSON parsed in the F12 Chrome Headers, and I receive the success alert.
$(document).ready(function() {
var test = {'bob':'foo','paul':'dog'};
$.ajax({
url: "test.php",
type: 'POST',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(test),
success: function(data) {
alert("Bien: " + data);
},
failure: function(errMsg) {
alert("Mal: " + errMsg);
}
});
});
But in my PHP page I cannot see any POST, anything. I can see that my post is received but anything else:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo "post"; //Result 'post'
}
foreach( $_POST as $stuff ) {
echo $stuff; //Nothing at all
}
print_r(json_decode($_POST["data"], true)); // Undefined index: data
In the same code I use
$.post( "test.php", { data: { name: "John", time: "2pm" } } );
and works, then is something related with the code, but I cannot really see waht is it.
Thank you for your help!
try this instead
$results = json_decode(file_get_contents('php://input'));
echo $results->bob //Result foo
I have a js script that does an ajax request and posts the data to a php script, this script with then echo something back depending if it works or not.
here is the JS
$(document).ready(function(){
var post_data = [];
$('.trade_window').load('signals.php?action=init');
setInterval(function(){
post_data = [ {market_number:1, name:$('.trade_window .market_name_1').text().trim()},
{market_number:2, name:$('.trade_window .market_name_2').text().trim()}];
$.ajax({
url: 'signals.php',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data:{markets:post_data},
dataType: "json",
success: function(response){
console.log("Response was " + response);
},
failure: function(result){
console.log("FAILED");
console.log(result);
}
});
}, 6000);
});
here is the php:
if(isset($_POST["json"]))
{
$json = json_decode($_POST["json"]);
if(!empty($json))
{
echo "IT WORKED!!!!";
}
else
echo "NOT POSTED";
}
So basically, i thought the response in the `success: function(response)' method would be populated with either "IT WORKED!!!" or "NOT POSTED" depending on the if statement in the php. Now everything seem to work because the js script manages to go into the success statement but prints this to the console:
Response was null
I need to be able to get the return from the server in order to update the screen.
Any ideas what I'm doing wrong?
Try:
if(isset($_POST["markets"]))
{
$json = json_decode($_POST["markets"]);
if(!empty($json))
{
echo "IT WORKED!!!!";
}
else
echo "NOT POSTED";
}
use this in your php file
if(isset($_POST["markets"]))
{
}
instead of
if(isset($_POST["json"]))
{
.
.
.
.
}
Obiously the if(isset($_POST["json"])) statement is not invoked, so neither of both echos is executed.
The fact that the function specified in .ajax success is invoked, only tells you that the http connection to the url was successful, it does not indicate successful processing of the data.
You are using "success:" wrong.
Try this instead.
$.post("signals.php", { markets: post_data }).done(function(data) {
/* This will return either "IT WORKED!!!!" or "NOT POSTED" */
alert("The response is: " + data);
});
Also have a look at the jQuery documentation.
http://api.jquery.com/jQuery.post/
Look, You send data in market variable not in json. Please change on single.php code by this.
$json_data = array();
if(isset($_POST["markets"]))
{
// $json = json_decode($_POST["markets"]);
$json = ($_POST["markets"]);
if(!empty($json))
echo "IT WORKED!!!!";
else
echo "NOT POSTED";
}
And change on your ajax function
$(document).ready(function(){
var post_data = [];
$('.trade_window').load('signals.php?action=init');
setInterval(function(){
post_data = [ {market_number:1, name:$('.trade_window .market_name_1').text().trim()},
{market_number:2, name:$('.trade_window .market_name_2').text().trim()}];
$.ajax({
url: 'signals.php',
type: 'post',
// contentType: 'application/json; charset=utf-8',
data:{markets:post_data},
dataType: "json",
success: function(response){
console.log("Response was " + response);
},
failure: function(result){
console.log("FAILED");
console.log(result);
}
});
},6000);
});
You have to you change you $.ajax call with
//below post_data array require quotes for keys like 'market_number' and update with your required data
post_data = [ {'market_number':1, 'name':'name1'},
{'market_number':2, 'name':'name2'}];
//console.log(post_data);
$.ajax({
url: "yourfile.php",
type:'post',
async: true,
data:{'markets':post_data},
dataType:'json',
success: function(data){
console.log(data);
},
});
and you php file will be
<?php
if(isset($_POST['markets']))
{
echo "It worked!!!";
}
else
{
echo "It doesn't worked!!!";
}
//if you want to work with json then below will help you
//$data = json_encode($_POST['markets']);
//print_r($data);
?>
in your php file check the $_POST:
echo(json_encode($_POST));
which will tell if your data has been posted or not and the data structure in $_POST.
I have used the following code to covert the posted data to associative array:
$post_data = json_decode(json_encode($_POST), true);
I'm sending a ajax request to update database records, it test it using html form, its working fine, but when i tried to send ajax request its working, but the response I received is always null. where as on html form its show correct response. I'm using xampp on Windows OS. Kindly guide me in right direction.
<?php
header('Content-type: application/json');
$prov= $_POST['prov'];
$dsn = 'mysql:dbname=db;host=localhost';
$myPDO = new PDO($dsn, 'admin', '1234');
$selectSql = "SELECT abcd FROM xyz WHERE prov='".mysql_real_escape_string($prov)."'";
$selectResult = $myPDO->query($selectSql);
$row = $selectResult->fetch();
$incr=intval($row['votecount'])+1;
$updateSql = "UPDATE vote SET lmno='".$incr."' WHERE prov='".mysql_real_escape_string($prov)."'";
$updateResult = $myPDO->query($updateSql);
if($updateResult !== False)
{
echo json_encode("Done!");
}
else
{
echo json_encode("Try Again!");
}
?>
function increase(id)
{
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
success: function (response) {
},
complete: function (response) {
var obj = jQuery.parseJSON(response);
alert(obj);
}
});
};
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
dataType: 'json',
success: function (response) {
// you should recieve your responce data here
var obj = jQuery.parseJSON(response);
alert(obj);
},
complete: function (response) {
//complete() is called always when the request is complete, no matter the outcome so you should avoid to recieve data in this function
var obj = jQuery.parseJSON(response.responseText);
alert(obj);
}
});
complete and the success function get different data passed in. success gets only the data, complete the whole XMLHttpRequest
First off, in your ajax request, you'll want to set dataType to json to ensure jQuery understands it is receiving json.
Secondly, complete is not passed the data from the ajax request, only success is.
Here is a full working example I put together, which I know works:
test.php (call this page in your web browser)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// Define the javascript function
function increase(id) {
var post_data = {
'prov': id
}
$.ajax({
'type': 'POST',
'url': 'ajax.php',
'data': post_data,
'dataType': 'json',
'success': function (response, status, jQueryXmlHttpRequest) {
alert('success called for ID ' + id + ', here is the response:');
alert(response);
},
'complete': function(jQueryXmlHttpRequest, status) {
alert('complete called');
}
});
}
// Call the function
increase(1); // Simulate an id which exists
increase(2); // Simulate an id which doesn't exist
</script>
ajax.php
<?php
$id = $_REQUEST['prov'];
if($id == '1') {
$response = 'Done!';
} else {
$response = 'Try again!';
}
print json_encode($response);