Passing array with Ajax to PHP script results in empty post - javascript

I want to pass an array from a HTML site to a PHP script using AJAX
JS
function selectPictures() {
//selected Pictures is my JS array
var jsonArray = JSON.stringify(selectedPictures);
var request;
request = $.ajax({
url: "selectedPictures.php",
type: "POST",
data: {
data: jsonArray
},
cache: false
success: function () {
alert('OK');
}
});
}
HTML
href="selectedPictures.php" onclick="selectPictures();"
PHP
if (isset($_POST['data'])) {
$data = json_decode(stripslashes($_POST['data']));
foreach($data as $d) {
echo $d;
}
}
Actually I want to send the data to another HTML page and then include the PHP script, but I don't understand why this example does not even work. The $_POST['data'] is not set.
UPDATE
Ok, the Ajax post is actually working, as I see the HTTP request is successful BUT: I cannot access the variable instantly. I need to access the values of the passed array at once to execute another PHP script. When I want to do this, I get an undefined index error. Also at the time when the isset function is executed, it returns false (despite the successful HTTP request).

HTML
click
JS
$(function(){
$('#selectPictures').click(function(){
var jsonArray = JSON.stringify(selectedPictures);
var request = $.ajax({
url: "selectedPictures.php",
type: "POST",
data: {data: jsonArray},
cache: false,
success: function(data){alert(data);}
});
});
});
Use f12 in chrome to see errors, you forgot to add a comma after the "cache: false"

Related

How to can I print an array transferred from javascript to php from $_POST

I am trying to transfer a javascript array to a php array and I used the following code in my php file to do so:
var rowArr=[];
var currow=$(this.closest('tr'));
var col1=currow.find('td:eq(0)').text();
rowArr.push(col1);
var col2=currow.find('td:eq(1)').text();
rowArr.push(col2);
var col3=currow.find('td:eq(2)').text();
rowArr.push(col3);
var myJSONText = JSON.stringify( rowArr );
$.ajax({
type: "POST",
url: "jsonRecieve.php",
data: { emps : myJSONText},
success: function() {
alert("Success");
}
});
so when I run this code, I get the success alert but I am not seeing any of the array elements being printed out. I am also not getting any error messages.Here is my jsonRecieve.php:
<?php
$rowAr=$_POST['emps'];
print_r($rowAr);
?>
is there a way to verify that it has been transferred? I don't believe it has but if it hasn't can someone help?
Seems you need to decode the json string with json_decode() to get your emps value on the server side and to alert the server response need to send something from the server. Let's debug this way-
ON JS
$.ajax({
type: "POST",
url: "jsonRecieve.php",
data: { emps : myJSONText},
success: function(data) {
alert(data); // alert your data to see that returns from server
}
ON PHP
<?php
$rowAr=$_POST['emps'];
$array = json_decode($rowAr,1); // 2nd params 1 means decode as an array
print_r($array);
die('response from the server');
?>

Header PHP not working after AJAX call from Javascript

so, this is probably a dumb question, but is it possible to execute the header function in a php file if I'm getting a response with AJAX?
In my case, I have a login form that gets error codes from the PHP script (custom error numbers hardcoded by me for testing) through AJAX (to avoid reloading the page) and alerts the associated message with JS, but if the username and password is correct, I want to create a PHP cookie and do a redirect. However I think AJAX only allows getting data, right?
This is my code:
JS
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
var responseCode = parseInt(response);
alert(codes[responseCode]);
}
});
PHP
if(empty($user)){
echo 901;
}else{
if(hash_equals($user->hash, crypt($password, $user->hash))){
setCookie(etc...); //this is
header('admin.php'); //what is not executing because I'm using AJAX
}else{
echo 902;
}
}
Please sorry if the question doesn't even make sense at all but I couldn't find a solution. Thanks in advance!
EDIT: I did not include the rest of the code to avoid complicating stuff, but if you need it for giving an anwser I'll add it right away! (:
You're right, you can't intermix like that. The php would simply execute right away, since it has no knowledge of the javascript and will be interpreted by the server at runtime, whereas the js will be interpreted by the browser.
One possible solution is to set a cookie with js and redirect with js as well. Or you could have the server that receives the login request set the cookie when the login request succeeds and have the js do the redirect after it gets a successful response from the server.
You can't do like that because ajax request process in backed and return the particular response and if you want to store the cookies and redirect then you should do it in javascript side while you get the response success
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
var responseCode = parseInt(response);
alert(codes[responseCode]);
window.location = "admin.php";
}
});
if(empty($user)){
setCookie(etc...); //this is
echo 901;
}else{
if(hash_equals($user->hash, crypt($password, $user->hash))){
echo response// what every you want to store
}else{
echo 902;
}
}
If the ajax response satisfies your condition for redirection, you can use below:
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
var responseCode = parseInt(response);
alert(codes[responseCode]);
window.location="%LINK HERE%";
}
});
It's kind of ironic that you use ajax to avoid loading the page, but you'll be redirecting in another page anyway.
test sending data in json format:
Javascript
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
if(response.success){
window.location="%LINK HERE%";
}else{
var responseCode = parseInt(response.code);
alert(responseCode);
...
}
}
});
PHP
header("Content-type: application/json");
if(empty($user)){
echo json_encode(['success' => false, 'code' => 901]);
}else{
if(hash_equals($user->hash, crypt($password, $user->hash))){
echo json_encode(['success' => true, 'data' => response]);
}else{
echo json_encode(['success' => false, 'code' => 902]);
}
}

AJAX not coming up a success even though its updating the database

My php is updating the table but not refreshing in javascript have tried several different ways of doing this and nothing is working.
PHP
$sql = "UPDATE INTOXDM.ASTP_FORM SET SUPERVISOR_EID = '".$newSuper."' WHERE FORMID = '".$formId."'";
$row = $xdm->fetch($sql);
$return["color"] = $row['APPRENTICE_SIGNATURE'];
$return["json"] = json_encode($return);
echo json_encode($return);
?>
Javascipt
var data = {
"formId": formID,
"newSuper": newSuper
};
data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
success: function() {
location.reload();
}
});
I'd start by modifing the code like this:
var data = {
"formId": formID,
"newSuper": newSuper
};
// No need for serialization here,
// the 'data' parameter of jQuery.ajax accepts JS object
// data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
// As suggested by Rocket Hazmat, try to add an error callback here
error: function(jQueryXHR, textStatus, errorMessage) {
console.log("Something went wrong " + errorMessage);
},
success: function(jsonResponse) {
// Try to reference the location object from document/window
// wd = document or window as seen here http://stackoverflow.com/questions/2624111/preferred-method-to-reload-page-with-javascript
// Also watch out, usually browsers require a user confirmation before reloading if the page contains POST data
// One of these should be fine
wd.location.assign(wd.location.href) : go to the URL
wd.location.replace(wd.location.href) : go to the URL and replace previous page in history
wd.location.reload(<true/false/blank>) : reload page from server/cache/cache
}
});
Also, this might be a shot in the dark but the parameter dataType gave me problems sometime in the past, so if you are sure about the json returned by your php script, you could use the eval function to jsonify the response
$.ajax({
...
// Remove data type
// dataType: "json",
...
success: function(plainTextResponse) {
// Eval response, NOT SAFE! But working
var jsonResponse = eval('('+ plainTextResponse +')');
...
}
});
Your ajax is expecting json data and your php is sending malformed json string. Send a correct json string and your script will work fine.
Your php json_encode should be like this:
$data = json_encode($return);
echo $data;

Ajax Error Potentially Due to Incorrect Data Object Being Passed

Hi I am new to ajax and I am attempting to pass a Json to a Database, but I am not that far yet. Currently I am attempting to be verified that the data I am passing is being done successfully. However, I always drop into the ajax error method. I will upload my code and the way the data looks and then the error.
Thank you for your help!
<script>
function updateTable()
{
alert("Do i try to update table?");
document.getElementById("testLand").innerHTML = "Post Json";
//echo new table values for ID = x
}
function popupClick (){
var popupObj = {};
popupObj["Verified_By"] = $('#popupVBy').val();
popupObj["Date_Verified"] = $('#popupDV').val();
popupObj["Comments"] = $('#popupC').val();
popupObj["Notes"] = $('#popupN').val();
var popupString = JSON.stringify(popupObj);
alert(popupString);
$.ajax({
type: "POST",
dataType: "json",
url: "popupAjax.php",
data: popupObj,
cache: false,
success: function(data)
{
alert("Success");
updateTable();
},
error: function(data)
{
alert("there was an error in the ajax");
alert(JSON.stringify(data));
}
});
}
</script>
JSON Being Passed shown in var popupString:
Error:
popupAjax.php file (warning it's testy)
<?php
echo "Testing tests are testy";
?>
You are specifying the dataType as json. But this is the returned data type, not the type of the data you are sending.
You are returning html / text so you can just remove the dataType line:
type: "POST",
url: "popupAjax.php",
If you do want to return json, you need to build your datastructure on the server-side and send it at the end. In your test-case it would just be:
echo json_encode("Testing tests are testy");
But you could send a nested object or array as well.
As an additional note, you can use .serialize() on your form (if you use a form...) so that jQuery automatically builds an object that you can send in the ajax method. Then you don't have to do that manually.

load view using ajax symfony2

I'm very new to symfony2 and I'm getting some problems to load a view using ajax when the user clicks on a div. Using firebug I can see the data is returned but I can not append the result in the page.
My Code:
//Default Controller
public function indexAction($num, Request $request)
{
$request = $this->getRequest();
if($request->isXmlHttpRequest()){
$content = $this->forward('PaginationBundle:Default:ajax');
$res = new Response($content);
return $res;
}
return $this->render('PaginationBundle:Default:index.html.twig', array('num' => $num));
}
public function ajaxAction()
{
return $this->render('PaginationBundle:Default:page.html.twig');
}
}
My Js:
When clicking on #target, I'd like to load page.html.twig in my div
$("div#target").click(function(event){
t = t +1;
$.ajax({
type: "POST",
cache: "false",
dataType: "html",
success: function(){
$("div#box").append(data);
}
});
});
I'm using isXmlHttpRequest() in my controller to detect if it's an ajax request to load ajaxAction. I get that view on firebug but it's not appended in my div#box. div#box exists in index.html.twig
Thanks everybody in advance
In your
$("div#target").click(function(event) event you didn't specify the url parameter in ajax call, and another thing is you must specify an argument inside the 'success'
parameter of ajax call.
$("div#target").click(function(event){
t = t +1;
$.ajax({
type: "POST",
url: "{{path('yourpath-means header name in routing.yml')}}",
cache: "false",
dataType: "html",
success: function(result){
$("div#box").append(result);
}
});
});
Hope this helps...
Happy coding
This has nothing to do with symfony but with your ajax options. Pece is right though: You can use the return from §this->forward directly as it is a Response object.
The problem lies within your ajax options. You must pass the data object within your inner function or data is simply null. Try this:
success: function(data){
$("div#box").append(data);
}
I don't get your forward to treat AJAX call. Try this :
if($request->isXmlHttpRequest()){
return $this->forward('PaginationBundle:Default:ajax');
}
Controller::forward() already returns a Response object ;)

Categories

Resources