How to catch data sent by Ajax using PHP - php

Would like to ask for a help. I'm having an issue about getting the right data that I wanted. Maybe there's something lack in my code. I always get null.
I didn't received any error on the console tab.
Here's my ajax
$(document).ready(function() {
$(".fsubmit").click(function() {
var emailval = $("#email").val().trim();
$.ajax({
url: '/test.php',
type: 'POST',
dataType: 'json',
data: 'email='+emailval,
success: function(data) {
console.log(data);
return false;
}
});
});
});
Maybe you could help me fix the PHP. Still learning some stuff. Kindly put some details for lesson please.
Here's my PHP code
<?php
$date = new DateTime();
$datelog = $date->format('d.m.Y h:i:s');
$data = $_POST['data'];
$message = '[' . $datelog . '] - email: ' . json_encode($data);
echo($message);
?>
I appreciate your answer!

Not allowed to comment. Here's a little edit to Mohammad's answer. isset() returns true for blank form fields. Use empty() instead.
this runs in my system ..
ajax call
$(document).ready(function(e) {
$(".fsubmit").click(function() {
e.preventDefault();
console.log("whooowww");
var emailval = $("#email").val().trim();
$.ajax({
url: '/arrayfilter.php',
type: 'POST',
dataType: 'json',
data: 'email='+emailval,
success: function(data) {
console.log(data);
return false;
}
});
});
});
html form
<form>
<input type="text" name="user-input" id="email"/>
<button type="submit">Send</button>
</form>
php
if($_POST){
if(!empty($_POST['email']))
echo "$_POST[email]";
}
}

try this:
$(document).ready(function() {
$(".fsubmit").click(function() {
var emailval = $("#email").val().trim();
$.ajax({
url: '/test.php',
type: 'POST',
dataType: 'json',
data: {email:emailval},
success: function(data) {
console.log(data);
return false;
}
});
});
});
then in php:
<?php
$date = new DateTime();
$datelog = $date->format('d.m.Y h:i:s');
$data = isset($_POST['email'])?$_POST['email']:'';
$message = '[' . $datelog . '] - email: ' . json_encode($data);
echo($message);
?>
You should always check for the posted elements if its isset or not.

The JS
I can see - at least - one major flaw in your JS code. You are passing data: 'email='+emailval to the request. This would be fine (well - possibly not, since you are not URL-encoding your message) for a GET, but with the post I'd doubt, that jQuery can make some decent JSON out of email=Some arbitrary text. At least it will make your JS vulnerable to injections. There are answers on how to send JSON to a webservice with jQuery, please see here.
The PHP
$_POST['data'] (if this is correct) will contain a string. But according to the PHP documentation
json_encode — Returns the JSON representation of a value
I don't think that this is what you want to do. You have a string, and you'll probably want to get an object from your JSON string (actually at the moment, I doubt that it's really a JSON string what you are passing). You can achieve this with json_decode, which
json_decode — Decodes a JSON string
I'd suggest the following PHP code, which decodes the JSON into an array and then outputs the value of email
$data = json_decode($_POST['data'], true);
$message = '[' . $datelog . '] - email: ' . $data["email"];
For this to work, $_POST['data'] will have to look like this
{'email': 'Your message'}
or the like.

Related

Creating a json file by PHP

I want to update the json file by overwriting the old one. I can export the data to a json string by using some jquery. And the data is stored in the variable json_update . But I don't know how to send the data to php.
$(function () {
$('#switcher').click(function () {
var json_update = JSON.stringify($('#table-hover').bootstrapTable('getData'));
$.ajax({
type: "POST",
url: "adding2.php",
data: json_update,
contentType: "application/json; charset=utf-8"
dataType: "json",
success: function (data) {
alert("success");
}
});
});
});
And here is the adding2.php . Thanks for helping me.
<?php
$data = $_POST['json_update'];
$fileHandler = fopen('work2.json', 'w+');
fwrite('work2.json',$data);
fclose($fileHandler);
?>
Give the data a parameter name before sending it:
var json_update = { json_update: JSON.stringify($('#table-hover').bootstrapTable('getData')) };
This will make it accessible in $_POST['json_update']
The data you send from the client side (the value of json_update) is stored in $_POST, so just change $data = $_POST['json_update']; to $data = $_POST;.

fetch data from JSON in PHP

I have a JSON code that send a form to on PHP file and I want to use data in PHP
the code is:
// add button .click
$('a.add').click(function(){
$('#loader').show();
var url = "/yadavari/test.php?";
var json_text = JSON.stringify($("form[name='add']").serialize(), null, 2);
var datas = JSON.parse(json_text);
ajx = $.ajax({
url: url,
type: 'post',
data: datas,
dataType: 'json',
success: function(r) {
$('#loader').hide();
if(r.r != 0){
alert("ok");
jsmsalert($('#alert_add'),'success',r.m);
apendtable(r.r);
$("tr").removeClass("odd");
$("tr.viewrow:odd").addClass("odd");
$("tr.editrow:odd").addClass("odd");
$('td[colspan="7"]').remove();
}
else{
jsmsalert($('#alert_add'),'error',r.m,0);
}
},
error: function(request, status, err) {
$('#loader').hide();
jsmsalert($('#alert_add'),'error','error msg');
alert( "ERROR: " + err + " - " );
}
Now I want to fetch data from this JSON code in my PHP page.
I searched but every body just said that $string='{"name":"John Adams"}'; and so.
But I dont know that how can I have this $string in my PHP.
You should have something like:
<?php
echo $_POST["INPUTNAME"];
?>
Care about this, it suffers from security injection.
You need to call the php json_decode function on the returned string. This will convert it into an associative array:
$json2array = json_decode($json_text);
echo $json2array['name']; // "John Adams"

PHP: Whois via AJAX

I am extremely bad at AJAX (actually, I just started to learn it).
So, I write whois service on PHP and I want to make it to output the result via AJAX-request.
All I have at the moment is:
my PHP code:
$domain = $_POST['domain'];
$whois = new Whois();
header("content-type:application/json");
$res = $whois->getWhois($domain); // Calls the Whois-query function;
echo json_encode($res);
my JS code:
$('#submit').on('click', function() {
e.preventDefault();
var domain = $('#value').val();
});
$.ajax({
url: 'ajax/whois.php',
type: "post",
data: {'domain': domain, 'action': 'whois'},
dataType: "json",
success: function(json) {
$('#whoisResult').html('<h2>Whois Query result for ' + domain + '</h2>');
$('#whoisContent').html(json.html);
},
error: function(xhr, status) {
$('#whoisResult').html('<h2>Sorry, an error occured. Try again later, please!</h2>')
}
});
As HTML I have an input: <input type="text" id="value"> and the submit button.
I searched for the script examples and tried to make something similar, but it does not work at all...
P.S. Guess you won't hit this question a negative rating :)
P.P.S: As requested, this is my response from PHP:
{"domain":"exp.cm","whois":"[Domain]\nDomain: exp.cm\nStatus: active\nChanged: 2014-02-25T12:22:00.957819+02:00\n\n[Holder]\nType: Legal person\nName: Name, Surname\nEmail: email#example.com\nPhone: Phone here\nAddress: Address goes here\nSome other info\n\nUpdated: 2014-03-18T18:12:35.717462+00:00\n"}
In this case you don't need the JSON datatype, just return html.
Additionally, you'll want the ajax request to be inside the click event. In your click event, you also forgot to pass the e parameter.
$domain = $_POST['domain'];
$whois = new Whois();
header("content-type:text/html");
$res = $whois->getWhois($domain); // Calls the Whois-query function;
echo $res;
js:
$('#submit').on('click', function(e) {
e.preventDefault();
var domain = $('#value').val();
$.ajax({
url: 'ajax/whois.php',
type: "post",
data: {'domain': domain, 'action': 'whois'},
//dataType: "json",
success: function(html) {
$('#whoisResult').html('<h2>Whois Query result for ' + domain + '</h2>');
$('#whoisContent').html(html);
},
error: function(xhr, status) {
$('#whoisResult').html('<h2>Sorry, an error occured. Try again later, please!</h2>')
}
});
});

jquery post not passing all parameters

i have this jquery code:
var idd = $(this).attr("id");
var page = $(this).attr("page");
var data = "lastmsg="+idd+"&page="+page;
$.ajax({
type: "POST",
url: "ajax_more.php",
data: data,
success: function(html){
$("ol#live_updates").append(html);
$("#more"+idd).remove(); // removing old more button
}
});
and this is the "ajax_more.php" code:
if(isset($_POST['lastmsg']))
{
$lastmsg = mysql_real_escape_string($_POST['lastmsg']);
$page = mysql_real_escape_string($_POST['page']);
echo $lastmsg . " " . $page;
}
Only ($lastmsg) passed, but any other parameter like ($page) is not passed. Where is the problem ??
i tried ($.post) and ($.ajax) with "POST" type, both not working...
data should be an object.
var data = {lastmsg: idd, page: page};
You need to properly encode all of your ajaxed parameters using encodeURI.
See my answer here for more information. Also, use your browser's console to debug.

POST a JSON object from Jquery to PHP and decoding it (cross domain)

I have code working to pass JSON objects from Jquery to PHP page.
The problem is with sending Cross-domain requests, If i try
dataType:'json'
in jquery, it gives me a xhttp error (the security) error which I understand.
I also understood after reading this post that JSONP only works for GET methods
This is how I am creating and using my object:
function order(id, name) {
return {
id: id,
name: name
}
}
var orders= [];
orders.push(order("123", "Lamb Kebab"), product("234", "Chicken"));
var jsonOrders = $.toJSON(orders);
$.post(
"process.php",
{orders: jsonOrders },
function(data){
$("#result").html(data);
}
);
What is the solution for me to pass a JSON object cross domain?
if that is not possible, what is an alternate solution ?
Please advise
Thanks
Edit:
Jquery code
function product(code, type) {
return {
code: code,
type: type
}
}
var products = [];
products.push(product("333", "Product one"), product("444", "Second product"));
var jsonProducts = $.toJSON(products);
$.ajax({
type: "GET",
url: "http://page.tld/foo.php",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
data:JSON.stringify({products: jsonProducts}),
error: function (msg) {
//alert("error");
console.log("Error here" +msg);
},
success: function (msg) {
console.log("Success"+msg);
}
});
**
The error on PHP end is: Invalid argument supplied for foreach() in
....
**
PHP Code (simplified version)
<?php header("Content-type: application/json; charset=utf-8");
require_once('json.php');
if (isset($_GET['products'])) {
$products = json_decode($_GET["products"],"true");
foreach ($products as $product){
echo $_GET['callback'] . '(' .(json_encode($product["type"])). ')';
}
}
else
{
echo $_GET['callback'] . '(' .(json_encode("not found")). ')';
}
?>
it is going into the block where it is able to find $_GET['products'], is it a parsing error on my part? i am sure it is an obvious mistake but im not able to spot it.
real sorry about that
I used the GET parameter and decoded JSON on the PHP end.

Categories