-
Posts
24,337 -
Joined
-
Last visited
-
Days Won
795
Posts posted by Barand
-
-
23 minutes ago, webdeveloper123 said:
header('Content-Type: application/json');
Try it without the above line.
Specifying the call type as "JSON" has always sufficed for me.
-
It won't be a million miles out. Try changing the last line of my code to
$result = json_encode(array_values($categories));
-
Remember that all output from a script called by AJAX or fetch becomes part of the response that is returned.
If a JSON response is expected then only json data should be output.
-
Start by removing the echo ...print_r() so it isn't included in the response (which is supposed to be JSON)
-
Try
$categories = []; foreach ($res as $r) { if (!isset($categories[$r['id']])) { $categories[$r['id']] = [ 'catid' => $r['id'], 'catname' => $r['name'], 'videos' => [] ]; } $categories[$r['id']]['videos'][] = [ 'vidname' => $r['fname'], 'vidthumbnail' => $r['fthumbnail'], 'vidid' => $r['fid'], 'vidlink' => $r['flink'] ]; } $result = json_encode($categories);
-
-
6 minutes ago, Adamhumbug said:
let fdata = $(this).serialize() + "&ajax=addNewZones";
Yes.
That is what I was going to suggest if you didn't want to use the hidden field approach. That way you send just a single querystring which will be handled automatically to create the $_POST array
12 minutes ago, Adamhumbug said:How does one go about looping through this array to insert it into the DB but only when a zone name is present.
Perhaps
$stmt = $pdo->prepare("INSERT INTO mytable (zoneType, zoneName, printValue) VALUES (?,?,?)"); foreach ($_POST['zoneName'] as $k => $zn) { if ($zn) { $stmt->execute([ $_POST['zoneType'][$k], $zn, $_POST['printValue'][$k] ]); } }
- 1
-
Your POST array looks like this, as you separate the "ajax" value from the serialized data in your JSON string...
Array ( [ajax] => testdata [data] => zoneType%5B%5D=1&zoneName%5B%5D=aa&printValue%5B%5D=1&zoneType%5B%5D=1&zoneName%5B%5D=bb&printValue%5B%5D=2&zoneType%5B%5D=1&zoneName%5B%5D=cc&printValue%5B%5D=3 )
With my code, where only the serialized form data is sent (which includes the "ajax" value from a hidden form field) it looks like this...
Array ( [ajax] => testdata [zoneType] => Array ( [0] => 1 [1] => 1 [2] => 1 ) [zoneName] => Array ( [0] => aa [1] => bb [2] => cc ) [printValue] => Array ( [0] => 1 [1] => 2 [2] => 3 ) )
-
I think you $zonearray as a string. Try your $params instead.
-
10 minutes ago, Adamhumbug said:
Once the data has been sent into PHP function. Do i need to unserialise it to insert it?
No. The $_POST array will be the same as if the form had been submitted
-
Here's a sample script
<?php ## ## HANDLE AJAX REQUEST ## if (isset($_POST['ajax'])) { if ($_POST['ajax']=='testdata') { exit('<pre>' . print_r($_POST, 1) . '</pre>'); // JUST RETURNS THE ARRAY OF POSTED DATA FOR DISPLAY } exit(); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Example</title> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script type='text/javascript'> $(function() { $("#form1").submit(function(ev) { ev.preventDefault() let fdata = $(this).serialize() console.log(fdata) $.post( "", fdata, function(resp) { $("#test-output").html(resp) }, 'TEXT' ) }) }) </script> </head> <body> <form id='form1'> <input type='hidden' name='ajax' value='testdata'> <div class="col"> <label for="zoneType" class="form-label">Zone Type</label> <select name="zoneType[]" class="form-select zoneType"> <option value="1">Normal Zone</option><option value="2">Special Zone</option> </select> </div> <div class="col"> <label for="zoneName" class="form-label">Zone Name</label> <input type="text" class="form-control simple-string zoneName" name="zoneName[]"> </div> <div class="col"> <label for="printValue" class="form-label">Print Value</label> <input type="text" class="form-control simple-string printValue" name="printValue[]"> </div> <br> <div class="col"> <label for="zoneType" class="form-label">Zone Type</label> <select name="zoneType[]" class="form-select zoneType"> <option value="1">Normal Zone</option><option value="2">Special Zone</option> </select> </div> <div class="col"> <label for="zoneName" class="form-label">Zone Name</label> <input type="text" class="form-control simple-string zoneName" name="zoneName[]"> </div> <div class="col"> <label for="printValue" class="form-label">Print Value</label> <input type="text" class="form-control simple-string printValue" name="printValue[]"> </div> <br> <div class="col"> <label for="zoneType" class="form-label">Zone Type</label> <select name="zoneType[]" class="form-select zoneType"> <option value="1">Normal Zone</option><option value="2">Special Zone</option> </select> </div> <div class="col"> <label for="zoneName" class="form-label">Zone Name</label> <input type="text" class="form-control simple-string zoneName" name="zoneName[]"> </div> <div class="col"> <label for="printValue" class="form-label">Print Value</label> <input type="text" class="form-control simple-string printValue" name="printValue[]"> </div> <br> <input type='submit'> </form> <div id='test-output'> </div> </body> </html>
[edit]...
NOTE - your form's input fields need name attributes
-
18 minutes ago, Adamhumbug said:
Should probably have included in the previous post.
Yes. Instead of saying this...
1 hour ago, Adamhumbug said:The database connection comment was more about each function having to establish a connection and send a query to the database
-
Whichever approach you use, do NOT connect to the database inside every function. Connect once to the db at start of each script and pass the connection to the functions. (The connection is the slowest part of the process)
So the function calls are
getFirstName($pdo, $id)
getLastName($pdo, $id)
getEmail($pdo, $id)
getDietary($pdo, $id)
getX($pdo, $id)I'd go with a single function
$user = getUserData($pdo, $user_id); // get an array containing the user data if ($user) { $fullname = $user['firstname'] . ' ' . $user['lastname']; // use array elements as required } function getUserData($pdo, $id) { $res = $pdo->prepare("SELECT firstname , lastname , email , diet , gender , x , y , z FROM user WHERE id = ? "); $res->execute([$id]); return $res->fetch(); }
-
Post the output from...
echo $sql;
-
52 minutes ago, Adamhumbug said:
Is this how i should be structuring all of my queries to interact with the database?
Only when you need to report an error that the user can do something about (like duplicates).
Most DB errors are beyond user control so I don't bother with try..catch and just let php handle the error
- 1
-
I wouldn't waste time on the first SELECT query.
Place a UNIQUE key constraint on the email column then
function createNewUser($pdo, $fname, $lname, $email, $password) { try { $sql2 = "INSERT INTO user (fname, lname, email, password) VALUES (:fname, :lname, :email, :password)"; $hashedPwd = password_hash($password, PASSWORD_BCRYPT); $stmt = $pdo->prepare($sql2); $stmt->execute([ ':fname' => $fname, ':lname' => $lname, ':email' => $email, ':password' => $hashedPwd ]); return 'User Created'; } catch (PDOException $e) { if ( str_contains($e->getMessage(), '1062 Duplicate entry')) { return "That email already exists"; } else throw $e; } }
-
An insert query works better if your sql informs the server
- it's an INSERT query
- which table to insert into
so needs to begin with "INSERT INTO tablename..."
Also, string literals like $imageName need to be inside single quotes. However you should be using a prepared statement.
I would also advise storing your image files in the filesystem and putting the metadata (such as filename) in the table.
-
I don't fancy the chances of sorting your files by the dates embedded in their names.
Instead, get the filenames, get the date of each file, store in array, then sort the dates.
$files = glob("$dir/*.*"); $fdates = []; foreach ($files as $f) { $fdates[basename($f)] = date('Y-m-d',filemtime($f)); } asort($fdates); echo '<ul>'; foreach ($fdates as $fn => $dt) { echo "<li>$dt – $fn</li>"; } echo "</ul>";
Results wil look something like this
-
If you want help sorting an array we need to know what that array looks like. Post the output from ...
echo '<pre>' . print_r($files, 1) . '</pre>';
-
1 minute ago, Makariuzz said:
I have so much to learn about php
Me too. Welcome.
- 1
-
Aside from the empty WHERE clause mentioned by @gizmola above, you may also have a problem with passing your limit and offset parameters.
You don't show us the relevant connection and execution code, but If your PDO connection code does not set ATTR_EMULATE_PREPARES to false (the default is true) then you cannot pass the limit and offset as parameters in an array when executing. You can, however, pass them using bindParam()
You should always set this attribute to false
- 1
-
current ------- X 100 = percent full
-
I have edited it for you this time.
- 1
-
When posting code, please use the button to place the code in a code block. (One copy of the code will suffice)
- 1
Error fetching booked seats: SyntaxError: Unexpected token '<', "<br />
in Javascript Help
Posted
How are you handling the reponse to make them red?