I have actually read all related answers to my question but I need a clear and simple example on how to properly implement my code below.
myHome.php
jquery
var url = "computeArea.php";
var data = $('thisForm').serialize();
$.post(url,data,function(response)); // how do i get the area being returned from
computeArea function? i need to save the
return value to a javascript variable
computeArea.php
function computeArea ($data){ // do i need to parse $data to make it an array?
return $area;
}
im new to jquery and your help is very helpful. thank you!
You can do:
$.post(url,data,function(response){
alert(response)
});
ps: you are missing the . between $ and post.
In your php code you could do that:
echo json_encode($area);
Do a simple teste.
jQuery:
$.post("url/to/file.php",{variable_name: "hello"/*(we'll give this value to variable_name*/)},
function(response){
if(response>0)
alert('Something went wrong');
else
alert(response);
});
Now, on server side:
<?php
if(isset($_POST['variable_name']) && $_POST['variable_name']!=="")
echo $_POST['variable_name'];
else
echo 1;
?>
You are misunderstanding the use of post requests. This will not call the computeArea function in computeArea.php and pass data as its parameter:
var data = $('thisForm').serialize();
$.post(url,data,function(response));
You can do this instead for computeArea.php:
$data = $_POST['watever_you_are_serializing'];
// Do computations, etc.
$area = 123; // Contains computed area
echo $area; // Or json_encode($area);
If you need to call that function from computeArea.php, then you can create a new file for $.post request (eg. computeArea2.php) and include computeArea.php from there. It would be something like this:
include 'computeArea.php';
$data = $_POST['watever_you_are_serializing'];
echo computeArea($data);
Something along the lines of:
var url = "computeArea.php",
data = $('thisForm').serialize(),
new_variable;
$.post(url, data, function(response) {
new_variable = response;
});
Though I presume there's a bit more to your PHP script, as otherwise $area isn't defined anywhere.
Related
I have 2 files(call.php and post.php) and using ajax pass value from call to post,and i want to get return value from post ,but this doesn't work. when i change post ,modify "return" to "echo",it works,but i don't know why.can anybody give me a help?
Examples would be most appreciated.
call.php
<script type="text/JavaScript">
$(document).ready(function(){
$('#submitbt').click(function(){
//var name = $('#name').val();
//var dataString = "name="+name;
var dataPass = {
'name': $("#name").val()
};
$.ajax({
type: "POST",
url: "post.php",
//data: dataString,
data: dataPass,//json
success: function (data) {
alert(data);
var re = $.parseJSON(data || "null");
console.log(re);
}
});
});
});
</script>
post.php:
<?php
$name = $_POST['name'];
return json_encode(array('name'=>$name));
?>
update:
by contrast
when i use MVC "return" will fire.
public function delete() {
$this->disableHeaderAndFooter();
$id = $_POST['id'];
$token = $_POST['token'];
if(!isset($id) || !isset($token)){
return json_encode(array('status'=>'error','error_msg'=>'Invalid params.'));
}
if(!$this->checkCSRFToken($token)){
return json_encode(array('status'=>'error','error_msg'=>'Session timeout,please refresh the page.'));
}
$theme = new Theme($id);
$theme->delete();
return json_encode(array('status'=>'success'));
}
$.post('/home/test/update',data,function(data){
var retObj = $.parseJSON(data);
//wangdongxu added 2013-08-02
console.log(retObj);
//if(retObj.status == 'success'){
if(retObj['status'] == 'success'){
window.location.href = "/home/ThemePage";
}
else{
$('#error_msg').text(retObj['error_msg']);
$('#error_msg').show();
}
});
This is the expected behaviour, Ajax will get everything outputted to the browser.
return only works if you are using the returned value with another php variable or function.
In short, php and javascript can't communicate directly, they only communicate through what php echoed or printed. When using Ajax or php with javascript you should use echo/print instead of return.
In Fact, as far as I know, return in php is not even used in the global scope very often (on the script itself) it's more likely used in functions, so this function holds a value (but not necessarily outputs it) so you can use that value within php.
function hello(){
return "hello";
}
$a = hello();
echo $a; // <--- this will finally output "hello", without this, the browser won't see "hello", that hello could only be used from another php function or asigned to a variable or similar.
It's working on the MVC framework because that has several layers, probably the delete() method is a method from the model, which returns its value to the controller, and the controller echo this value into the view.
Use dataType option in $.ajax()
dataType: "json"
In post.php try this,
<?php
$name = $_POST['name'];
echo json_encode(array('name'=>$name));// echo your json
return;// then return
?>
I'm trying to build an array of data that will then be ajax using post to php - below is my code:
$('#mainBodySaveSubmitButtonProfilePhotoIMG').click(function() {
var profilePhotoArray = [];
$('.mainUnapprovedProfilePhotoWrapperDIV').each(function() {
var action = '';
alert( this.id );
if($('.mainUnapprovedProfilePhotoAttractiveIMG', this).is(':visible')) {
alert('attractive...');
action = 'attractive';
}
else if($('.mainUnapprovedProfilePhotoDeleteIMG', this).is(':visible')) {
alert('delete...');
action = 'delete';
}else{
alert('normal...');
action = 'normal';
}
profilePhotoArray[this.id+'_'+this.id] = action;
});
alert(profilePhotoArray.length);
for (i=0;i<profilePhotoArray.length;i++) {
console.log("Key is "+i+" and Value is "+array[i]);
}
$.post('scripts/ajax/ajax_approval_functions.php', {
'approvalProfilePhotos': '1',
'approvalProfilePhotosData': profilePhotoArray},
function(data) {
alert(data);
});
});
The if, else if, else section works fine as I can see the alerts.
When I try to alert the array length 'profilePhotoArray' it says 0 so I'm not populating the array correctly. Do I need to use .push()? I thought this format was ok?
Also do I need to do anything to the array before sending to php via ajax?
thankyou
** edit - I'm adding "profilePhotoArray[this.id+'_'+this.id] = action;" this.id twice just to prove this words as I will pass a second variable like this... am I better to use JSON for this?
Javascript arrays use numerical index, therefore your storage is failing. Use a javascript Object to store string based keys.
var lang=new Object();
lang["foo"]="Foo";
lang["bar"]="Bar";
I have:
var apiQuizData = {'ect stuff removed...',answers:{}};
$.each(dataCEActiveQuiz.quiz_data, function(index, answer) {
if(answer.selected == undefined){
apiQuizData.answers[answer.id] = 0;
} else {
apiQuizData.answers[answer.id] = answer.selected;
}
});
$.post(URL, apiQuizData, function(data) {
If I look at the form data submitted through the header via chromes inspect tools it shows:
// url decoded
answers[28194]:112768
answers[28195]:112773
answers[28199]:112788
answers[28202]:112803
answers[28204]:112809
// url encoded
answers%5B28194%5D:112768
answers%5B28195%5D:112773
answers%5B28199%5D:112788
answers%5B28202%5D:112803
answers%5B28204%5D:112809
// query string
answers%5B28195%5D=112773&answers%5B28199%5D=112788&answers%5B28202%5D=112803&answers%5B28204%5D=112809
In PHP I use
$sent_data = file_get_contents('php://input');
$sent_data_decoded = json_decode($sent_data, true);
the string that php receives is
&answers=&answers=&answers=&answers=&answers=
What do I need to do to the data so that it goes through to php with the values?
Thanks.
=================
UPDATE 1
If I use
$.post(URL, JSON.stringify(apiQuizData), function(data) {
This is what is sent
{...extra stuff...,"answers":{"28195":"112773","28199":"112791","28201":"112796","28202":"112800","28204":"112810"}}
From PHP using json_decode(file_get_contents('php://input'), true);
{...extrastuff...}id%22%3A952077%2C%22answers%22%3A%7B%2228195%22%3A%22112
When I do a print_r of the data it is an empty array?
=================
UPDATE 2 - Working
Updated the jquery post to
$.post(URL + 'sendCEQuizResults', {jsonstringify: JSON.stringify(apiQuizData)}, function(data) {
Updated the php receiving code to handle the new way I am sending data with the old way
$sent_data = file_get_contents('php://input');
if(substr($sent_data, 0, 13) == 'jsonstringify')
{
parse_str($sent_data);
$sent_data_decoded = json_decode($jsonstringify, true);
} else
{
$sent_data_decoded = json_decode($sent_data, true);
}
For some reason it would not work if I didn't assign the JSON.stringify(apiQuizData) into the value of another object. The browser seemed to choke on the text by itself, I guess because it was a huge text string by itself? not sure. Either way the above update #2 solved the issues I was having.
Thanks.
Stringify the object into a JSON string:
$.post(URL, JSON.stringify(apiQuizData), function(data) {
Before I answer your question I would like to encourage you to follow the "Ask Question" recommendations in order to facilitate people willing to help you all they need to know to answer your question. Yours has been too ambiguous and I came to understand what you need with some difficulty.
You may want to use php parse_str function for this:
<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first; // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz
parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz
?>
I have the following javascript loop which correctly alerts the value I need to use in a Codeigniter method. Here is the js loop:
function myInsert(){
$('input[name=r_maybe].r_box').each(function(){
if( $(this).prop('checked') ){
// need to replace this alert with codeigniter method below
alert ($(this).prop('value'));
}
});
}
Instead of alerting the required value, I need to somehow execute this Codeigniter method:
//this would never work because it mixes JS with PHP, but I need a workaround
$this->appeal_model->myMethod($(this).prop('value'), 888, 999);
Is there someway that I can run this PHP code inside the javascript loop? I know about PHP being server-side and JS being client-side, but I'm sure there must be a solution to my problem that I'm just not aware of yet. Thanks.
The solution to this is to make an ajax call to the server, you can have a method on your controller which calls your codeigniter method. This divides your php call and your client side call.
If you are inserting something into the database, you should use the ajax post method.
http://api.jquery.com/jQuery.post/
function myInsert() {
$('input[name=r_maybe].r_box').each(function(){
if( $(this).prop('checked') ){
var value = $(this).prop('value');
$.post("controllername/functionname", { value: value }, function(data) {
alert(data); // Returned message from the server
});
}
});
}
Use ajax to store data to the server side:
The code should be something like this:
function myInsert(){
$dataArray=[];
$('input[name=r_maybe].r_box').each(function(){
if( $(this).prop('checked') ){
// need to replace this alert with codeigniter method below
dataArray.push($(this).prop('value'))
}
});
if(dataArray.length>0)
{
$.ajax({
url:"your file name",//this file should contain your server side scripting
type:"POST",
data:{dataName : dataArray}
success:function(){
}
});
}
}
you can use $.post from jquery
function myInsert(){
$('input[name=r_maybe].r_box').each(function(){
if( $(this).prop('checked') ){
$.post('<?php echo site_url("controllerName/functionName")?>',
{"post1": $(this).prop('value'), "post2":888, "post3": 999 },
function(data.res == "something"){
//here you can process your returned data.
}, "json"); //**
}
});
}
In your controller you can have:
function functionName()
{
//getting your posted sec token.
$post1 = $this->input->post('post1');
$post2 = $this->input->post('post2');
$post3 = $this->input->post('post3');
$data['res'] = "something";// return anything you like.
// you should use json_encode here because your post's return specified as json. see **
echo json_encode($data); //$data is checked in the callback function in jquery.
}
Since this will be dumping data directly into your db, make sure this is secured in some manner as well, in terms of who has access to that controller function and the amount of scrubbing/verification done on the data being passed.
i'm a little stuck with a jQuery. At the moment my function looks like this.
$(function(){
$(".url2").keyup(validNum).blur(validNum);
function validNum() {
var initVal = $(this).val();
outputVal = initVal.replace(/(https?:\/\/)?(www.)?[0-9A-Za-z-]{2,50}\.[a-zA-Z]{2,4}([\/\w\-\.,#?^=%&:/~\+#]*[\w\-\#?^=%&/~\+#]){0,250}(\s){1}$/
,"http://my.site/ref.php?id=<?php $code = unqiue-ref-id(); echo $unqiue-ref-id;?>");
if (initVal != outputVal) {
$(this).val(outputVal);
return false;
}}
});
So right now it rewrites a user typed url (in a textarea) to a redirection link with my own url (e.g. my.site?ref.php?id=unique12. What I need exactly is a POST Request to a php file (code below) where the valid user-url is given to the php file as a var and then the php file should give back a var with the generated unique unique-ref-id. I do of course know that the code above isn't working like that, it only shows how the final result should look like. The php file wich generates the unique-ref-id looks like this.
function unqiue-ref-id() {
$unqiue-ref-id = "";
$lenght=4;
$string="abcdefghijklmnopqrstuvwxyz123456789";
mt_srand((double)microtime()*1000000);
for ($i=1; $i <= $lenght; $i++) {
$shorturl .= substr($string, mt_rand(0,strlen($string)-1), 1);
}
return $unqiue-ref-id;
}
$user-url = // var send from jquery
do{
$unqiue-ref-id = unqiue-ref-id();
} while(in_array($unqiue-ref-id, $result));
// var send back to jquery function => final results of do function above
// Here i add the $user-url and $unique-ref-id to datebase (Dont need code for that)
?>
Would be so great if someone can help me out with that. Thanks a lot :)
Use the POST jQuery's method. Here's an example
$.post('URL-TO-POST-DATA', {'parameter1': 'value', 'parameter2': 'value'}, function(data_received){
/** Here goes your callback function **/ alert(data_received);
});
More information about POST method
Don't forget one thing. jQuery will not receive nothing if you don't use echo on PHP (instead of return). You MUST use echo in PHP, don't forget it.