How to pass json data from one javascript to another - javascript

Guys here the first script is designed to take static .json files to display certain content and animate them. The code snippet is
var self = this;
$.getJSON('data/post_'+ index +'.json', function(d){
self.postCache[index] = d;
callback(d)
but I want to modify it to so it could take data from database. I got the data in the same format as it was in static json files and my question is how can I pass that data to this script so that it work as it should.
I am sending request using ajax
$(function ()
{
$.ajax({
url: 'api.php',
data: "<?php echo $data?>",
dataType: 'json',
success: function(data)
{
//I really dont know what to write here :(
}
});
});
and the api.php file is getting data from database and I an encoding the data to json using json_encode

var self = this;
$.post('api.php',
{"post_id": index},
success: function(d)
{
self.postCache[index] = d;
callback(d);
});
see http://api.jquery.com/jquery.post/
In api.php do a SQL query where the post_id = $_POST['post_id'] then echo json_encode($database_row);

$.getJSON just calls $.ajax with some predefined values automatically set for you. This means, since you said the data is the same, that you can do exactly the same as you were doing previously.
Keep a reference to this
Make your async call
in the success function, save your reference and execute your callback
var self = this;
$.ajax({
url: 'api.php',
data: "<?php echo $data?>",
dataType: 'json',
success: function(data)
{
self.postCache[index] = data;
callback(data);
}
});

Related

A part of AJAX response storing in PHP variable

I need to store a piece of data, into PHP variable, which is received through AJAX response in an input box. How can I do this?
<script type="text/javascript">
$(document).ready(function() {
$("#user_id").change(function() {
var id = $(this).val();
var dataString = 'user_id='+ id;
$.ajax({
type: "POST",
url: "wmat_details.php",
data: dataString,
cache: false,
success: function(result) {
var data = result.split(",");
$('#name').val(data[0]);
$('#email').val(data[1]);
$('#ref_id').val(data[2]);
$('#candidature_start').val(data[3]);
$('#candidature_end').val(data[4]);
$('#default_attempts').val(data[5]);
$('#existing_complimentary').val(data[6]);
$('#wmat_start').val(data[9]);
$('#wmat_end').val(data[10]);
$('#attempts_taken').val(data[11]);
}
});
});
});
</script>
As shown in above code, I want to store $('#attempts_taken').val(data[11]); this value to a PHP variable. Any insight is appreciated.
Unfortunately you can't.
PHP is server side while jQuery (JS) is client side. They are two separate layers of abstraction that interact only when the client call the server.
I don't have enough informations about what you need to do with data[11] but it seems that you have only one option: make a consecutive AJAX call to the php file that will manipulate data[11].
The consecutive AJAX call must be executed from inside the first call success callback; something like this:
success: function(result){
// Your on success logic
// ...
// Prepare the object to send to the server
var objData = {};
objData.attemptsTaken = data[11];
// Execute the second AJAX call to the server
$.ajax({
type: "POST",
url: "second_call_destination_file.php",
data: objData,
success: function(result){
// Do something on success
},
error: function(){
// Do something on error
},
complete: function(){
// Do something on complete (executed after success and error)
}
}
You cannot store ajax response into a php variable.
way 1 :
You can make another ajax call.
way 2 :
you can set session.

how to pass a javascript variable to another php file

I have a javascript file which contains an array of variable-array[] and I want to pass this variable to another php file using post(data=array). So that I can get the $_POST['data'] inside the php file.How can I do it?
You can use an Ajax POST to the php script to send data:
$.ajax({
type: "POST", //http method
url: url, //url to php file
data: data, //array or json object
success: success, //callback
});
In PHP you will need to get the data from the $_POST array.
var val1 = 'test1';
var val2 = 'test2';
$.ajax({
type: 'POST',
url: 'yourfile.php',
data: { data: [text1: val1, text2: val2] },
success: function(response) {
console.log(response);
}
});
You can't directly do that, since JavaScript runs on the client-side and PHP gets executed on the server-side. You would need to execute the JavaScript first and then send the result to the server via a FORM or AJAX call.
PHP
$parameter = "this is a php variable";
echo "var myval = foo(" . parameter . ");";
javascript
var myval = foo("this is a php variable"); // generated by PHP
$.ajax({
type: 'POST',
url: 'yourphpfile.php',
data: {'variable': myval},
});
Receiving PHP (yourphpfile.php)
$myval = $_POST['variable'];
//do something!

Passing php string as json to be received by jquery

I am trying to echo a string which is structured like json, but the jquery ajax post is not able to parse it properly. What I want to know is if this string will be treated like json in the jquery json parse just like when we echo a json_encode.
echo '{"mobno":'.$mobno.',"charge":'.$charge.',"capacity":'.$capacity.'}';
ajax code:
jQuery.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
success: function(response){
var Vals = JSON.parse(response);
if(!Vals){
alert("Error1");
}else{
var capacity = parseInt(Vals.capacity);
if(capacity>0){
alert("worked1");
}else{
alert("worked2");
}
}
}
});
I don't get a single alert out of the 3.
As per your edit and comment, your json string is correct. You just have to change your AJAX request.
Add this setting dataType: "json" in your AJAX request if you're expecting a json object as response from server.
So your AJAX request should be like this:
jQuery.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
dataType: "json",
success: function(response){
// you can access json properties like this:
// response.mobno
// response.charge
// response.capacity
var capacity = response.capacity;
if(capacity > 0){
alert("worked1");
}else{
alert("worked2");
}
}
});
Just so JavaScript can differ string and properties of json, please use double quote for starting and ending the string and for json properties use single quote or vice-versa. Try that out and let me know if you could not figure that out.
As other answers suggest you need to fix the quotes of the JSON the web service is sending back in the response.
Regarding you question, everything sent back in the response is actually a string. You need to decide what to do with it once it arrives.
One of the ways to allow both client side and server side programs understand what was sent is setting the right content type header.
For JSON the best way is to set the content type header to "application/json".
If you're using php you can do this:
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);
On the client side jquery ajax you can do this:
$.ajax({
dataType: "json",
url: url,
data: data,
success: function(data, textStatus, jqXHR){}
});
In this example the "data" parameter passed to the "success" callback function is already a js object (after JSON.parse). This is due to the use of the "dataType" parameter in the ajax declaration.
Optionally, you can do this manually and write a simple $.post which receives a string and do the JSON.parse yourself.
Maybe you should do the manual parsing yourself at first, and use the console.log(data) before and after the parsing so you'd know you're doing it correctly. Then, move on to the automatic way with "dataType" set to "json".
Please see #Rajdeep Paul's JSON string correction. Then, have your response JSON object remapped to an array.
JSON string
echo "{\"mobno\":\"".$mobno."\",\"charge\":\"".$charge."\",\"capacity\":\"".$capacity."\"}";
Ajax
$.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
success: function(response){
// map JSON object to one-dimensional array
var Vals = $.map( JSON.parse(response), function(el) { return el });
if(!Vals){
alert("Error1");
}else{
var count = parseInt(Vals.length);
if(count>0){
alert("worked1");
}else{
alert("worked2");
}
}
}
});
Reference: Converting JSON Object into Javascript array

split JSON data from PHP to three arrays in JavaScript

I am passing values from PHP Script to JS using JSON encode.
$arr=array('X'=>$X,'Y'=>$Y,'par'=>$par);
echo json_encode($arr);
Which produces
{"X": ["-0.9537121038646844","-0.9537121038646844","-0.9537121038646844","0.9537121038646843",""],
"Y": ["-0.9537121038646844","-0.7799936811949519","-0.5533396521383813","-0.37962122946864896",null],
"par": ["0.009811016749950838","0.005007306592216437","5.058030686503405E-4","9.451402320405391E-4",null]}
In the javascript, I used the following command
{
$.post("plot.php",param,function(data){dataType:"json";console.log(data);Var X1=data.X;});
}
But I am not able to obtain the values of X alone. I tried few suggestions from similar threads, but none of them did the trick.I need the three arrays, X,Y and Par to be used in JS.
Try this:
$.post("plot.php", param, function(data) {
console.log(data);
var X1 = data.X;
},
"json"
);
You can also use $.ajax (which is the function $.post internally calls):
{
$.ajax({
type: "POST",
url: "plot.php",
dataType: "json",
data: param,
success: function(data) {
console.log(data);
var X1=data.X;
}
});
}
If you are using php you have to specify at the last parameter of post fn that is json type:
$.post("plot.php",param, function(data){
console.log(data);
var X1=data.X;
},'json');

returning part of a json file as a variable in jquery

I am attempting to create a glossary tooltip for a website that finds keywords from a json file that is being created by sitecore. I need to get the "Text:" parts from the json file and make then a variable in my jquery so they are the keywords that are found and wrapped with the appropriate tags. I had it working to the point where i could get console to log that there were 2 entries in my json file but that's it.
Here is my sample json code:
[{"Id":"ef339eaa-78e1-4f9e-911e- 096a1920f0b6","Name":"Glossary","DisplayName":"Glossary","TemplateId":"b27d2588-3d02-4f5f-8064-2ee3b7b8eb39","TemplateName":"Glossary","Url":"/Global-Content/Glossary/Glossary","Version":1,"Created":"\/Date(1343987220000)\/","CreatedBy":"sitecore\\rgoodman","Revision":"ae8b3ae0-d0ca-4c4a-9f27-a542a31ab233","Updated":"\/Date(1348137810133)\/","UpdatedBy":"sitecore\\admin","Text":"Glossary","Content":"A bit of test content for the glossary"},{"Id":"3fa51ad4-cfb6-4ff1-a9b5-5276914b2c23","Name":"Abraham","DisplayName":"Abraham","TemplateId":"b27d2588-3d02-4f5f-8064-2ee3b7b8eb39","TemplateName":"Glossary","Url":"/Global-Content/Glossary/A/Abraham","Version":1,"Created":"\/Date(1348148640000)\/","CreatedBy":"sitecore\\admin","Revision":"231284ec-9fb9-4502-ad79-a5806479ecba","Updated":"\/Date(1348148779656)\/","UpdatedBy":"sitecore\\admin","Text":"Abraham","Content":"This is a lincoln person"}]
But I suppose this is not of any use as it is just the "Text:" part i am looking to return.
Here is my jquery:
function getData(url) {
var data;
$.ajax({
async: false,
url: '/_assets/js/glossary.json',
dataType: 'json',
success: function(data.Text){
data.Text = response;
}
return(response);
});
}
function HighlightKeywords(keywords)
{
var el = $("body");
$(keywords).each(function()
{
var pattern = new RegExp("(" +this+ ")", ["gi"]);
var rs = "<mark href='#' class='tooltip'>$1</mark>";
el.html(el.html().replace(pattern, rs));
});
}
HighlightKeywords(data.Text);
Essentially i need to return the "Text:" bit of json where data is on the HighlightKerywords function. Where am i going wrong?
Any help would be much appreciated. Thanks
Your function is not syntactically formatted properly. Your return must go inside of the success function in the synchronous example, and not randomly placed in the ajax object..
function getData() {
$.ajax({
async: false,
url: '/_assets/js/glossary.json',
dataType: 'json',
success: function(data){
//HighlightKeywords(data.Text);
//or
return(data.Text);
}
});
}
Ajax is Asynchronous communication, you can't insert its response into a global variable and expect to be able to work with it.
You need to do all the work on the data.text in the success function.
success: function(response){
HighlightKeywords(response.Text);
}

Categories