How to access part of an array in ajax - php

In my ajax, the PHP side contains an array with 3 values. I'd like to put these 3 values into separate input fields. How can I do this? How do I access the array sent from PHP?
My code so far:
PHP
$total['tot1'] = $numwelds + $numconwelds + $mpcountrys ;
$total['tot2'] = $numwelds + $numconwelds + $fortot2 ;
$total['tot3'] = $numwelds + $numconwelds + $fortot2 / $fortot3;
$response = json_encode($total);
header("Content-Type: application/json");
echo $response;
exit;
Jquery
jQuery(document).ready( function($) {
(function($) {
$(document).ready(function(){
$('#formsubmit').click(function(){
$.post(
PT_Ajax.ajaxurl,
{
action : 'ajax-inputtitleSubmit',
numberofwelds : $('input[name=numberofwelds]').val(),
numberofconwelds : $('input[name=numberofconwelds]').val(),
nextNonce : PT_Ajax.nextNonce
},
function( response ) {
$("#totalone").val(response);
$("#totaltwo").val(response);
$("#totalthree").val(response);
}
);
return false;
});
});
})(jQuery);
});

You can use JSON.parse to convert json to object:
var obj = JSON.parse(response);
$("#totalone").val(obj.tot1);
$("#totaltwo").val(obj.tot2);
$("#totalthree").val(obj.tot3);
Or you can also use $.parseJSON() of jQuery.

use like
$("#totalone").val(response["tot1"]);
$("#totaltwo").val(response["tot2"]);
$("#totalthree").val(response["tot3"]);

Related

Can't read json elements from mysql query via ajax

I need to add some geo-marker to my map.
the markers are in my mysql table on altervista.org
but my JavaScript says [object Object] every time i try...
here my php code:
require('connect.php');
$query = "SELECT latit, longit FROM segnalazioni";
$result = mysql_query($query);
$rows = array();
while ($row = mysql_fetch_assoc($result)){
$rows[] = $row;
}
echo json_encode($rows);
it returns:
[{"latit":"12.34","longit":"12.34"},{"latit":"56.78","longit":"56.78"},...]
here my JavaScript:
function addMarker(mapobj) {
$.getJSON( "http://####.altervista.org/map.php", function( data ) {
var items = [];
$.each( data, function( key1 , val1 ) {
items.push( "<li id='" + key1 + "'>" + val1 + "</li>" );
//next todo:
//mapobj.marker([latit, longit]).addTo(map).bindPopup("hi");
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
}
and on the end of my [body] i can see only:
[object Object]
[object Object]
[object Object]
...
According to jquery.each the parameters are
indexInArray , value and NOT key, value
So the code is:
$(function () {
var data = [{"latit": "12.34", "longit": "12.34"}, {"latit": "56.78", "longit": "56.78"}];
var items = [];
$.each(data, function(indexInArray , value) {
items.push( "<li id='" + indexInArray + "'>latit: " + value.latit + ' longit:' + value.longit + ' OR '+ JSON.stringify(value) + "</li>" );
//next todo:
//mapobj.marker([latit, longit]).addTo(map).bindPopup("hi");
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
Use this
$.each(result, function(key, value){
$.each(value, function(key, value){
console.log(key, value);
});
});
I would also encourage to use header before sending JSON stream. It is always good to tell the content type sent in HTTP response. Use
header('Content-Type: application/json');
Before using
echo json_encode($rows);

Form validation not working when using Ajax

I'm currently using ajax to auto-save a form. Codeigniter's form validation function doesn't seems to be working when using ajax. Anyone knows whats the problem here?
PHP:
function autoSavePublicationDetails()
{
$this->form_validation->set_rules('first_author', 'First author', 'required');
if ($this->form_validation->run() == FALSE)
{
$data['message'] = validation_errors();
}
else
{
$newRow = json_decode($_POST['json']);
$claim_id = $_POST['claim_id'];
//$this->publicationClaim_model->updateClaim($newRow,$claim_id);
//$data['claim_id'] = $claim_id;
$data['message'] = "Success";
}
print json_encode($data);
}
Jquery:
setInterval(function(){
var date = new Date();
var dateFormat = date.getFullYear() + "-" + ("0" + date.getMonth()).slice(-2) + "-" + ("0" + date.getDate()).slice(-2) + " " + ("0" + date.getHours()).slice(-2) + ":" + ("0" + date.getMinutes()).slice(-2) + ":" + ("0" + date.getSeconds()).slice(-2);
var claimObj = {
first_author : $('#first_author').val(),
authors : $('#authors').val(),
publication_title : $('#publication_title').val(),
source : $('#source').val(),
publication_submitted : $('#publication_submitted :selected').val(),
research_bank_number : $('#research_bank_number').val(),
research_code_1 : $('#research_code_1 :selected').val(),
research_code_2 : $('#research_code_2 :selected').val(),
research_code_3 : $('#research_code_3 :selected').val(),
issn : $('#issn').val(),
type_of_publication : $('#type_of_publication :selected').val(),
claim_type : $('input[name="claim_type"]').val(),
claim_author : $('input[name="claim_author"]').val(),
claim_date : dateFormat,
user_id : $('input[name="user_id"]').val()
};
var json_data = JSON.stringify(claimObj);
var className;
$.post("autoSavePublicationDetails",
{
'<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo $this->security->get_csrf_hash(); ?>',
'json' : json_data,
'claim_id' : $('#claim_id').val()
},
function(data,status){
console.log("Status: " + status);
var jsonReturn = $.parseJSON(data);
alert(jsonReturn.message);
if (jsonReturn.message == "Success")
{
className = 'label label-success';
$('#message').addClass(className);
$('#message').text('Data saved.');
}
else
{
className = 'label label-danger';
$('#message').addClass(className);
$('#message').text('Form not saved.');
}
$('#message').fadeIn();
setTimeout(function() {
$('#message').fadeOut();
$('message').removeClass()
}, 1000);
});
}, 10000);
I tried alerting the validation errors. It says that my first_author field is empty even when I already entered the some text inside.
Json that is passed to controller:
instead of $.post() try to use $.ajax()

passing parameters to a php from javascript

I've done this before but for some reason the parameters are being passed oddly.
I have a javascript function that I've used to pass parameters, I've ran some tests and in the function the variables are correct.
These are just a few snippets of the js that relate to the issue:
var tdes = document.getElementById("taskDescription1").value;
var tnam = document.getElementById("taskName1").value;
var shif = document.getElementById("shift1").value;
var ttyp = document.getElementById("taskType1").value;
var date = document.getElementById("datepicker").value;
var ooc = document.getElementById("ooc1").value;
var dateSplit = date.split('/');
var deadlineDate = "";
for( var i = 0; i < dateSplit.length; i++){
deadlineDate = deadlineDate + dateSplit[i];
}
xmlhttp.open("GET","subTask.php?q="+ encodeURIComponent(tdes) + "&w=" + encodeURIComponent(tnam) +"&e=" +encodeURIComponent(shif) + "&y=" + encodeURIComponent(ttyp) + "&b=" + encodeURIComponent(deadlineDate) + "&u=" + encodeURIComponent(ooc),true);
I ran a web console and this is what is actually getting passed...
http://***************/****/********/subTask.php?taskName1=test+taskname+works&taskDescription1=test+des&shift1=All&ooc1=Open&taskType1=normal&datepicker=06%2F28%2F2013
I'm not sure what's going on in between the xmlhttp.open and the GET method in php. None of these variables are getting passed.
Why not use jQuery - very straightforward format (I prefer POST...):
$(document).ready(function() {
var tdes = $("#taskDescription1").val();
var tnam = $("#taskName1").val();
var shif = $("#shift1").val();
var ttyp = $("#taskType1").val();
var date = $("#datepicker").val();
var ooc = $("#ooc1").val();
var dateSplit = date.split('/');
var deadlineDate = "";
for( var i = 0; i < dateSplit.length; i++){
deadlineDate = deadlineDate + dateSplit[i];
}
$.ajax({
type: "POST",
url: "subTask.php",
data: "q="+ encodeURIComponent(tdes) + "&w=" + encodeURIComponent(tnam) +"&e=" +encodeURIComponent(shif) + "&y=" + encodeURIComponent(ttyp) + "&b=" + encodeURIComponent(deadlineDate) + "&u=" + encodeURIComponent(ooc),true),
success: function(whatigot) {
alert('Server-side response: ' + whatigot);
} //END success fn
}); //END $.ajax
}); //END document.ready()
Notice how easy the success callback function is to write... anything returned by subTask.php will be available within that function, as seen by the alert() example.
Just remember to include the jQuery library in the <head> tags:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
Also, add this line to the top of your subTask.php file, to see what is happening:
<?php
$q = $_POST["q"];
$w = $_POST["w"];
die("Value of Q is: " .$q. " and value of W is: " .$w);
The values of q= and w= will be returned to you in an alert box so that (at least) you can see what values they contained when received by subTask.php
Following script should help:
function ajaxObj( meth, url )
{
var x = false;
if(window.XMLHttpRequest)
x = new XMLHttpRequest();
else if (window.ActiveXObject)
x = new ActiveXObject("Microsoft.XMLHTTP");
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
var ajax = ajaxObj("POST", "subTask.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
console.log( ajax.responseText )
}
}
ajax.send("u="+tdes+"&e="+tnam+ ...... pass all the other 'n' data );

How to pass a php array with json to jquery function, ajax

How to pass my php array to this jquery code ?
i have tried json_encoding but couldnt use it in my jquery function.
my json string looks like this:
{"1":{"id":"1","league":"england","team1":"Arsenal","team2":"Chelsea"},"2":{"id":"2","league":"spain","team1":"Deportivo","team2":"Real Madrid"}}
JS:
<script type="text/javascript">
$(document).ready(function(){
var shownIds = new Array();
setInterval(function(){
$.get('livescore_process.php', function(data){
for(i = 0; i < data.length; i++){
if($.inArray(data[i]["id"], shownIds) == -1){
if(data[i]["league"]=="england"){
$("#eng").append("id: " + data[i]["team1"] + " [ "+data[i]["team1"]+ " - "+data[i]["team1"]+" ]"+ data[i]["team2"] +"<br />");
}
shownIds.push(data[i]["id"]);
}
}
});
}, 3000);
});
</script>
try $.getJSON instead of $.get and use php json_encode:
$.getJSON('livescore_process.php', function(data){...
however the response data is not an array but a json object, so to handle it you can try:
$.each(data, function (index, item) {
if (item.hasOwnProperty('id')) {
if (item.league == "england") {
$("#eng").append("id: " + item.team1 + " [ " + item.team1 + " - " + item.team1 + " ]" + item.team2 + "<br />");
}
shownIds.push(item.id);
}
});
jsfiddle

Passing JSON data from JavaScript using Ajax to PHP

I have the following JS:
window.onload = function() {
'use strict';
var ajax = getXMLHttpRequestObject();
ajax.onreadystatechange = function() {
if ( ajax.readyState == 4 ) {
if ( (ajax.status >= 200 && ajax.status < 300) || (ajax.status == 304) ) {
var data = JSON.parse(ajax.responseText);
var file = '';
file += 'Original: ' + data['org'].file + '<br>';
file += 'Processed: ' + data['pre'].file + '<br>';
document.getElementById('output').innerHTML = file;
} else {
document.getElementById('output').innerHTML = 'Error: ' + ajax.statusText;
}
}
};
document.getElementById('btn').onclick = function() {
ajax.open('POST', 'resources/test.json', true);
ajax.setRequestHeader('Content-Type', 'application/json');
ajax.send(null);
};
};
I would like to pass the data from
data['org'].file
and
data['pre'].file
to PHP and have it echo out the value using the POST method. Please no jQuery solutions this needs to be strictly JavaScript.
Something like this:
<?php $data = $_POST['the_data']; echo $data; ?>
Here is the JSON from test.json:
{
"org": {
"file": "css/original.css"
},
"pre": {
"file": "css/preprocessed.css"
}
}
If you want a PHP script to echo JSON data, it's as simple as this:
<?
$json = file_get_contents('php://input');
//...
echo $json;
?>
To post it from Javascript, I reccomend reading this. There's a reason so many people use jQuery...
have a look on JSON Stringify you can use that to encode your data.
Then after you encoded you can send it wherever you need.

Categories