I have a web page that sends form data to php using jQuery. I want to decode the data array and loop through it, displaying each of the four values using php print_r.
Here is the jQuery function to post the data to php:
<script type="text/javascript">
function postData() {
return $.ajax({
var datastring = $("#echo_test").serialize();
$.ajax({
type: "POST",
url: "echo_test.php",
data: {post: datastring},
});
});
}
</script>
Here is the php function echo_test:
<?php
$obj = json_decode($_POST['post']);
print_r($obj['firstname']);
?>
I think json_decode is wrong because the data posted is not json format.
When I click the button that calls the jQuery function, the php page opens in the browser but it's blank, with nothing echoed back. Ideally I would I loop through $obj to display each of the four values on the screen.
Ultimately I will post the data to Postgres on a cloud server. For now, I'm testing it locally to verify the data because I'm new to passing data to php from jQuery.
Thanks for any help with this.
What you need to do is use parse_str, but correctly:
<?php
parse_str($_POST['post'], $obj);
print_r($obj['firstname']);
?>
form.serialize() send data in query string format. The parse_str() function parses a query string into variables.
<?php
parse_str($_POST['post'], $obj);
print_r($obj);
?>
What you need to do is use parse_str:
https://php.net/manual/en/function.parse-str.php
<?php
parse_str($_POST['post'], $obj);
print_r($obj['firstname']);
?>
Related
I am recording the information using the data() method
optionScope.data().stage = 'a';
where optionScope = $(this);
where I would like to store this value in my php code:
<?php
include("functions/db.php");
$format = "Online Course";
$stage = GETTING THIS DATA;
$topic = "Idea Generation";
$resources = "select * from resources where format LIKE '".$format."' and stage LIKE '%".$stage."%' ";
$run_query = mysqli_query($con, $resources);
while($row = mysqli_fetch_array($run_query)) {
$stage = $row['stage'];
echo "$stage <br>";
}
?>
Update:
How the data is being sent
optionScope.data().stage = 'b';
$.ajax({
url: "functions/contact.php",
type: "post",
data: {stage: optionScope.data().stage}
});
How the data is being retrieved
<?php
$stage = $_POST['stage'];
echo $stage;
?>
you can use the AJAX method. This is the only way you can transfer your JS data into PHP script.you will get the Jquery data in GET or POST variables.
jQuery AJAX has the various method you can choose as per your requirement.
http://api.jquery.com/category/ajax/
You can't directly transfer data between JS and PHP (unless you use string interpolation inside <script> tags which is a big no-no), since JS deals in the client-side and PHP on the server-side.
You need to make a request to the server and then manipulate the data there.
Take a look at AJAX requests.
For the easiest implementation of this, see JQuery's AJAX method.
Is it possible to run a JavaScript function from PHP using an Ajax call.
For example, if I have a html page in php with an ajax call. The ajax post gets sent to a php engine:
index.php
<script>
Ajax.post('http://example.com/ajaxEngine.php', { data: "someData" });
</script>
Then in the PHP engine, can I run a JavaScript function like this:
ajaxEngine.php
<?php
$data = $_POST['data'];
?>
<script type="text/javascript">
var php_var = "<?php echo data ?>";
function doSomething(php_var) {
// do something with data
}
</script>
Lastly, If the JavaScript function needs to return a value, how would you then transfer that back to php? Could I post to the same page and then get it as a variable with PHP?
Short answer: No.
Your code in ajaxEngine.php would just output that snippet of javascript. This will be transfered back to your page, so you could insert it into a script tag or eval it, if you like it to execute. But this would then happen on the client side not on your server. The script would have the dynamic data from the php, though. So if this is everything you need, it would work that way.
Beware: That would NOT hide your script. It would be visible for any client.
Try this function
function includetext(text,onlyone)
{
var d=document.createElement('script');
if(onlyone)
{
var ds=document.getElementById('onlyonesscript');
if(ds)
removeElement(ds);
d.id='onlyonesscript';
}
d.innerHTML=text;
document.body.appendChild(d);
}
text - returing text of script from ajax.
onlyone use for just one script node, this will help you.
ajaxEngine.php
<?php
$data = $_POST['data'];
?>
var php_var = "<?php echo data ?>";
// do something with data
i am having the same problem as faced by many that the script tags are not executed in the jquery ajax response and i already tried the solutions with the 'eval()' method and similar but none is working.Is there any other way to accomplish this.
i am sending a ajax request to a file cart.php from home.php
HOME.php
$.ajax({
type:"POST",
url:"cart.php?action=inc&id="+id+"&value="+myvalue+"&linecost="+linecost,
cache:false,
success: function(data)
{
alert(data);
i am actually converting a php array to a javascript array inside cart.php file like this:
CART.php:
processing code here...
<?php
$res=array($val,$cost,$total);
foreach ($res as $a) {
$string .= "\"" . $a . "\", ";
$final = substr($string, 0 ,(strlen($string) - 2));
}
?>
<script>var j = new Array(<?php echo $final; ?>);</script>
Returned data at home.php inside data variable:
<script>var j = new Array("4", "2928", "6708");</script>
Now i just want the elements of this array but it is returning the whole line at the calling file inside the 'success' function..how do i extract the values at the calling file?Any help?
You want to use JSON. Instead of returning the script, you can use json_encode.
echo json_encode($final);
Then to convert the JSON back to an array you can do in JS:
var result=JSON.parse(data);
result is now a normal JS array containing the same data as in $final.
I am making a web app, where I want to provide a search function. I am sending the searched name with an ajax request, and i want to pull the records of that particular person. But since there are many details that are to be displayed, I am finding it difficult to get the response. (I am not able to get more than one response at a time)
I want to know, if there is a way to get multiple responses for a single request, or a way to send all my variables in the target PHP file to the requesting javascript file as an array or something.
Thank you. If this question is asked before, please provide the link.
Use JSON as the datatype to communicate between PHP(Backend) and Javascript(Frontend). Example:
PHP
<?
$person = array("name"=>"Jon Skeet","Reputation"=>"Infinitely Increasing");
header("Content-Type: application/json");
echo json_encode($person);
?>
Javascript/jQuery
$.ajax({
url: "your_script.php",
dataType: "JSON"
}).success(function(person) {
alert(person.name) //alerts Jon Skeet
});
Add everything you want to an array, then call json_encode on it.
$data = array();
$data[] = $person1;
$data[] = $person2;
echo json_encode($data);
So I half got jQuery's ajax ($.post) to work. But, for some reason, I haven't been successful with finding the right online article to explain to me how PHP retrieves the ajax data that is sent. I've found some stuff on json_decode, but upon me doing that to basically decode it, it wont work (and yes, I am using json for the $.post command).
Here is my javascript code
$.post("notificationNum.php", {"user":"1"},
function(data){
$(".example-number").html(data.amount);
}, "json");
Here is my PHP code
<?php
session_start();
//link to db info here
$user_id_got = json_decode($_REQUEST['user']);
$checknoti = mysql_query("SELECT * FROM notifications WHERE notification_users = '".$user_id_got."' AND notification_viewed= '0'");
echo json_encode(array("amount"=>mysql_num_rows($checknoti)));
?>
Mind you all, I've also tried using the $_POST command instead of the $_REQUEST. Any ideas how to send data to the PHP file so I can use it?
"json" in your jQuery call is how your php should write its output, not how jQuery sends it. Use normal $_REQUEST in your php:
$user_id_got = $_REQUEST['user'];
try this
notificationNum.php
<?php
//link to db info here
$user_id_got = intval($_POST['user']);
$checknoti = mysql_query("SELECT * FROM notifications WHERE notification_users = '".$user_id_got."' AND notification_viewed= '0'");
echo json_encode(array("amount"=>mysql_num_rows($checknoti)));
?>