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]...
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 found this and its very helpful...
Demo: jQuery Ajax Call to PHP Script with JSON Return
But i have some problem with to use it....
I need to understand how to use it correctly...
I dont understand why my array cannot be transform in a json....
These code are in response.php :
$champs = ["user" => "", "combinaison" => 0, "valeurSmall" => "", "valeurBig" => "", "aucune_valeur" => false, "trop_valeur" => false, "color_red" => 0, "color_green" => 0, "color_blue" => 0];
$return["json"] = json_encode($champs, JSON_FORCE_OBJECT);
echo json_encode($return);
And in my index.html the part javascript :
$.ajax({
type: "POST",
dataType: "json",
url: "changerMise/changer.php",
data: data,
success: function(dataReturn) {
alert("Form submitted successfully.\nReturned json: " + dataReturn["json"] );
}
});
The alert dont come back with the thing i need to use after....
The result gave :
Form submitted successfully.
Returned json: {"aucune_valeur": true}
any ideas ?!??!
Thx guys
Are you has give header json for response output on top of your php file, like below ?
<?php header("Content-type: application/json; charset=utf-8"); ?>
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));
?>
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');
Am using WordPress ajax to load the sub-categories dynamically.
Here's my code
Php code
function techento_getsubcat() {
$category_name = $_POST['catname'];
$cat_id = $_POST['catid'];
return wp_dropdown_categories( 'show_option_none=Choose a Sub Category&tab_index=10&taxonomy=category&hide_empty=0&child_of=' . $cat_id . '' );
}
add_action('wp_ajax_techento_getsubcat', 'techento_getsubcat');
add_action('wp_ajax_nopriv_techento_getsubcat', 'techento_getsubcat');
Jquery
jQuery(document).ready(function(){
$('#cat').change(function(e){
alert("changed");
$.ajax({
type: 'POST',
dataType: 'json',
url: pcAjax.ajaxurl ,
data: {
'action': 'techento_getsubcat', //calls wp_ajax_nopriv_ajaxlogin
'catname': $('#cat option:selected').text(),
'catid': $('#cat option:selected').val() },
success : function(response){
alert(response);
console.log(response);
$("#subcats").html(response);
}
});
e.preventDefault();
});
});
The problem with the above code is that php returns the raw html irrespective of the thing asked to return
even if set it to
return true;
it then returns the raw html of subcategories generated plus '0'
You're missing the $ shortcode in
jQuery(document).ready(function($){
The Ajax callback is better handled by wp_send_json_success(), so we don't have to worry with return or echo, exit or die. For that, set echo to false in the dropdown arguments:
function techento_getsubcat() {
$cat_id = intval( $_POST['catid'] );
$args = array(
'hide_empty' => 0,
'echo' => 0,
'child_of' => $cat_id,
'taxonomy' => 'category'
);
$data = wp_dropdown_categories( $args );
wp_send_json_success( $data );
}
On Ajax success, use response.data:
success : function(response){
console.log(response.data);
}