php load data into fancybox when is load with JSON - php

I have a php page with a fancybox.
I have a a page in php that with jquery shown a fancybox.
When the fancybox is shown I need to load data from database.
Code of the click event:
$("a#addActivitat").click(function(){
var retorn;
$.getJSON('aplicacio/agendaLoadData.php?action=loadIdAct',function(data){
retorn = data;
});
alert(retorn);
});
The alert is undefined
the code of fancybox:
<div id="agendaAddAct">
<form method="post" action="" target="workFrame" id="actionform">
<p>
<input type="text" name="idRel" id="idRel"/>
</p>
<input type="button" value="Afegir activitat" class="btnsubmit" id="afegirActivitat"/>
</form>
</div>
I need that the value returned of php call is loaded in the idRel input.
And the code of the agendaLoadData that is called with JSON:
$var = new facanabbdd();
echo json_encode($var->getMaxValueRel());

You are not using $.getJSON correctly. Keep in mind that Ajax requests are asynchronous (Ajax does after all mean Asynchronous JavaScript and XML).
Therefore your retorn variable will not be filled with the value obtained from the Ajax call.
What you should do instead is update your DOM when you receive the data (ie. in your callback function)
$("a#addActivitat").click(function(){
$.getJSON('aplicacio/agendaLoadData.php?action=loadIdAct', function(data){
$('#idRel').val(data.value);
});
});
Provided your returned JSON document is like
{
"value": 42
}

If you put your alert inside the success handler, it will alert the data, if data is returned from your server. Try it like this:
$("a#addActivitat").click(function(){
$.getJSON('aplicacio/agendaLoadData.php?action=loadIdAct',function(data){
$("#idRel").val(data);
var retorn = $.parseJSON( data );
alert(retorn);
});
});

I found the error:
code of php page:
$("a#addActivitat").click(function(){
$.getJSON('aplicacio/agendaLoadData.php?action=loadIdAct',
function(data){
$('#idRel').val(data);
});
});
And code of agendaLoadData
echo json_decode("43");
The error was that I call the function json_encode and I need to call the function json_decode.

Related

Ajax .post() method doesn't send data to the server [duplicate]

I know there a fair few entries on SO and the web on this however I just can't get to work - any help would be appreciated.
So i have an array in Javascript which I'm trying to pass on to PHP.
I've got a little JS function to first POST it, so:
function sendToPHP() {
$.post("index.php", { "variable": toSearchArray });
}
Then down the page, I have the PHP:
<?php
$myval = $_POST['variable'];
print_r ($myval);
?>
*The prints just there for me to check.
Any ideas - fyi I'm using MAMP so its localhost:8888/index.php. Could this be causing issues in that the URL is not correct?
Thanks.
You have a misunderstanding about how ajax works. Although jquery makes it easy, it is still not automatic. You should just find a tutorial about ajax with jquery, but if you want to just send an array to php and see the output on screen, something like this would work:
index.php
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//attach to the button a click event
$('#btn').click(function(){
//get the value from the textbox
var txt=$('#txt').val();
//if txt is blank, alert an error
if(txt == ''){
alert("Enter some text");
} else {
//send txt to the server
//notice the function at the end. this gets called after the data has been sent
$.post('catcher.php', {'text':txt}, function(data){
//now data is an object, so put the message in the div
$('#response').text(data.message);
}, 'json');
}
});
});
</script>
</head>
<body>
<input type="text" id="txt">
<input type="button" id="btn">
<pre id="response" style="overflow:auto;width:800px;height:600px;margin:0 auto;border:1px solid black;"> </pre>
</body>
</html>
catcher.php:
<?php
//if something was posted
if(!empty($_POST)){
//start an output var
$output = array();
//do any processing here.
$output['message'] = "Success!";
//send the output back to the client
echo json_encode($output);
}
It is better to use 2 files, one for the user to load that initiates the ajax call and one page to handle the ajax call. Sending an array works the same, just replace getting the textbox value with sending an array.
Instead of declaring variable toSearchArray as array. consider it an javascript object.
var toSearchArray = {}.
This is what happens when you open your page (index.php)
A GET request is issued to index.php and the content is returned. There are no values in the $_POST array so your print_r() line does nothing.
Javascript is executed that sends a POST request to index.php via AJAX. Note that this is an entirely new request, separate to the original GET. The $_POST array will be populated on this request however the response is discarded.
Hopefully this will illustrate what you can do.
ajax.php
<?php
header("content-type: application/json");
exit(json_encode($_POST));
index.php
<script>
const toSearchArray = ['some', 'array', 'with', 'values'];
$.post('ajax.php', {
variable: toSearchArray
}).done(data => {
console.log(data) // here you will see the result of the ajax.php script
})
</script>
Well I don't think thats the right way to do it when it comes to arrays, see you need to use JSON encode in javascript then JSON decode in php
Refer to this question Pass Javascript Array -> PHP

Data is not getting set in php when ajax call is successful [duplicate]

I know there a fair few entries on SO and the web on this however I just can't get to work - any help would be appreciated.
So i have an array in Javascript which I'm trying to pass on to PHP.
I've got a little JS function to first POST it, so:
function sendToPHP() {
$.post("index.php", { "variable": toSearchArray });
}
Then down the page, I have the PHP:
<?php
$myval = $_POST['variable'];
print_r ($myval);
?>
*The prints just there for me to check.
Any ideas - fyi I'm using MAMP so its localhost:8888/index.php. Could this be causing issues in that the URL is not correct?
Thanks.
You have a misunderstanding about how ajax works. Although jquery makes it easy, it is still not automatic. You should just find a tutorial about ajax with jquery, but if you want to just send an array to php and see the output on screen, something like this would work:
index.php
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//attach to the button a click event
$('#btn').click(function(){
//get the value from the textbox
var txt=$('#txt').val();
//if txt is blank, alert an error
if(txt == ''){
alert("Enter some text");
} else {
//send txt to the server
//notice the function at the end. this gets called after the data has been sent
$.post('catcher.php', {'text':txt}, function(data){
//now data is an object, so put the message in the div
$('#response').text(data.message);
}, 'json');
}
});
});
</script>
</head>
<body>
<input type="text" id="txt">
<input type="button" id="btn">
<pre id="response" style="overflow:auto;width:800px;height:600px;margin:0 auto;border:1px solid black;"> </pre>
</body>
</html>
catcher.php:
<?php
//if something was posted
if(!empty($_POST)){
//start an output var
$output = array();
//do any processing here.
$output['message'] = "Success!";
//send the output back to the client
echo json_encode($output);
}
It is better to use 2 files, one for the user to load that initiates the ajax call and one page to handle the ajax call. Sending an array works the same, just replace getting the textbox value with sending an array.
Instead of declaring variable toSearchArray as array. consider it an javascript object.
var toSearchArray = {}.
This is what happens when you open your page (index.php)
A GET request is issued to index.php and the content is returned. There are no values in the $_POST array so your print_r() line does nothing.
Javascript is executed that sends a POST request to index.php via AJAX. Note that this is an entirely new request, separate to the original GET. The $_POST array will be populated on this request however the response is discarded.
Hopefully this will illustrate what you can do.
ajax.php
<?php
header("content-type: application/json");
exit(json_encode($_POST));
index.php
<script>
const toSearchArray = ['some', 'array', 'with', 'values'];
$.post('ajax.php', {
variable: toSearchArray
}).done(data => {
console.log(data) // here you will see the result of the ajax.php script
})
</script>
Well I don't think thats the right way to do it when it comes to arrays, see you need to use JSON encode in javascript then JSON decode in php
Refer to this question Pass Javascript Array -> PHP

Javascript POST not working - Sending Javascript array to PHP

I know there a fair few entries on SO and the web on this however I just can't get to work - any help would be appreciated.
So i have an array in Javascript which I'm trying to pass on to PHP.
I've got a little JS function to first POST it, so:
function sendToPHP() {
$.post("index.php", { "variable": toSearchArray });
}
Then down the page, I have the PHP:
<?php
$myval = $_POST['variable'];
print_r ($myval);
?>
*The prints just there for me to check.
Any ideas - fyi I'm using MAMP so its localhost:8888/index.php. Could this be causing issues in that the URL is not correct?
Thanks.
You have a misunderstanding about how ajax works. Although jquery makes it easy, it is still not automatic. You should just find a tutorial about ajax with jquery, but if you want to just send an array to php and see the output on screen, something like this would work:
index.php
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//attach to the button a click event
$('#btn').click(function(){
//get the value from the textbox
var txt=$('#txt').val();
//if txt is blank, alert an error
if(txt == ''){
alert("Enter some text");
} else {
//send txt to the server
//notice the function at the end. this gets called after the data has been sent
$.post('catcher.php', {'text':txt}, function(data){
//now data is an object, so put the message in the div
$('#response').text(data.message);
}, 'json');
}
});
});
</script>
</head>
<body>
<input type="text" id="txt">
<input type="button" id="btn">
<pre id="response" style="overflow:auto;width:800px;height:600px;margin:0 auto;border:1px solid black;"> </pre>
</body>
</html>
catcher.php:
<?php
//if something was posted
if(!empty($_POST)){
//start an output var
$output = array();
//do any processing here.
$output['message'] = "Success!";
//send the output back to the client
echo json_encode($output);
}
It is better to use 2 files, one for the user to load that initiates the ajax call and one page to handle the ajax call. Sending an array works the same, just replace getting the textbox value with sending an array.
Instead of declaring variable toSearchArray as array. consider it an javascript object.
var toSearchArray = {}.
This is what happens when you open your page (index.php)
A GET request is issued to index.php and the content is returned. There are no values in the $_POST array so your print_r() line does nothing.
Javascript is executed that sends a POST request to index.php via AJAX. Note that this is an entirely new request, separate to the original GET. The $_POST array will be populated on this request however the response is discarded.
Hopefully this will illustrate what you can do.
ajax.php
<?php
header("content-type: application/json");
exit(json_encode($_POST));
index.php
<script>
const toSearchArray = ['some', 'array', 'with', 'values'];
$.post('ajax.php', {
variable: toSearchArray
}).done(data => {
console.log(data) // here you will see the result of the ajax.php script
})
</script>
Well I don't think thats the right way to do it when it comes to arrays, see you need to use JSON encode in javascript then JSON decode in php
Refer to this question Pass Javascript Array -> PHP

JQuery Form Plugin, can't receive data in PHP

I'm using JQuery Form Plugin for AJAX file uploader.
The (html) form is created dynamically, and looks like this:
<form id="formUpload" action="fileReceiver.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileUpload" multiple>
<input type="submit" value="Upload File to Server">
</form>
Because, the form is created dynamically, I'm using jquery on(). I also need to send a few variables, I'm using data options from the plugin.
The Javascript looks like this:
$(document).on("submit", "form#formUpload", function() {
$(this).ajaxForm({
data: { someVariable : 'someValue' },
complete: function(xhr) {
status.html(xhr.responseText);
}
});
});
I think the form is binded correctly, I could call/alert something from the ajaxForm (jquery form plugin) function through beforeSend or Success options.
Now, the problem is the PHP couldn't get the data I posted in the Javascript.
My PHP is simple like this:
<?php
echo $_POST["someVariable"];
?>
It gives me error "Notice: Undefined index: someVariable blah blah blah"
Any advice? Thx :)
Try adding some variables in hidden input inside form
<input type="hidden" name="someVariable" value="someValue">
and remove $(document).on("submit",... event
You can try
var input = $("<input>").attr("type", "hidden").attr("name", "someVariable").val("someValue");
$('#formUpload').append($(input));
this links may help you
http://www.malsup.com/jquery/form/progress2.html
http://www.malsup.com/jquery/form/file-echo2.php.txt
Well, in case your form is being added dynamically then you'd have to use DOMNodeInserted event instead of submit. That way, whenever there's some addition in DOM your form will be attached to form plugin.
You can replace your function with following --
$(document).on("DOMNodeInserted", "form#formUpload", function() {
$(this).ajaxForm({
data: { someVariable : 'someValue' },
complete: function(xhr) {
// do something
}
});
});
But remember, using DOMNodeInserted event will fire that method whenever there's addition of any kind into DOM. So just put what is essential ( in this case form plugin init for #formUpload ) .
Try to locate if you already added the jQuery Form Plugin...
<script src="jquery.form.js"></script>
Your syntax is definitely correct according to http://malsup.com/jquery/form/#options-object

AJAX (jQuery) Response

Suppose all forms in your application has this structure:
<div id="result_messages"></div>
<form action="/action">
<!-- all the form -->
</form>
A submit button for this form looks like this:
<input type="button" onclick="$.post( '/action', $(form).serialize(), function (data) {
$('#result_messages').html( data ); // At this point the 'data' is an standard HTML with a message
});" />
BUT, But not always the response is a message... how to detect when data is a message or not??????:
<input type="button" onclick="$.post( '/action', $(form).serialize(), function (data) {
if (isMessage( data ))
$('#result_messages').html( data );
else
doActionWith( data );
});" />
Using JSON maybe a solution:
{ response_type : 'message', data: 'all_data_here' }
{ response_type : 'nomessage', data: 'all_data_here' }
Other solution is to put a special STRING at the begin of data:
<!--message--><ul><li>form was processed</li></ul>
Have you other ideas? what do you think about this solutions?
what do you think about this solutions?
<input type="button" onclick="$.post( "/action", $(form).serialize(), function (data) {
That will fall over. The quote before /action will terminate the onclick attribute value
Inline JS is nasty. Bind your event handlers from external scripts.
If JS is not available, this won't work. Write a form that works (with a regular submit button) and then progressively enhance with JS.
form is undefined, that should be this.form
/action is repeating yourself. Write more reusable code: this.form.action
Using JSON maybe a solution
Yes. Use a structured data format instead of a blob of code to shove into the page.
What are the options, other than simple html output? json?
If so, you can send an object back and check it in the callback.

Categories