質問編集履歴

1

ajaxでの処理と遷移させたいphpファイルを追加しました。

2020/07/11 06:43

投稿

zuka3
zuka3

スコア3

test CHANGED
File without changes
test CHANGED
@@ -38,8 +38,170 @@
38
38
 
39
39
  </div>
40
40
 
41
+
42
+
43
+ //ajaxでの処理
44
+
45
+ $(".trip_button").on("click", function(event){
46
+
47
+ $.ajax({
48
+
49
+ type: "POST",
50
+
51
+ url: "get_trip.php",
52
+
53
+ data: {
54
+
55
+ "id": $(".list:first").data("list"),
56
+
57
+ "user_id": "<?php echo $_SESSION['user_id']; ?>",
58
+
59
+ "comment": $(".comment").val(),
60
+
61
+ "image" : $(".image").val()
62
+
63
+ },
64
+
65
+ dataType: "json"
66
+
67
+ })
68
+
69
+ .done(function(data){
70
+
71
+ update();
72
+
73
+ $(".comment").val(""),
74
+
75
+ $(".image").val("");
76
+
77
+ })
78
+
79
+ .fail(function(XMLHttpRequest, textStatus, errorThrown){
80
+
81
+ fail_err_msg(XMLHttpRequest, textStatus, errorThrown);
82
+
83
+ });
84
+
85
+ });
86
+
87
+
88
+
41
89
  ```
42
90
 
91
+ ```php
92
+
93
+ <?php
94
+
95
+ header("Content-type: application/json; charset=UTF-8");
96
+
97
+
98
+
99
+ date_default_timezone_set("Asia/Tokyo");
100
+
101
+      
102
+
103
+     //function.php はdb接続をする
104
+
105
+ require("function.php");
106
+
107
+
108
+
109
+ $sql = null;
110
+
111
+ $stmt = null;
112
+
113
+
114
+
115
+ $id = $_POST["id"];
116
+
117
+ $user_id = $_POST["user_id"];
118
+
119
+ $comment = $_POST["comment"];
120
+
121
+ $name = $_FILES['image']['name'];
122
+
123
+ $type = $_FILES['image']['type'];
124
+
125
+ $content = file_get_contents($_FILES['image']['tmp_name']);
126
+
127
+ $size = $_FILES['image']['size'];
128
+
129
+ $datetime = new DateTime();
130
+
131
+ $datetime = $datetime->format("Y-m-d H:i:s");
132
+
133
+
134
+
135
+ try{
136
+
137
+ $db = db_connect();
138
+
139
+
140
+
141
+ $sql = "INSERT INTO trips(id, user_id, comment,image_name , image_type ,
142
+
143
+ image_content , image_size , created_at) VALUES(null, ?, ?, ? , ?, ?, ?, ?)";
144
+
145
+ $stmt = $db->prepare($sql);
146
+
147
+ $stmt->execute( array($user_id, $comment, $name, $type, $content, $size, $datetime) );
148
+
149
+
150
+
151
+ $sql = "SELECT * FROM trips WHERE id>? ORDER BY created_at DESC";
152
+
153
+ $stmt = $db->prepare($sql);
154
+
155
+ $stmt->execute( array($id) );
156
+
157
+
158
+
159
+ $content = array();
160
+
161
+ while( $row = $stmt->fetch() ){
162
+
163
+ $content[] = array(
164
+
165
+ "id" => $row["id"],
166
+
167
+ "user_id" => $row["user_id"],
168
+
169
+ "comment" => $row["comment"],
170
+
171
+ "image_content" => $row["image_content"],
172
+
173
+ "created_at" => $row["created_at"]
174
+
175
+ );
176
+
177
+ }
178
+
179
+
180
+
181
+ $db = null;
182
+
183
+ echo json_encode($content);
184
+
185
+
186
+
187
+ }catch(PDOExeption $e){
188
+
189
+ echo $e->getMessage();
190
+
191
+ die();
192
+
193
+ }
194
+
195
+
196
+
197
+ ?>
198
+
199
+ ```
200
+
201
+
202
+
203
+
204
+
43
205
 
44
206
 
45
207
  わかりづらいと思いますが、よろしくお願いします。