2

I have the following $ajax code which is meant to send an array with 'title' and 'name' keys populated with data to script.php. This script creates a new instance of a 2D array, and adds it to an existing multidimensional array with the 'name' as the key.

However the script.php is not reading the $newTitle & $newName being sent from the ajax.

I'm sure it's something easy - I am very new to PHP and jQuery.

javascript:

$.ajax({
    data: {title: 'this', name:'testthis'},
    url: 'script.php',
    method: 'POST',
    success: function(msg) {
        alert(msg);
    }
});

script.php:

//load the existing array into memory
$newLogins =json_decode(unserialize(file_get_contents("config.data")),true);
// get the data from ajax
$newTitle = $_POST["title"];
$newName = $_POST["name"];
//create a new instance of the example array
$addNew = array(
     'password' => 'pw',
     'title' => $newTitle,
     'emails' => array('[email protected]'));
//add the new array to the existing array with 'name' as key
$newLogins[$newName] =$addNew;
//save it
file_put_contents("config.data", serialize(json_encode($newLogins)));
//send it back to ajax
echo json_encode($newLogins);

EDIT

Added HTML file below:

<?php
$thisLogins = json_decode(unserialize(file_get_contents("config.data")),true);
?>
<head>
<script src="../libs/jquery.min.js"></script>
<script src="../libs/jquery-ui.min.js"></script>
</head>
<table id="tableId" border=1>
<thead>
    <tr>
    <th> Project Login</th>
    <th> Project Name</th>
    </tr>
    </thead>
<tbody>
<?php foreach( $thisLogins as $name => $infos ): ?>
    <tr>
        <td><?= $name ?></td>
        <td><?= $infos["title"]?></td>
        <td><button>Delete</button></td>
    </tr>

<?php endforeach; ?>
</tbody>
</table>

<script type="text/javascript"> 

$.ajax({
    data: {title: 'this', name:'testthis'},
    url: 'script.php',
    method: 'POST',
    success: function(msg) {
        alert(msg);
    }
});
</script>

What I'm getting is for output:

"":{"password":"caps","title":null,"emails":["[email protected]"]}}
3
  • 1
    This appears to be working just dandy. I'm getting this output: {"testthis":{"password":"pw","title":"this","emails":["[email protected]"]}}. Does your JS console provide any clues? Commented Aug 11, 2015 at 21:11
  • 1
    Assuming that it's just a few lines, show us the HTML. Are you sure you've got JQuery on the page-- see HPierce's comment. Commented Aug 11, 2015 at 21:39
  • 1
    I added the HTML files. There is no JS console warnings etc on Firefox. Added my output as well Commented Aug 12, 2015 at 20:24

1 Answer 1

2

In order to read data from JSON output, its best if you set content header to JSON in script.php. it will make output perfect for $.ajax function to be easily readable, for example... header('Content-Type:application/json;');

Also remove unnecessary comma in $.ajax function in JavaScript, just for caution need to run the JavaScript code after after the link of jquery.

You can use conditioning in PHP for checking whether there is an empty input or not from JavaScript. For Example...

<?php
if(!empty($_POST["title"]) && !empty($_POST["name"])){
$newTitle = $_POST["title"];
$newName = $_POST["name"];
/****** process your code here ******/
//create a new instance of the example array
 $addNew = array(
  'password' => 'pw',
  'title' => $newTitle,
  'emails' => array('[email protected]'));
  //add the new array to the existing array with 'name' as key
  $newLogins[$newName] =$addNew;
 //save it
 file_put_contents("config.data", serialize(json_encode($newLogins)));
 //send it back to ajax
 $output['status'] = 'true';
 $output['error'] = 'none';
 $output['newLogins'] = $newLogins;
 }
else{
$output['status'] = 'false';
$output['error'] = 'Invalid Input';
}

//Setting up proper output
header('Content-Type:application/json;');
echo json_encode($output);
?>
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for this. How would I get the ajax to read if the status was true or false?
Use this... $.post('script_url', { //Your variables here {title: 'this', name:'testthis'} }, function(data,status){ if(data['status']=='true'){ //it's done } else { /* it's not done */ } });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.