Execute PHP code on form submit without text input - javascript

I just want to know if it is possible to execute a PHP post request with ajax by click on a form submit button that does not have any text input. Say i have a form
<form action="connecting.php" id="connect" method="post" enctype="multipart/form-data">
<input type="submit" name="userconnect" id="userconnect" value="connect">
</form>
And i want to execute this block of php code on submit button
connecting.php
<?php
require_once ("db.php");
$db = new MyDB();
session_start();
if (isset($_POST['userconnect']))
{
$my_id = htmlspecialchars($_SESSION['log_id'], ENT_QUOTES, 'UTF-8');
$user_id = (int) htmlspecialchars($_SESSION['userid'], ENT_QUOTES, 'UTF-8');
$rand_num = rand();
$hsql =<<<EOF
SELECT COUNT(hash) as count FROM connect WHERE (user_one = '$my_id' AND user_two = '$user_id') OR (user_two = '$my_id' AND user_one = '$user_id');
EOF;
$hret = $db->querySingle($hsql);
if ($hret == 1)
{
echo "<script>alert('You are already connected to this user')</script>";
}
else
{
$usql = $db->prepare("INSERT INTO connect (user_one, user_two, hash) VALUES (:my_id, :user_id, :rand_num)");
$usql->bindValue(':my_id', $my_id, SQLITE3_INTEGER);
$usql->bindValue(':user_id', $user_id, SQLITE3_INTEGER);
$usql->bindValue(':rand_num', $rand_num, SQLITE3_TEXT);
$uret = $usql->execute();
if (!$uret)
{
echo "Error connecting";
}
else
{
echo "Connection Sucessful";
}
}
}
This is the ajax request i am trying to use
$("#connect").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "connecting.php",
data: $(this).serializeArray(), //the data is an issue cause of no text input in for
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(response) {
}
});
});
This doesn't work because there is no data in the form for ajax to send but all data are in the PHP file. How do i execute the php file with ajax. Is there any way?

You dont have to send a POST request to a PHP script in order for it to execute. You can send a normal GET to a URL that executes a PHP script and send you back the JSON data you are looking for. That way, you dont have to send data with the post request and you can still run your PHP script.
Edit*
Another thing you can do is add a hidden ID field or some random text and send that with the POST as data. You dont have to do anything with it, it could just be a time stamp, but it will send the POST request. This is of course overhead and not my kind of programming, but an option nonetheless.

Yes it is possible.... you need to harness a click event...
for example if you had a div element like so:
<div id='mybutton'>click me</div>
then you could use code like this to do literally whatever you want when the button is clicked.:
$('#mybutton').on('click',function(){
$.post...
});
BONUS INFO:
You could also hijack the form submit event like so:
$('#form#myform').on('submit',function(e){
e.preventDefault(); //stop before page is reloaded with post headers
$.post...
});
You don't actually need a form event though, you can just $.get to a php url and return the html or json it generates. just check out the jquery documentation on $.get()

Related

Send php request onclick via ajax

I know this question have been asked alot but none of the answer are related to my case ,I have a button ,onclick it should call a javascript function send it a php variable,and ajax would call a php file via post and send that vriable and the php file updates my table
so here is the onclick event first
<button class="button button6 " onclick="incrementclicks('<?php echo $id; ?>');">increment</button>
it should send a variable called $id to the javascript function
<script type="text/javascript">
function incrementclicks(id) {
$.ajax({
url: "increment.php",
data: "id=" + id,
type: "POST"
});
}
</script>
and the php file increment.php (I'm 100% sure it connects to the server just fine )
<?php
require_once 'dbconnect.php';
$db_handle = new DBController();
$id=$_POST["id"];
$q="UPDATE clicks SET linkclicks = linkclicks + 1 WHERE id = '".$id."'";
$result = mysql_query($q);
?>
it doesn't increment, I don't understand what did i do wrong here
First of all you can debug your code on the php by doing
echo $id;
exit();
My quess is that your are missing something there..
Use this method of ajax to check the issue.And if error found check in console for the issue
$.ajax({
url: "increment.php",
type: "post", //send it through post method
data: {
id:id
},
success: function (response) {
alert("success");
},
error: function (xhr) {
//Do Something to handle error
alert("some error found");
}
});
NB:Try to add type="button" to your button for not to reload
<button class="button button6 " onclick="incrementclicks(5);" type="button">increment</button>
I just want to answer this if anyone have future problems like this
The problem is I forgot to add script src at the beginning
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
after adding this my code worked just fine :)

Post on native php (without framework) Into Code Igniter using AJAX

I'm trying to post data on my HTML code to CI with Ajax. But I got no response?
Here is my JS Code
$(document).ready(function(){
$("#simpan").click(function(){
nama_pelanggan = $("#nama_pelanggan").val();
telp = $("#telp").val();
jQuery.ajax({
type: "POST",
url: "http://192.168.100.100/booking_dev/booking/addBookingViaWeb/",
dataType: 'json',
data : {
"nama_pelanggan":nama_pelanggan,
"telp":telp,
},
success: function(res) {
if (res){
alert(msg);
}
}
});
});
});
And here is my form
<form>
Nama Pelanggan <br>
<input type="text" name="nama_pelanggan" id="nama_pelanggan"><br>
Telepon<br>
<input type="text" name="telp" id="telp"><br>
<input type="button" name="simpan" id="submit" value="Simpan">
</form>
and here is my contoller function code
public function addBookingViaWeb(){
$data = array(
'nama_pelanggan' => $this->input->post('nama_pelanggan'),
'telp'=>$this->input->post('telp')
);
echo json_encode($data);
}
Here is my post param
But I got no response
any idea?
add method in from if you use post then
<form method="post" action ="" >
Try using JQuery form serialize() to declare which data you want to post. It automatically put your form input into ajax data. Example :
first set ID to your form tag
<form id="form">
then
$.ajax({
type:'POST',
url : 'http://192.168.100.100/booking_dev/booking/addBookingViaWeb/',
data:$('#form').serialize(),
dataType:'JSON',
success:function(data){
console.log(data);
}
});
First problem I see is in your ajax submission code. Change
$("#simpan").click(function(){
to
$("#submit").click(function(event){
Notice that I added the event parameter. You now need to prevent the default submission behavior. On the first line of your click method add
event.preventDefault();
Now I'm assuming that your url endpoint http://192.168.100.100/booking_dev/booking/addBookingViaWeb/ can handle POST requests. Usually this is done with something like PHP or Ruby on Rails. If I was doing this in PHP I would write something like the following:
<?php
$arg1 = $_POST["nama_pelanggan"];
$arg2 = $_POST["telp"];
// do something with the arguments
$response = array("a" => $a, "b" => $b);
echo json_encode($response);
?>
I personally don't know anything about handling POST requests with js (as a backend) but what I've given you should get the data over there correctly.
I got solution for my problem from my friend xD
just add header("Access-Control-Allow-Origin: *"); on controller function
Thank you for helping answer my problem.

Receiving data in Ajax for a Div

So this one problem has taken me on a wild goose chase for a week or so now and I am really hoping that the problem will finally be able to be solved tonight. I'm not at all experienced with Ajax or JS so I really struggle here and am still learning. Here is what I hope to achieve...
I have a basic PHP messaging system in messages.php showing all messages between two users within a DIV which automatically adds a scroll bar when you receive more messages. Here is my DIV which does this:
<div class="list-group-message" style="overflow-y: scroll;height:385px;width:680px">
<div id="content">
/// PHP MESSAGE SCRIPT
</div>
</div>
When you send a reply, it uses this Ajax script to send that data to be processed on system/reply_system.php if it notices you are talking to an automated account, it will also send the data to system/sars_system.php to be processed, this works fine for adding, and sending back messages...
<script>
setInterval(function() {
$("#content").load(location.href+" #content","");
}, 5000);
</script>
<script>
function loadDoc() {
$.ajax({
url: 'system/reply_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
success: function(data) {
console.log("success");
var $content = $(".list-group-message");
$content.text(data); // Here you have to insert the received data.
$content[0].scrollTop = $content[0].scrollHeight;
// Second ajax
$.ajax({
url: 'system/sars_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
success: function(data) {
$content.text(data); // Here you have to insert the received data.
$content[0].scrollTop = $content[0].scrollHeight;
},
error: function(e) {
//called when there is an error
console.log('fail');
}
});
},
error: function(e) {
//called when there is an error
console.log('fail');
}
});
}
</script>
The nice gent who helped me with this script has informed me that I need to receive data back from system/sars_system.php and system/reply_system.php which basically look like this:
<?
require 'db.php';
$message = $_POST['message'];
$conversation_id = $_POST['conversation_id'];
$sarssystem = $_POST['sarssystem'];
$user_id = $_POST['user_id'];
$usr_message = str_replace("'","\\'",$message);
mysqli_query($conn,"INSERT INTO ap_messages (message_id, message, sender_id, time_sent, time_read, conversation_id)
VALUES ('','$usr_message','$user_id', NOW(), NOW(), '$conversation_id')");
mysqli_query($conn, "UPDATE ap_conversations SET time = NOW() WHERE conversation_id = '$conversation_id'");
echo json_encode('success');
?>
But I am having a real big problem trying to figure out how to do that or what data I even need to send back or how I go about coding that in to the current script? If this all works, the final aim is to automatically initiate sending the scroll bar to the very bottom of the page every time this Ajax script runs?
The ajax looks right because it is ready to receive data. In the php you can set the data to whatever you need, it could be the results of the database call. Here's a small example of sending some data back to the ajax script.
$data = array(
'status' => 'ok',
'message' => 'Customer account saved',
);
return json_encode($data);
If you know how to get whatever data you need on the server you can encode it and return it to the client.
The success method will run on the ajax object. It is passed the data and you can reference and manipulate/use it. Your code looks like it is already prepared for this:
success: function(data) { // <-- this is the data in json format from the server
console.log("success");
var $content = $(".list-group-message");
$content.text(data); // Here you have to insert the received data.

Echo PHP message after AJAX success

I have a modal that will display when the user clicks a delete button. Once they hit the delete button I am using AJAX to subimit the form. Eveything works fine, but it is not display my success message which is set in PHP.
Here is my AJAX code:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function () {
// This is empty because i don't know what to put here.
}
});
}
Here is the PHP code:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
} else {
$errors[] = lang("SQL_ERROR");
}
And then I call it like this:
<div class="col-lg-12" id="resultBlock">
<?php echo resultBlock($errors,$successes); ?>
</div>
When I use AJAX it does not display the message. This works fine on other pages that does not require AJAX to submit the form.
I think you are getting confused with how AJAX works, the PHP script you call will not directly output to the page, consider the below simplified lifecycle of an AJAX request:
Main Page -> Submit Form -> Put form data into array
|
--> Send array to a script to be processed on the server
|
|----> Callback from the server script to modify DOM (or whatever you want to do)
There are many callbacks, but here lets discuss success and error
If your PHP script was not found on the server or there was any other internal error, an error callback is returned, else a success callback is fired, in jQuery you can specify a data array to be received in your callback - this contains any data echoed from your PHP script.
In your case, you should amend your PHP file to echo your arrays, this means that if a successful request is made, the $successes or $errors array is echoed back to the data parameter of your AJAX call
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo $successes;
} else {
$errors[] = lang("SQL_ERROR");
echo $errors;
}
You can then test you received an object by logging it to the console:
success: function(data) {
console.log(data);
}
Well, it's quite not clear what does work and what does not work, but two things are bothering me : the function for success in Ajax is empty and you have a header function making a refresh in case of success. Have you tried removing the header function ?
success: function(data) {
alert(data);
}
In case of success this would alert the data that is echoed on the php page. That's how it works.
I'm using this a lot when I'm using $.post
Your header will not do anything. You'll have to show the data on the Java script side, maybe with alert, and then afterwards redirect the user to where you want in javascript.
you need put some var in success function
success: function(data) {
alert(data);
}
then, when you read var "data" u can do anything with the text
Here is what I changed the PHP to:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo resultBlock($errors,$successes);
} else {
$errors[] = lang("SQL_ERROR");
echo resultBlock($errors,$successes);
}
And the I changed the AJAX to this:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function (data) {
result = $(data).find("#success");
$('#resultBlock').html(result);
}
});
}
Because data was loading all html I had to find exactly what I was looking for out of the HTMl so that is why I did .find.

From a running PHP Code, how to update status in DIV tag

I have a web Page, in which i an downloading data one after another in a loop. After each data download is finished i want to update the status to a DIV tag in the Web Page. How can i do this. Connecting to server and downloading data via php code and the div tag is within the .phtml page.
i have tried
echo "
<script type=\"text/javascript\">
$('#tstData').show();
</script>
";
But the echo statement update will happen at the end only. Refreshing of DIV tag need to happen at the end of each download.
Use jQuery load()
$('#testData').load('http://URL to script that is downloading and formatting data to display');
$("#save_card").submit(function(event) {
event.preventDefault();
var url = "card_save.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
dataType:"json",
data: $("#save_card").serialize(), // serializes the form's elements.
success: function(data)
{
console.log(data);
if(data.msg=="success")
{
$("#submit_msg").html("Thank You !!!");
console.log("Record has been Inserted Successfully!!!");
}
else
{
$("#submit_msg").html(data.er);
console.log("There Is Some Error");
}
$("#submit_msg").show();
setTimeout(function() { $("#submit_msg").hide(); }, 5000);
$("#save_card").get(0).reset();
}
});
return false; // avoid to execute the actual submit of the form.class_master
});
Use This Ajax function to call PHP function to get data. Here
#save_card = Id of the form that you want to submit.
url = action for the form or the location to the php file from where your data is coming.
data: $("#save_card").serialize() = it is sending all the data of the form in serialize form. Data can be created manually to do this repalce this line with data: {'name':name,'year':year}
function(data) = here data is returned from the php code in json formate.
data.msg = It is a way to access different field from data.
$user_email = $_REQUEST['user_email'];
$cat_id = $_REQUEST['category'];
$title = $_REQUEST['title'];
$country = $_REQUEST['country'];
$date = date("Y-m-d H:i:s");
$sql = "INSERT INTO project(title, user_email, cat_id, country, start_date) VALUES ('$title','$user_email','$cat_id','$country', '$date')";
if (mysql_query($sql)) {
$project_id = mysql_insert_id();
echo json_encode(array('project_id' => $project_id, 'msg' => 'Successfully Added', 'status' => 'true'));
} else {
echo json_encode(array('msg' => 'Not Added', 'status' => 'false'));
}
PHP code to send data in json format

Categories