i get the json data from the php to ajax how can i separate the value of the console data just like that
i have to set in my id only the agent name not the hole "name" : "Testing"
This is my console value
[{"agent_module_id":"1","agent_module_number":"101","name":"Testing","description":";;;","agent_mobile":"0123456789","email":"d#gmial.com","category":"","unit_price":null,"cost_price":null,"deleted":"0"}]
This is My PHP Code
$this->load->model("member");
$agent_value = $_POST['agent_value'];
$data["results"] = $this->member->get_agent_data($agent_value);
echo json_encode($data["results"]);
This is my JavaScript Code
function agentForm()
{
var agent_id = document.getElementById("agent_code").value;
if(agent_id !='')
{
document.getElementById("agent_operation_form").style.display ="block";
$.ajax({
url: '<?php echo site_url("members/get_agent_data");?>',
data: { 'agent_value': agent_id},
type: "post",
/* success: function(data){
// document.write(data); //just do not use document.write
var fd_values = data.split(/,/);
document.getElementById("agent_name").value=fd_values[2]; // unique _id
document.getElementById("agent_mobile_number").value=fd_values[1];
console.log(data);*/
success: function(data){
// document.write(data); //just do not use document.write
var fd_values = $.parseJSON(data);
document.getElementById("agent_name").value = fd_values[0].name; // unique _id
document.getElementById("agent_mobile_number").value = fd_values[0].agent_module_number;
console.log(fd_values);
}
}
});
}else
{
document.getElementById("agent_operation_form").style.display ="none";
}
}
Thanx in advance
Try as (Not Tested). You can parse your JSON data using $.parseJSON
success: function(data){
// document.write(data); //just do not use document.write
var fd_values = $.parseJSON(data);
document.getElementById("agent_name").value = fd_values[0].name; // unique _id
document.getElementById("agent_mobile_number").value = fd_values[0].agent_module_number;
console.log(fd_values);
}
Related
I would like to send my variable "var targetId" to my php file.
I try to make ajax request but nothing happens.
My js file :
$( ".project_item" ).click(function(e){
var targ = e.target;
var targetId = targ.dataset.id;
console.log(targetId);
$('.popUp').fadeIn("200");
$('header, main, footer').addClass('blur');
$.ajax({
url: 'function.php',
type: "POST",
data: {idVoulu: targetId},
success: function(data){
alert(data);
console.log(data);
}
});
});`
And my php file to get the data
$idProject = (isset($_POST['idVoulu'])) ? $_POST['idVoulu'] : 0;
if($idProject==0) { echo ' ID not found';}
Can you tell me what's going wrong?
Well I can't Find a problem on your code but you can try this may be this will help you
var mydata = "idVoulu='+targetId+'"; // make a string
$.ajax({
url: 'function.php',
type: "POST",
data: mydata,
success: function(data){
alert(data);
console.log(data);
}
});
So, i made this and it works:
My js:
$( ".project_item" ).click(function(e) {
var targ = e.target;
var targetId = targ.dataset.id;
$('.popUp').fadeIn("200");
$('header, main, footer').addClass('blur');
$.post('../function.php', { id: targetId }, function(response) {
console.log("reponse : ", response)
});
My php :
if (isset($_POST['id'])) {
$newID = $_POST['id'];
$response = 'Format a response here' . $newID;
return print_r($response);
}
I am trying to send values to other page Using Ajax
But i am unable to receive those values , i don't know where i am wrong
here is my code
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var dataString1 = "fval="+fval;
alert(fval);
var sval = document.getElementById('country').value;
var dataString2 = "sval="+sval;
alert(sval);
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: "{'data1':'" + dataString1+ "', 'data2':'" + dataString2+ "'}",
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
in alert i am getting those value but in page 'getmoreinfo.php' i am not receiving any values
here is my 'getmoreinfo.php' page code
if ($_POST) {
$country = $_POST['fval'];
$country1 = $_POST['sval'];
echo $country1;
echo "<br>";
echo $country;
}
Please let me know where i am wrong .! sorry for bad English
You are passing the parameters with different names than you are attempting to read them with.
Your data: parameter could be done much more simply as below
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var sval = document.getElementById('country').value;
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: {fval: fval, sval: sval},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
Or cut out the intermediary variables as well and use the jquery method of getting data from an element with an id like this.
<script type="text/javascript">
function get_more_info() { // Call to ajax function
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: { fval: $("#get_usecompny").val(),
sval: $("#country").val()
},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
No need to create 'dataString' variables. You can present data as an object:
$.ajax({
...
data: {
'fval': fval,
'sval': sval
},
...
});
In your PHP, you can then access the data like this:
$country = $_POST['fval'];
$country1 = $_POST['sval'];
The property "data" from JQuery ajax object need to be a simple object data. JQuery will automatically parse object as parameters on request:
$.ajax({
type: "POST",
url: "getmoreinfo.php",
data: {
fval: document.getElementById('get_usecompny').value,
sval: document.getElementById('country').value
},
success: function(html) {
$("#get_more_info_dt").html(html);
}
});
I'm trying to call an AJAX query and have had lots of trouble recently.
Im trying to call a api that I have custom made myself, it displays this when the url api/reverse/test - tset (is just uses a php function to reverse the text given in the slug3.
That function works fine, just wanted to give some back on what gets requested.
reverse.php - HTML File
<textarea id="input"></textarea>
<div id="output">
</div>
index.js - All of my jQuery and AJAX
$(document).ready(function(){
var $input = $('#input');
var $output = $('#output');
$input.on('keyup', function(){
var text = $input.val();
var url = 'http://coder.jekoder.com/api/?area=reverse&text='+text;
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
success: function(data) { var output = data; },
error: alert('fail')
}) // End of AJAX
$output.html = output;
});
});
api.php - PHP file being called
<?php
$area = $_GET['area'];
if ($area == 'reverse') {
if (isset($_GET['text']) ) $text = $_GET['text'];
else $text = 'Hello';
echo strrev($text);
}
It's then supposed to take the output variable and display that in a div but that's not the main thing that matters.
error removed - was trying to see if it fixed it
There are several issue I found:
Jquery:
var text = $('#input').val(); // if you are getting value from any inputbox - get value using .val() function
var url = 'http://localhost/test.php?data='+text; // pass data like this ?data='+text
// AJAX START
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
async: true,
success: function(data) { var output = data; alert(output)},
error: function(data) { alert('fail') }
});
In php you ca get data like this:
echo $_GET['data'];
exit;
Try this. Scope of variable output is within the success call and you are using it outside the ajax call.
$(document).ready(function()
{
var $input = $('#input');
var $output = $('#output');
$input.on('keyup', function()
{
var text = $input.val();
var url = 'http://coder.jekoder.com/api/?area=reverse&text='+text;
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
success: function(data) { var output = data; $output.html = output;},
error: alert('fail')
}) // End of AJAX
});
});
I'm trying to send an AJAX request to a php file, and I want the php file to respond with a JSON object, however the AJAX function is continually failing when declare that I specifically want JSON returned. Any help will greatly be appreciated.
this is my ajax function
function getMessages(){
$.ajax({
type: 'POST',
url: 'viewInbox',
dataType: 'json',
success: function(msg){
//var content = data.substr(0, data.indexOf('<'));
populateMessages(msg);
},
error: function(){
alert("ERROR");
}
});
}
and this is the relevant code for the php file
$message_links[] = array();
.....
while($run_message = mysql_fetch_array($message_query)){
$from_id = $run_message['from_id'];
$message = $run_message['message'];
$user_query = mysql_query("SELECT user_name FROM accounts WHERE id=$from_id");
$run_user = mysql_fetch_array($user_query);
$from_username = $run_user['user_name'];
$message_links[] = array("Hash" => "{$hash}", "From" => "{$from_username}", "Message" => "{$message}");
// is that not valid json notation???
}
}
echo json_encode( $message_links, JSON_FORCE_OBJECT);
//$arr = array("a" => "1", "b" => "2");
//echo json_encode($arr);
UPDATE:
Well, I ended up switching the dataType request to 'html' and I am now able to actually access these values via JSON, however, I would still like to know why the php file was not returning correct JSON notation. Any insight would be awesome, cheers.
function getMessages(){
$.ajax({
type: 'POST',
url: 'viewInbox',
dataType: 'html',
success:function(msg){
var content = msg.substr(0, msg.indexOf('<'));
msg = JSON.parse(content);
populateMessages(msg);
},
error: function(xhr, textStatus, errorThrown) {
alert(errorThrown);
alert(textStatus);
alert(xhr);
}
});
}
function populateMessages(data){
var out = '';
var json;
for (var i in data){
var my_string = JSON.stringify(data[i],null,0);
json = JSON.parse(my_string);
alert(json.Hash);
out += i + ': ' + my_string + '\n';
}
alert(out);
}
You need to set the header as json type before your echo in PHP:
header('Content-Type: application/json');
I have this php script:
<?php
add_action('wp_ajax_nopriv_getuser', 'getuser');
add_action('wp_ajax_getuser', 'getuser');
function getuser($str)
{
global $wpdb;
if(!wp_verify_nonce($_REQUEST['_nonce'], 'ajax-nonce'))
{
die('Not authorised!');
}
$myoption = get_option( 'fixformdata_options' );
$myoptionValue = maybe_unserialize( $myoption );
$result2 = $wpdb->get_row
(
$wpdb->prepare
(
"SELECT * FROM {$myoptionValue[tablename]} WHERE personeelsNummer = %s", 1
)
);
if($result2)
{
echo json_encode( $result2 );
}
}
And this javascript file:
jQuery(document).ready(function($){
jQuery('#input_1_2').change(function()
{
jQuery.ajax({
type : 'post',
dataType : 'json',
_nonce : myAjax.ajaxurl,
url : myAjax.ajaxurl,
data : {action: 'getuser', value: this.value},
succes: function(response){
var parsed = JSON.parse(response);
var arr = [];
for(var x in parsed){ arr.push(parsed[x]);}
jQuery('#input_1_3').val(arr[1]);
jQuery('#input_1_4').val(arr[2]);
}
});
});
});
Purpose of the scripts:
When a text inputs change, use the value of this text input to display some database data in another text input.
Now I have 2 problems:
I can't get the value of the text input to the function getuser()
When I hardcode a value in the sql statement, I get the results, but they display in the console instead of using:
.
success: function(response){
var parsed = JSON.parse(response);
var arr = [];
for(var x in parsed){ arr.push(parsed[x]);}
jQuery('#input_1_3').val(arr[1]);
jQuery('#input_1_4').val(arr[2]);
}
How can I resolve this, I'm new in Wordpress and Ajax.
By the looks of your php _nonce should be inside data. You cant use this.value as this is the jQuery ajax function itself so Try:
jQuery('#input_1_2').change(function()
$value = $(this).val();
jQuery.ajax({
type : 'post',
dataType : 'json',
url : myAjax.ajaxurl,
data : {
action: 'getuser',
value: $value,
_nonce : myAjax.ajaxurl
},
succes: function(response){
var parsed = JSON.parse(response);
var arr = [];
for(var x in parsed){ arr.push(parsed[x]);}
jQuery('#input_1_3').val(arr[1]);
jQuery('#input_1_4').val(arr[2]);
}
});
});
In the php you will find value in
$_POST['value'];
Edit
inside the php add
header('content-type:application/json');
before
echo json_encode( $result2 );
on the js you shoud then not need
JSON.parse(response)
you shoud have the results in the array, ie:
response[0]
etc