POST a javascript objet to a PHP file - php

I try to post an JS object to PHP, but the PHP says nothing.. It looks like it don't recognize the POST...
Here is the JS :
$('.send').click(function() {
var Scommand = JSON.stringify(command);// Command is my JS obj
if (commande.type) {
$.ajax({
url:'test.php',
context:$(this),
type:'POST',
data:Scommande,
success : function(data){
commande = {};
window.location='test.php';
}
});//End Ajax
}
else {'PLz specify a type');}
});
And my PHP :
<?php
echo $_POST['type'];
?>
It returns : Notice: Undefined index: type in /Applications/MAMP/htdocs/BackOfficeDavid/test.php on line 2
Like nothing go throw the POST ... Any clue ?

Disable/remove window.location='test.php';.
What might be happening is that the success callback is called, redirecting you to the test.php after everything is actually done. This would be a plain move to test.php, by GET, so there will be no parameters in $_POST.
Actually, better yet, replace window.location='test.php'; with alert(data), so you'll see what is returned. Otherwise it will seem like nothing happened since the ajax just completes successfully and silently in the background.

The problem is that you're converting the command to a string. The data on the ajax call has to be a JSON object, not a string. What you can do is pass the command variable directly:
var command = { type: "whatever" };
$.ajax({
url:'test.php',
context:$(this),
type:'POST',
data: command,
success: function(data){
command = {};
window.location='test.php';
}
});

You probably mean
data:'type=' + encodeURIComponent(Scommande),
instead of
data:Scommande,
This will URL-encode the Scommande variable and assign its value to the type POST variable.
Alternatively, you can rely on jQuery to do that for you by using
data: {'type': Scommande},
(PS. Not sure if the variable is meant to be named Scommand or Scommande. You probably have a typo somewhere)

Related

Update Hidden Field Value Inside PHP Function

I am new to php and am trying to update a hidden field value inside a php function and can't see to find a solution that works.
In template.php I have:
<input type="hidden" id="variable_ID" name="variable_name" value="variable_value">
This works fine.
However I need to update the value of the variable to the record ID of inserted record in a function in functions.php eg
function myFunction() {
$insert_record = $mydb->query("INSERT INTO `Table`(`Name`) VALUES ('John')");
$get_record_id = $mydb->insert_id;
// *** Set Hidden field value to $get_record_id here ***
}
I have tried a myriad of things but can't seem to find a solution.
Any pointers on how to solve this problem?
Here is the solution I used - thanks to #Steven and #El_Vanja for direction.
(I may need to change the question title now though because what I actually needed to do was return a variable to javascript from PHP using Ajax. I didn't need to use hidden fields).
PHP
function myFunction() {
$insert_record = $mydb->query("INSERT INTO `Table`(`Name`) VALUES ('John')");
$get_record_id = $mydb->insert_id;
echo json_encode($get_record_id);
exit;
}
JS
jQuery.ajax({
url: ajax_url,
type:'POST',
data: {
action: "myFunction",
anydata:"to be posted"},
success: process_record_ID
});
function process_record_ID(data_returned_from_myFunction){
recordID = data_returned_from_myFunction;
}
Hope this helps others!
Notes
I believe that we have to declare 'process_record_ID' as a separate function outside of AJAX because AJAX is asynchronous. If we define the function in the success handler, the function runs in AJAX before the value is actually returned from PHP.
In the AJAX success handler, we don't need to explicitly list the 'data_returned_from_myFunction' variable in the call to process_record_ID function. When the data is returned to the AJAX success handler from PHP, it still gets sent to the function.
Additional answer
You're correct AJAX is an asynchronous construct which means that certain tasks can be carried out before you might expect them to (from a synchronous perspective).
For example we can (as per the code in the original answer) use jQuery to update the value of a field directly in the success handler.
We can't update a JS variable directly, i.e:
some_variable = response.value;
If you attempt it the variable some_variable will likely be undefined.
The difference comes down to callbacks:
Callbacks allow the asynchronous function to call a function after it completes. Where as setting a variable happens on the spot.
There are two easy ways to solve this issue then:
Create a function outside of the AJAX request and allow it to callback that function once the AJAX request has completed -- as you've already discovered.
Use the complete option inside of your AJAX request.
Using a call back
Firstly we need to define out variable to be updated and the function which we will use to update it:
var inserted_id = "";
function update_id(data){
inserted_id = data.record_id;
}
Then we can make out AJAX call:
$.ajax({
type : "POST",
url : "/url/to/functions.php",
data : {data:"to be posted"},
dataType: 'json',
success : update_id
});
N.B.
Calling update_id in this fashion means we pass the entirety of the returned JSON object; not just the returned number.
Alternatively...
var inserted_id = "";
function update_id(data){
inserted_id = data;
}
$.ajax({
type : "POST",
url : "/url/to/functions.php",
data : {data:"to be posted"},
dataType: 'json',
success : function(response){
update_id(response.record_id);
}
});
This method is effectively the same but we only pass the returned number to the update_id function.
Using complete
complete works the same way as success however activates once the AJAX request is... complete...
var inserted_id = "";
$.ajax({
type : "POST",
url : "/url/to/functions.php",
data : {data:"to be posted"},
dataType: 'json',
complete: function(data) {
inserted_id = data.responseJSON.record_id;
}
});
Original answer
Having not seen the rest of your code giving a complete answer is tricky. However, this should set you on the right track:
PHP
Firstly, in your PHP you need to make sure and output the data that you want returned to the webpage. In this case we want to return the insert id of the newly created record; to do this we're going to output a JSON object so that the AJAX call can interpret the value and update the page:
function myFunction() {
$mydb->query("INSERT INTO `Table`(`Name`) VALUES ('John')");
echo json_encode(["record_id" => $mydb->insert_id]);
exit;
}
N.B.
We don't want any output other than the JSON string. Hence exit has been used after the echo. You may want/need to adjust the echo and exit to fit with the rest of your code etc.
JS
Now that we have our PHP returning usable data to our ajax call (which should look something like the below) we can take the returned data aka response and update the value of the hidden field accordingly.
$.ajax({
type : "POST",
url : "/url/to/functions.php",
data : {data:"to be posted"},
dataType: 'json',
success : function(response) {
$("#id_of_hidden_field").val(response.record_id);
}
});

No response from PHP Script

Absolutely new to PHP and so far it isn't pretty.
Anyway, I'm trying to pass a variable over to a PHP script, do a couple things with it, and pass it back to my Javascipt code.
Here's where I pass it off to PHP:
var src=encodeURIComponent("http://www.someonlinesite.com/file.swf");
$.ajax({
url:'test.php?src='+src,
dataType:'json',
success:function(response){
alert(response)
}
});
and here's the script:
<?php
$src=isset($_GET['src'])?$_GET['src']:'';
$size=getimagesize($src);
echo json_encode(array('size'=>$size));
?>
I'm trying to pass the URL of a .SWF video file over to a small PHP script that will use getImagesize() to figure it's dimensions and pass them back.... but I'm not seeing anything in the response and the alert isn't firing.
What's going wrong?
UPDATE:
I've updated the code with the most recent - according to the advice from some nice SO members. When I hardcode the $src variable and navigate directly to the test.php it echoes everything perfectly. So, it looks like the PHP is working. However, it appears like either the callback is never firing or the PHP file isn't returning the data. In the console there still isn't anything in the response.
You need to concatenate your url string parameter in get():
$.get('test.php?src=' + src, function(data){
alert(data);
});
And also, your src variable begins with a double quote and is closed with a single quote. That will cause issues.
var src="http://www.someonelinesite.com/file.swf";
Also, it's probably a bad idea to do this via $_GET since you are passing a URL. $_POST would be better or encode the URL before you pass it. The current url you are passing right now would look like this in a browser:
http://www.mysite.com/test.php?src=http://www.someonelinesite.com/file.swf
That's not pretty. Using encodeURIComponent(), your whole URL will end up looking like this:
http://www.mysite.com/test.php?src=http%3A%2F%2Fwww.someonelinesite.com%2Ffile.swf
Edit to $.ajax
$.get above would work just fine, but going with the implementation of $.ajax works too:
$.ajax({
url:'test.php',
type: 'GET', //Add the type
dataType:'json',
data: {'src': src}, //Add the data, leave it out the url
success:function(data){
alert(data)
}
});
Try this :
In Jquery :
var src="http://www.someonelinesite.com/file.swf";
$.ajax({
url:'test.php?src='+src,
dataType:'json',
success:function(response){
alert(response.size);
}
});
In php
$src=isset($_GET['src'])?$_GET['src']:'';
$size=getimagesize($src);
echo json_encode(array('size'=>$size));
?>

JQuery Ajax call failing but service is hit

I'm not sure how to best explain this so bear with me.
I have the following in some javascript (using jQuery)
$(document).ready(function(){
$("#myForm").submit(function(){
var request = $.ajax({
url: "myPage.php", //sits on localhost
crossDomain: true,
type: "POST",
data: {
var1 : "foo",
var2 : "bar"
}
});
request.done(function(res){
alert("DONE");
});
request.fail(function(jqXHR , textStatus){
alert(textStatus);
});
}
MyPage.php uses SoapClient to call a service. And then return some data.
I can directly call MyPage.php from the webBrowser and get a result (failed because there is no POST data).
If I try to make the MyPage.php call from the AJAX and put a breakpoint in my service, I see the service being called and returning a value.
But the request.Fail ALWAYS calls. It appears that it just directly jumps to that fail before the service can even finish.
How would I remedy this?
I may be wrong but aren't you missing the colon between data and the data map? and then you should be doing key : value not key = value inside the map.
Your syntax is wrong, it should be:
data: {
var1: "foo",
var2: "bar"
}
I do not know why, but apparently changing it from
$("#myForm").submit(function(){
And moving it into function SubmitForm(){...}
and then making the call from
Fixed the whole thing. Thanks for the advice....

How to return value using ajax

I have Ajax file in which code has written to accept values form user and then these values are taken in a Ajax function as follows:
$(document).ready(function(){
$("#newsletterform").validate();
$('#Submit').click(function(){
var name = $('#newsletter_name').val();
var email = $('#newsletter_email').val();
sendValue(email,name);
});
});
The function for passing values and getting values from other file:
function sendValue(str,name){
$.post(
"newsletter/subscribe.php", //Ajax file
{ sendValue: str,
sendVal: name
},
function(data2){
$('#display').html(data2.returnValue);
},
//How you want the data formated when it is returned from the server.
"json"
);
}
and these values are passed to another file called "subscribe.php" in which insertion code to database is written and again I return the value to my first ajax function as follows:
echo json_encode(array("returnValue"=>$msg));
The msg is ging to contain my message to be displayed.
But now, this works fine on localhost, I get the return values nad message properly but when I upload it on server this gives me an error as:
data2 is null
[Break on this error] $('#display').html(data2.returnValue);
This only gives error for return value but insertion, sending mail functionality works fine.
Please provide me with a good solution wherein I can be able to get back the return values without any error.
Thanks in advance.
If it works on your development site, I suspect the error to be in your PHP script.
Your host might run an ancient php version which does not have json_encode().
Simply call the script manually to check its output. If it requires POST you could write a form or check the result to your ajax call with FireBug
Without additional explanation why this is happening, try this:
$(document).ready(function(){
$("#newsletterform").validate();
$('#Submit').click(function(e){ // added the e paramenter
var name = $('#newsletter_name').val();
var email = $('#newsletter_email').val();
sendValue(email,name);
e.stop(); // dont submit the form normaly
});
});
If you have firebug, write data2 to its console and see what it is:
function(data2) {
console.log(data2);
$('#display').html(data2.returnValue);
}
In addition, you can use firebug net panel to see your php file raw response (if it has error - you will see it there).
Use that:
var response = $.ajax({
type : "POST",
url : "newsletter/subscribe.php",
dataType : "json",
async : false,
data : "sendValue="+str+"&sendVal="+name
}).responseText;

AJAX/JQUERY/PHP issue

I am trying to use an ajax 'POST' call through the jquery $.ajax function to send data to a php file. For some reason the callback is a success but the data is not getting to the php file. Here is an example of the code:
In JS file:
$.ajax({ type: "POST",
url: "setData.php",
data: "myPOSTvar=myData"
success: function(){ alert("Data Saved"); }
});
In php file:
$var = $_POST['myPOSTvar']
...
$var ends up with a default value instead of the data it is sent.
Any ideas?
Sorry about the syntax errors...at work right now and don't have my code in front of me...the syntax is all correct in the actual script, just typed to quick when posting here...
Try this and see if you get any info.
$.post("setData.php", { myPOSTvar: "myData" },
function(data){
alert("Data saved");
});
I doubt it's a success, the url should be a string : url: "setData.php" .
I really doubt that piece of JS code is working as it should. POST and setData.php should be enclosed with quotes. Right now you should get some errors because "POST" variable is not defined and then because you're accessing a "php" property on a non existent object "setData".

Categories