AJAX submit and 500 server error - javascript

I get the 500 server error when trying to run my AJAX. I am very new to AJAX. Every thing works in the code if I run no AJAX in the script, for example just running:
$("#book-appointment-form").submit();
Therefore, it appears that all the database functions are fine. However, I need AJAX to run my code in a Wordpress page.
I do not see any notes in the error logs. The console log shows that the url is pointing to the correct location. What may I be missing?
The console log shows data within the hidden input showing up in confirmedData:
0: Object
name: "csrfToken"
value: "0f4343dfd0e71a8fa515d08f340f7bc9"
__proto__: Object
1: Object
name: "post_data"
value: "{"customer":{"last_name":"Test","first_name":"Joe","email":"email4me#verizon.net","phone_number":"9093334444","address":"","city":"","zip_code":"","id_cellcarrier":"2","wp_id":"1"},"appointment":{"start_datetime":"2015-12-25 11:00:00","end_datetime":"2015-12-25 11:50:00","notes":"","is_unavailable":false,"id_users_provider":"85","id_services":"13"},"manage_mode":false}"
__proto__: Object
length: 2
__proto__: Array[0]
VIEW:
<html>
<form id="book-appointment-form" style="display:inline-block" method="post">
<button id="book-appointment-submit" type="button">Confirm</button>
<input type="hidden" name="csrfToken" />
<input type="hidden" name="post_data" />
</form>
</html>
JS
<script>
$("#book-appointment-form").submit(function(event){
var confirmedData = $(this).serializeArray();
var dataUrl = GlobalVariables.baseUrl + '/index.php/appointments/ajax_confirm_appointment';
$.post(dataUrl, confirmedData, function(response) {
////////////////////////////////////////////////////////////
console.log('Customer Confirmed Post Response:', response);
////////////////////////////////////////////////////////////
}, 'json');
event.preventDefault();
});
$("#book-appointment-form").submit();
</script>
PHP CONTROLLER
<?php
public function ajax_confirm_appointment() {
if($_POST["post_data"]){
try {
$post_data = json_decode($_POST['post_data'], true);
$appointment = $post_data['appointment'];
$customer = $post_data['customer'];
...some database stuff here ....
} catch(Exception $exc) {
$view['exceptions'][] = $exc;
}
$this->load->view('appointments/book_success', $view);
$form_data = TRUE;
break;
} else {
$form_data = FALSE;
}
echo json_encode($form_data);
}
?>
I have tried replacing serializeArray() with serialize(). I have also tried serializeArray() converted with $.param(confirmedData)-- same results really and still it does not appear to reach the server. 500 error persists. I think serialize() may be the more appropriate one however.

I do not think it is related to Ajax. There may be problem in script that you are calling through ajax.
Try to check without ajax dataUrl
Please also check link .
http://pcsupport.about.com/od/findbyerrormessage/a/500servererror.htm

This worked:
My JS
<script>
$("#book-appointment-form").submit(function(event){
var postData = {
csrfToken: $('input[name=csrfToken]').val(),
post_data: jQuery.parseJSON($('input[name="post_data"]').val())
};
var postUrl = GlobalVariables.baseUrl + '/index.php/appointments/ajax_confirm_appointment';
$.post(postUrl, postData, function(response) {
////////////////////////////////////////////////////////////
console.log('Customer Confirmed Post Response:', response);
////////////////////////////////////////////////////////////
if (!GeneralFunctions.handleAjaxExceptions(response)) return;
}, 'json');
});
</script>
My CONTROLLER
<?php
public function ajax_confirm_appointment() {
try {
$post_data = $_POST['post_data'];
$appointment = $post_data['appointment'];
$customer = $post_data['customer'];
...some database stuff here ....
}
echo json_encode($yn_response);
}
?>
No more 500 server error.

Related

Button to change value in SQL without any redirection

Trying to use Javascript to pass the value from a button
to execute a PHP Script (The script simply changed a boolean column to 1 / True.
However i cannot get the code to work, i am not sure if its my Formatting, but i am not very familiar with Javascript
i am simply trying to change the value in the SQL Database on a column without any redirection.
index.php
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script language="javascript">
$("body").on("click","button", function(ev){
ev.preventDefault(); // prevent submitting a form ...
let data={id: $(this).data("id")}
$.post("viewed.php",data)
.done(function (result) {
console.log("Message:",result);
});
});
</script>
My Button index.php
<div><button name="Delete" data-id='<?echo $data['orderReference']?>'">Delete</button></div>
and Viewed.php
$orderID = $_POST['id'] ;
if ($_POST)
{
try {
$sqlOrderviewed = "UPDATE `Order_Header` SET `orderViewed` = '1' WHERE `Order_Header`.`orderReference` IN ($orderID) ";
$resultOrderupdate = $products->conn->query($sqlOrderviewed); // Execute Statement
echo $count = $resultOrderupdate->rowCount();
} catch
(PDOException $e) { // If error in SQL
echo "One or more errors occurred saving to database This transaction will be rolled back:" . $e->getMessage(); // Display Message on End Point
// $products->conn->rollback(); // Rollback SQL
}
}
I am aware of the SQL Injection in this example, this is not production just trying to get an example working
To do this I would suggest making REST API type behaviour in your PHP that accepts JSON (as an example) which you can define with headers. So your JavaScript can stay mostly the same, just make sure you are pointing to the correct URL. But I think your PHP should look more like this:
<?php
// Headers
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: POST'); //maybe make this an update to be Semantic with the SQL operation you are doing
// Get raw data from the post you made in JavaScript
$data = json_decode(file_get_contents("php://input"));
$id = $data.id;
// Use the data in your SQL
$sqlOrderviewed = "UPDATE `Order_Header` SET `orderViewed` = '1' WHERE `Order_Header`.`orderReference` IN ($id) ";
?>
If you need more information on creating APIs with PHP I suggest these resources:
https://www.youtube.com/watch?v=OEWXbpUMODk
https://shareurcodes.com/blog/creating%20a%20simple%20rest%20api%20in%20php
https://github.com/bradtraversy/php_rest_myblog
I am not sure that $(this).data("id") is getting the data you want. I assume you want to get the value of data-id in your button? If so I would change your JavaScript to something more like this:
<script language="javascript">
$("body").on("click","button", function(ev){
ev.preventDefault(); // prevent submitting a form ...
let id = ev.target.getAttribute("data-id");
let data={id: id};
$.post("http://localhost:{port}/viewed.php",data)
.done(function (result) {
console.log("Message:",result);
});
});
</script>
I hope this helps!
P.S this is how I might have written the JS for this, I just find it a bit more readable (Not tested, just written in the MD editor while answering the question):
let buttons = document.querySelectorAll("button");
buttons.forEach((button) => {
button.addEventListener("click", (e) => {
e.preventDefault();
let id = e.target.getAttribute("data-id");
let data = {
id: id
};
$.ajax({
type: 'POST',
url: '/viewed.php',
data: data,
success: function(result){
console.log( "result: " + result );
}
})
})
});

Submit a Form Using Jquery Ajax

Fiddle And Code:
$("form.signupform").submit(function(e) {
var data = $(this).serialize();
var url = $(this).attr("action");
var form = $(this); // Add this line
$.post(url, data, function(data) {
try {
data = JSON.parse(data);
$(.result).html(data.result + " Watchlist");
} catch (e) {
console.log("json encoding failed");
return false;
}
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="result"></p>
<form class="signupform" method="post" action="admin/signupinsert.php" onsubmit="this.onsubmit=function(){return false;}">
<input type="text" name="firstname" />
<input type="submit" value="Sign Up"/>
</form>
admin/signupinsert.php code:
// Insert into DB code in PHP
$response = new \stdClass();
$response->result = "".$result."";
die(json_encode($response));
I am trying to submit this form using My Jquery Ajax Code. And the signupinsert.php file will return a value in $result variable. I am trying to print it inside <p class="result"></p>
But, the code re-directs users to signupinsert.php page.
What's wrong?
you must prevent the default action of submitting the form
$("form.signupform").submit(function(e) {
e.preventDefault(); // <-- add this
var data = $(this).serialize();
var url = $(this).attr("action");
also, in your php file return proper JSON and avoid parsing the response in javascript with JSON.parse(data);
the output in your php file should look like this
$response = new \stdClass();
$response->result = $result;
header('Content-Type: application/json');
print json_encode($response);
and in your success handler just process the data parameter as a normal json object
$.post(url, data, function(data) {
$(.result).html(data.result + " Watchlist");
}
Also, just a curiosity, what is this supposed to do?
$response->result = "".$result."";
Update:
I just realized why you had most of the issues:
$('.result').html(data.result + " Watchlist");
^ ^
see the missing quotes
you are redirecting because of action:
action="admin/signupinsert.php"
var url = $(this).attr("action");
got me?

Trying to send a value from JS to PHP - JQuery's $.ajax() method is not working

I want to execute a JS function when a PHP form is submitted, and from that function, I want to return a value (which is based on user's input) to PHP, where I'd like to echo it.
This is an SSCCE. In the real code, there is more than just echoing the value, and the value is a JSON object.
Following is my code. The problem is that the $.ajax(); part is not working. Nothing happens in the browser after alert(name);.
Why isn't this working properly? How can I fix this?
From index.php:
<form id="form">
Name:
<input id="name" type="text" />
<input type="Submit" value="Go" />
</form>
From scripts.js:
$(document).ready(function() {
$("#form").submit(function(event) {
event.preventDefault();
var name = $("#name").val();
alert(name);
$.ajax({
type:'POST',
url:'echo.php',
data: {
nameEntered : name
}
});
});
});
echo.php:
<?php
if ( isset($_POST["nameEntered"]) && !empty($_POST["nameEntered"]) ) {
echo $_POST["nameEntered"];
} else {
echo '$_POST["nameEntered"] is not set.';
}
?>
EDIT:
Console:
Network:
EDIT 2:
Added the following to $.ajax():
,
success: function(){
alert("success");
},
error : function(){
alert("error");
}
I get an alert saying success but the browser NEVER directs to echo.php =s
EDIT 3:
After the alert saying success, a ? is added to the URL in the browser. Initially the URL was http://localhost/Test12/index.php and it changed to http://localhost/Test12/index.php?.
This way should show response.
JAVASCRIPT
$("#form").submit(function(event) {
event.preventDefault();
var name = $("#name").val();
//alert(name);
$.ajax({
type:'POST',
url:'http://localhost/Test12/echo.php',
data: {
nameEntered : name
},
success : function(data){
console.log(JSON.parse(data));
},
error : function(error){
console.log('erro', error);
}
});
});
PHP
<?php
if (isset($_POST["nameEntered"]) && !empty($_POST["nameEntered"])) {
$name = array("nome" => $_POST["nameEntered"]);
echo json_encode($name);
} else {
echo '$_POST["nameEntered"] is not set.';
}
?>
As a test, replace your echo.php with:
<?php
echo 'Incoming = ' .$_POST["nameEntered"]. "/r/n";
if (isset($_POST["nameEntered"]) && !empty($_POST["nameEntered"])) {
echo 'Here 01';
} else {
echo 'Here 02';
}
?>
Try removing the document.ready() or instead of .submit use .on('submit', function(e){}); or add absolute path '/page.php'
I think you need to add "event" as parameter in your submit function, in addition to the success call to show results
What does this give you:
$.ajax({
type:'POST',
url:'echo.php',
data: {
nameEntered : name
},
success: function(recd){ // <-------
alert(recd); // <-------
},
error : function(){
alert("error");
}
});
You're calling event.preventDefault(), but you've failed to add the event to your callback's parameters... so you're not actually stopping the form from being submitted. That is why you see the question mark in the address bar.
Try:
function(e){
e.preventDefault();
};

Create a loop to call php function and echo from that function on same html page in javascript

I am trying to create a simple webapp sort of thing that will send push notifications to my clients on button click. Here is a sample page that i have created
I have a file named as sendPush.php
On button click i want to send a push notification which will be echoed as
Notifications sent:
"Notification sent to userId : xxxX"
"Notification sent to userId : xxxX"
"Notification sent to userId : xxxX"
"Notification sent to userId : xxxX"
I want to send notifis to all 147 users. Now here is my php code for button click
<script type="text/javascript">
function sendNotif()
{
alert('ok');
}
</script>
<div class="content">
<input type="button" value="Click to Send" onClick="sendNotif();">
<br />
<br />
<label for="push">Notifications sent: </label>
</div>
The problem here i am facing is, i have php function in same app named as sendNotification() that will send notification and echo the result. But I am not sure how can i make a loop of this php function in javascript inside javascript function
function sendNotif()
{
// LOOP HERE
}
If $clients is the list of my clients, how can i send notif to all in a loop using php function in same page as sendNotification($client)
MOdified
<script type="text/javascript">
var lastIdCount = 0;
function sendNotif()
{
var clients = "<?php echo $clients; ?>";
var getPath = "push.php?clientId=".concat(clients['lastIdCount']);
$.ajax({
type: "POST",
url: getPath,
task: "save",
data: {
ajax: "true",
},
dataType : 'json'
}).done(function( msg )
{
alert('ok');
if( msg.status=="1")
{
alert('okasdf');
lastIdCount++;
sendNotif();
}
else
{
alert("Error : "+msg.error);
}
});
}
</script>
In push.php
sample
$resp = array();
$resp['error'] = 'Invalid Request';
$resp['status'] = '0';
$resp['data'] = '0';
You can try first to get all clients you want to send notification and use them ID's for setInterval or setTimeout functions which would repeat your queries. Probably you should
get_clients.php
<?php
$clients_array = array(1,2,6,15,29); /// let's say ID's you got from SQL or w/e you need.
echo json_encode($clients_array); // [1,2,6,15,29]
?>
send_for_client.php
<?php
$id = isset($_POST['id'])?$_POST['id']:false;
if($id){
// do some code you need
echo "Notification sent for id: ".$id;
}
?>
index.html
...
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(window).load(function(){
$("#send").click(function(){
$.post('get_clients.php',{},function(cid){
obj = JSON.parse(cid);
var cids = obj;
/// cids is array of clients. so, you can do like:
var i = 0;
var interval = setInterval(function(){
if(cids.length > i){
$.post('send_for_client.php',{id:cids[i]},function(resp){
$("#result").append(resp+"<br />");
i++;
});
} else {
clearInterval(interval);
}
},100);
});
});
});
</script>
</head>
<body>
<input id="send" type="submit" name="button" value="Send notifications" />
<div id="result">
</div>
</body>
...
I'm not tested this think, however it should work or simply show idea how you could try to find a solution for your problem. Have in mind this code can have mistakes so.. don't be lazy to check them out, not even do copy/paste :)
I hope it helped even a bit.
javascript and php are run in 2 different places. Your javascript runs in a browser while your php runs on the server. You cant really mix those two.
The way you probably want to do this is, on button click capture the click with javascript and send ajax request to your php script sitting on the server. Than have the php perform push notifications. Once php script is done, return result back to javascript to show it to the user.
You should also use javascript library like jquery which makes things much easier (especially the ajax call).

jQuery ajax returns error but data being added to database

I'm currently trying to store data into a database via ajax.
This works fine but the ajax always returns "error" even if the php code has been executing fine.
Javascript
jQuery.ajax({
type:'POST',
url:ajaxurl,
data: { game:game, variation:variation, player:player, win:win },
success: function(data){
alert('success');
},
error: function(data) {
alert('error');
}
});
PHP
<?php
include('connectdb.php');
function addNewMatch() {
$game = $_POST['game'];
$variation = $_POST['variation'];
$date = time();
$player = $_POST['player'];
$win = $_POST['win'];
$queryMatch = "INSERT INTO pd_match VALUES (
NULL,
'".$game."',
'".$variation."',
'".$date."',
'".$player."',
'".$win."'
)";
$doQueryMatch = mysql_query($queryMatch);
if (!$doQueryMatch) { return (false); } else { echo 'success'; }
} // end function addNewMatch
addNewMatch();
?>
As I said, it works fine but ajax is returning the alert("error").
I must be missing somthing.
(It's done locally on localhost)
try this
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus, errorThrown);
}
and let us know what error you are getting.
If you are using ajax you shouldn't use
<form method="POST" action="phpfile.php">
And if you are wrapping the Ajax function inside a .on('click') or .click event your buttun should be button type button instead of button type submit, like this:
<button type="button"></button>
I havn't seen your HTML but usually when I have a problem like this it's because of that.
I hope it helps.

Categories