I have the following jquery function which is supposed to post data to a php function which in the process it passes it to the external script for processing.
Below is my jquery function :
function order_confirmation(json) {
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>home/confirm_order_received/",
data: json,
contentType: 'application/json',
dataType: 'json',
success: function (data) {
console.log(data);
},
failure: function (errMsg) {
console.log(errMsg);
}
});
}
This function is supposed to pass the json data to my php function which is below here :
function confirm_order_received() {
$json = $this->input->post('json');
// Initialize curl
$curl = curl_init();
$externalscriptaddress = "http://197.237.132.178/api/order/order_upsert";
// Configure curl options
$opts = array(
CURLOPT_URL => $externalscriptaddress,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $json
);
// Set curl options
curl_setopt_array($curl, $opts);
// Get the results
$result = curl_exec($curl);
// Close resource
curl_close($curl);
echo $result;
}
I have a problem of how I am supposed to access the data from the php side, I have tried accessing it through the post : $json = $this->input->post('json'); and passed it to the CURLOPT_POSTFIELDS => $json but I get an error since nothing has been passed. Please advise how can i pass the json data to an external script?
For getting raw post data (in your case) use file_get_contents("php://input")
Instead of data: json, you should use data: "json:json",
Using just data: json, will post the data, but it will not be assigned to a key. To access the data ou need to assign it to a key. By using data: "json:json",, you can access it with $json = $this->input->post('json');
Related
I developed a contact form with pure PHP and HTML. I wanna insert the input values into the database with AJAX. Here is my Javascript/jQuery code:
var email = jQuery("#email").val();
var data = {
'email': email
}
jQuery.ajax({
type: "POST",
url: "http://mywebsitedomain.com/wp-content/themes/mytheme/contactform.php",
dataType: "json",
data: data,
success : function(data) {
// do something
}
});
And my contactform.php:
$date = date('Y-m-d H:i:s');
global $wpdb;
$wpdb->insert('myTableName', array(
'email' => $_POST["email"],
'date' => $date,
));
My code works well. My question is what is the correct way to do that? Because I think it's not a good idea to create a .php file inside the WordPress theme and use it just for inserting data into the database. I think it has security issues and users can see my script URL (http://mywebsitedomain.com/wp-content/themes/mytheme/contactform.php) that used in my javascript file for using ajax.
Do you have better ways to do that?
Create a function for inserting data and also enqueue script for ajax call and pass it in url. example like:
function mytheme_admin_scripts() {
wp_enqueue_script( 'ajax-script', get_stylesheet_directory_uri().'/admin_script.js');
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts','mytheme_admin_scripts' );
Enqueue your js file which you have wrote your ajax call and pass my_ajax_object.ajx_url in your ajax url.
jQuery.ajax({
type : "POST",
url : my_ajax_object.ajax_url,
data : data,
dataType: "json",
cache: false,
success : function(data) {
// do something
}
});
I cant find whats is wrong with my code. When printing the json file from the post_receiver.php, the json is printed accordingly.
The JSON printed from the post_receiver.php
<?php
session_start();
ob_start();
require_once('../../mysqlConnector/mysql_connect.php');
$result_array = array();
$query="SELECT COUNT(initID) AS count, urgency, crime, initID, TIMESTAMPDIFF( minute,dateanalyzed,NOW()) AS minuteDiff FROM initialanalysis WHERE commanderR='0' AND stationID='{$_SESSION['stationID']}';";
$result=mysqli_query($dbc,$query);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push($result_array, $row);
}
}
echo json_encode($result_array);
?>
Result from above:
[{"count":"10","urgency":"Low","crime":"Firearm","initID":"5","minuteDiff":"329"}]
my ajax code:
$.ajax({
method: 'POST',
url: "post_receiver.php",
data: {
'count': count,
'urgency': urgency
},...
the 'count' and 'urgency' variable is not defined, i am not that familiar with JSON format...
In your success callback, you get a data string, which contains the response. To parse it as JSON, use the json dataType setting:
$.ajax({
method: 'POST',
url: 'post_receiver.php',
dataType: 'json',
success: function (data) {
// 'data' contains the parsed JSON
console.log('Count:', data[0].count); // read the values from the JS object and log them to the console
console.log('Urgency:', data[0].urgency);
}
});
Afternoon guys/gals,
I'm relatively new to using AJAX to POST information to a JSON file and I am not sure what the .php file should look like to process it. I have very little experience with .php. Am I on the right track? I've looked a lot of examples but most of them only have pieces of the .php file to process it. I am trying to inject the "task" into the JSON file which I then use handlebars to read on another page.
function fnCreateTask() {
var url = "save.php";
var title = $("#TaskTitle").val();
var date = $("#TaskDate").val();
var desc = $("#TaskDescription").val();
var info = {
Title: title,
Date: date,
Description: desc
};
var body = JSON.stringify(info);
$.ajax({
type: "POST",
url: url,
contentType: 'application/json',
data: body,
dataType: 'json',
error: function (err) {console.log(err)},
success: function (data) {
alert('Task Created.');
location.reload();
}
});
}
<?php
$fp = fopen('careers.json', 'w');
fwrite($fp, $_POST = json_decode(file_get_contents('php://input'), true););
fclose($fp);
?>
$.ajax POST (or GET for that matter) data will be x-form encoded by default when sent to the server. You can do
on the client
//object for the data
var data = {
title: $("#TaskTitle").val(),
date: $("#TaskDate").val()
};
$.ajax({
type: "POST",
url: "save.php",
data: data,
error: function (err) {console.log(err)},
success: function (data) {
alert('Task Created.');
location.reload();
}
});
and on the server
// as a separate object to be safe
$dataobj['title'] = $_POST['title'];
$dataobj['date'] = $_POST['date'];
// write json_encode object to file
file_put_contents ( 'filename.json' , json_encode($dataobj));
To create a JSON in PHP :
<?php
$array = array(
"name" => "toto",
"lastname" => "lafraise",
"age" => 33
);
$fp = fopen('careers.json', 'w');
fwrite($fp, json_encode($array));
fclose($fp);
I am working on a chat system which refreshes automatically using AJAX. First I was using the jQuery $.post function, but since i wanted to return JSON data from my PHP script, i want to use the $.ajax function. My script worked well using the $.post function, but i can not return JSON. This is the relevant code:
Javascript:
$.ajax({
url: "pages/loadmessage.php",
type: "POST",
data: {"c": getUrlParameter("c"), "t": messagetime},
dataType: "json",
success: function(pData){
console.log(pData);
},
error: function(xhr, status, error) {
alert(error + status);
}
});
PHP Code:
<?php
require_once("../init.php");
header('Content-Type: application/json');
if (Input::exists() && Input::get("c") && Input::get("t")) {
$chat = new Chat($user->data()->ID, Input::get("c"));
$messages = $chat->getNewMessages(Input::get("t"), $user->data()->ID);
if ($messages) {
$result = array(
'topic' => $chat->getTopic(),
'messages' => array()
);
foreach($messages as $m) {
array_push($result['messages'], array('source' => 'mine', 'Text' => $m->Text));
}
echo json_encode("string!!!");
}
} else {
echo json_encode("string" . Input::get("c") . Input::get("t") . Input::exists());
}
?>
I already tried to set the contentType of the AJAX call to "application/json" and convert the data to JSON using JSON.stringify, but then no input data gets to the PHP script. The code works if just one parameter (data: {"c": getUrlParameter("c")}) is sent to the PHP script...
I already searched StackOverflow, but i could not find a solution...
Thanks
JSON example:
Index.html
<script type="text/javascript">
$.ajax({
url: "out.php",
type: "POST",
data: {"param1": "test 1", "param2": "test2"},
dataType: "json",
success: function(data){
alert("param1:"+data.param1+" | param2:"+data.param2);
},
error: function(xhr, status, error) {
alert(error + status);
}
});
</script>
out.php
<?php
if(isset($_POST["param1"])){ $param1 = $_POST["param1"];}
if(isset($_POST["param2"])){ $param2 = $_POST["param2"];}
$out = array("param1"=>$param1,"param2"=>$param2);
echo(json_encode($out));
?>
The Problem is, the json file is not showing. Im using Xampp as local Server.
php file:
$array = array(
array(
"title" => "Erster Eintrag",
"description" => "Description",
"link" => "http://",
"pubDate" => "02.07.2015"
),
array(
"title" => "Zweiter Eintrag",
"description" => "Description",
"link" => "http://",
"pubDate" => "02.07.2015"
)
);
echo json_encode($json);
html file:
$ajax({
url:'localhost/uebung/staticfeed.php',
type:'POST',
data:'data',
dataType: 'json',
success: function(result){
$('#feeds').html(result[0]);
}
})
JavaScript use $.ajax and then full URL.
$.ajax({
url:'http://localhost/uebung/staticfeed.php',
type:'POST',
data:'data',
dataType: 'json',
success: function(result){
$('#feeds').html(result[0]);
});
You also need to encode your array in your php file.
echo json_encode($array);
Use json_encode in PHP
Returns a string containing the JSON representation of value.
Use $array to json_encode instead of $json.
echo json_encode($array);
/// ^^^^^^^^^
Change $ajax to $.ajax, this will remove the error in your code, everything else works fine
You are missing JSON headers in your PHP answer, Jquery may interpret your response as plain text or HTML...
Also, you are echoing $json and your array is $array.
Try this for PHP:
header('Content-type: application/json');
$array = [["title" => "Erster Eintrag","description" => "Description","link" => "http://","pubDate" => "02.07.2015"],["title" => "Zweiter Eintrag","description" => "Description","link" => "http://","pubDate" => "02.07.2015"]];
echo json_encode($array);
And this on your HTML:
$.ajax({type: "POST", url: "localhost/uebung/staticfeed.php", data:data, dataType: "json", timeout: 25000, success: function (result) {
$('#feeds').html('First array:' + result.[0].title + '<br />Seccond array:' + result.[1].title );
}});
You need to select the value INSIDE the array inside [result]...