Get done a php file with a simple click with jquery - javascript

I am Totally Newbie, i just want a very very simple example for my question.
Think i have this piece of PHP code :
<?php
echo "Test";
?>
And a piece of jquery like this :
$(document).ready(function() {
$('.div').click(function(){
$('.loading').show();
// DO PHP NOW
$('.loading').hide();
});
});
And HTML :
<div class="div">Click here</div>
I want a simple code , to connect Jquery to PHP file.
When the .div clicked, then php code get happen with No refreshing the page. Just this.
How should i do this ?
(i need a simple way to ajaxify a PHP !)
+ If i want to do Ajax, i have to write code for every every PHP code i write or one piece of Ajax code for ALL PHP codes ?
thanks

If you want to display some value from php in your div use $(".div").load("/url/to/your/php");
Or use
$.post("url/to/php",{val:val,val:val},function(callback){
alert("callback");
$(".div").html(callback);
}
Or AJAX
$.ajax({
url: "/php/code/sd.php",
type: "POST",
date: {
username: "asdasd",
password: "asdasd"
},
success: function(callback){
$(".div").html(callback);
}
});

$(function() {
$('.div').click(function(){
var $this = $(this);
$('.loading').fadeIn(200);
$.ajax({
url: 'url_to_your_file.php',
type: 'GET',
data: {},
success: function(data) {
//do smthing OR
$(data).insertAfter($this);
},
error: function(e) {
//do smthing when error
alert('Error happen!');
console.log(e);
},
complete: function(data) {
$('.loading').fadeOut(200);
}
});
});
});

Related

Why can't I toss post variable to PHP when I cover .ajax with function?

I have 3 files for showing data from myAdmin and it shows no error but after I put function around .ajax, to re-use it, I cannot pass button id to PHP. " Undefined index: btnId"
What seems wrong?
HTML file, written in PHP (below looped in for code)
print"<button class='refresh' data-name='$btnId' id='$btnId'>{$btnId}</button>";
print "<table id='$idForShowNewData' class='showNewData'></table>";
show.js
$(document).ready(function(){
$('.refresh').click(function(){
$(function showTable() {
    $.ajax({
url: "show.php",
type: "POST",
data: {
"btnId": $(this).data("name")
},
success: function(data) {
//more code
},
error: function(xhr,XMLHttpRequest,errorThrown){
//more code
}
});
});
showTable();
});
});
PHP file that get's data from myAdmin. Getting id like below is at the top of the script.
$gotBtnId = $_POST['btnId'];
this in showTable refers to window object and not the button whose data-name you want to send in the request.
If you want showTable to be invoked when the page is loaded and also be registered as a listener for click events to the refresh button, declare it as follows:
const $refreshBtn = $('button.refresh');
function showTable() {
    $.ajax({
url: "show.php",
type: "POST",
data: {
"btnId": $refreshBtn.data("name")
},
success: function(data) {
//more code
},
error: function(xhr,XMLHttpRequest,errorThrown){
//more code
}
});
});
$(function() {
showTable();
$refreshBtn.click(showTable);
});

Page is getting Submit Without Refresh Via Otp?

I got this website when I fill the information and try to send the OTP page reload
Here's the website:
https://tunisia.blsspainvisa.com/english/book_appointment.php
After you fill the information and click on (Request verification code) and you will know what I mean
What I tried is:
$(function () {
$('#tunisiaThird').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'https://tunisia.blsspainvisa.com/book_appointment.php',
data: $('#tunisiaThird').serialize(),
success: function () {
}
});
});
});
I'm only a client, so I'm using Tampermonkey to inject.
You need to read more about jquery ajax post or get method here:
https://api.jquery.com/jQuery.post/
And there are tons of questions here if you search you will find tons of examples
Here is a complete example, which is getting error messages from php part and displaying on html form.
Like this: in php : $error .= 'an error happend'; and ajax $('#result').html(data.error);
to display in html.
<div id="result"></div>
$(document).ready(function(){
$('#tunisiaThird').submit(function(event){
event.preventDefault();
var formValues = $(this).serialize();
$.ajax({
url:"book_appointment.php",
method:"POST",
data:formValues,
dataType:"JSON",
success:function(data){
if(data.error === 'ok'){
$('#result').html('Successfuly');
$('#tunisiaThird')[0].reset();
setTimeout(function() {
window.location = 'index.php';
}, 1000);
} else {
$('#result').html(data.error);
}
}
});
});
});

How to upload a HTML variable to a PHP file using AJAX

On my website I am trying to basically generate a random code (which I will set up later) and then pass that code into a PHP file to later retrieve it when the client needs it. But my code just isn't working.
Here is the code:
Javascript/HTML:
function init() {
var code = "12345";
$.ajax({
type: 'POST',
url: 'codes.php',
data: { code: code},
success: function(response) {
$('#result').html(response);
}
});
}
PHP:
<?php
$code = $_POST['code'];
echo $code
?>
So what I understand that is supposed to happen is that the code is uploaded or 'posted' to the php file and then the #result is the echo $code. None of that happens and I have no idea.
Your code working perfect with some basic changes.
You need a html element with id 'result'.
And then you need to call your init() as per requirement.
<div id="result"></div>
<script>
function init() {
var code = "12345";
$.ajax({
type: 'POST',
url: 'codes.php',
data: { code: code},
success: function(response) {
$('#result').html(response);
}
});
}
init();
</script>
I tried this on my server in the head of my document, and it worked :)
I used on complete instead of on success.
<script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script>
<script>
function init() {
$.ajax({
type: "POST",
url: "codes.php",
data: {
'code': '12345'
},
complete: function(data){
document.getElementById("result").innerHTML = data.responseText
},
});
}
init();
</script>
with codes.php the same as you have :)
just a few notes:
Make sure you point your url to the correct file. You can check it by using the console network. Or you can simply print anything out, not just the $_POST data. e.g:
echo 'Test info';
Open browser developer panel, to see if is there any client code issue. For example, document with id 'result' existed, or you have not included jquery in. The developer console will tell you everything on the client side. For Chrome, check it out here https://developer.chrome.com/devtools
Have you actually called init() ?

Javascript method similar to php file_getcontents

Is there any mehtod similar to file_getcontents in javascript or jquery.
<?php $html = file_get_contents('http://m.uploadedit.com/b037/1405919727889.txt');
echo ($html);?>
This works fine but i dont want to use php i want to jquery or javascript i have tried this method
$(document).ready(function () {
$.ajax({
url:"http://m.uploadedit.com/b037/1405919727889.txt",
type: "Get",
success: function (data) {
alert(data)
}
});
});
But i get nothing. Any recommendations?
You cannot do cross domain requests, you need to setup a php proxy, like, create a php file in your server say get_contents.php,
$html = file_get_contents('http://m.uploadedit.com/b037/1405919727889.txt');
echo ($html);
and in jquery, access your php, as:
$(document).ready(function () {
$.ajax({
url:"http://your_server.com/get_contents.php",
type: "GET",
success: function (data) {
alert(data)
}
});
});
Javascript cant get content of a file, but as you can see, php can. What I suggest to you is to work with togeter
$(document).ready(function () {
$.ajax({
url:"http://m.uploadedit.com/content/somehash",
type: "Get",
success: function (data) {
alert(data)
}
});
});
And in '/content/somehash' put a php file:
<?php echo file_get_contents('http://m.uploadedit.com/content/somehash');
I suggest you to hide the real name of filename. If you expose information like that, what do you expect if some malicious user try to http://m.uploadedit.com/content/../../.htaccess (for example). The risk is to give too many information. And it's not a good idea.
Exists an alternative and its name is NodeJs:
fs.readFile('/content/somehash', function (err, data) {
if (err) throw err;
// here you can output the content ...
});
Here is a solution. I found this and working fine
$( document ).ready(function() {
$.ajaxPrefilter(function(options) {
if(options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
//options.url = "http://cors.corsproxy.io/url=" + options.url;
}
});
$.get(
'http://m.uploadedit.com/b037/1405919727889.txt',
function(response) {
$("#content").html(response);
alert(response);
});

jquery .ajax always returns error - data being added to database

I am trying to add users to a database using jquery ajax calls. The users get added just fine to the database, but the ajax always returns with error. I'm not sure how to retrieve the specific error either. Below is my code, form, php, and jquery.
Here is the jquery
$(document).ready(function() {
//ajax call for all forms.
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
dataType: 'json',
data: form.serialize(),
success: function (response) {
alert('something');
},
error: function() {
alert('fail');
}
});
});
});
Here is the PHP
<?php
include 'class_lib.php';
if(isset($_POST['username'])) {
$user = new Users;
$user->cleanInput($_POST['username'], $_POST['password']);
if($user->insertUser()) {
echo json_encode('true');
} else {
echo json_encode('false');
}
}
Here is the HTML
<div id='newUser' class='tool'>
<h3>New User</h3>
<form method='post' name='newUser' data='../php/newUser.php'>
<span>Username</span><input type='text' name='username'><br>
<span>Password</span><input type='password' name='password'>
<input type='submit' name='submit' class='button' style='visibility: hidden'>
</form>
<span class='result'> </span>
</div>
#Musa, above you mentioned
My guess is its a parsing error, try removing dataType: 'json', and see if it works
You absolutely solved the problem I was having! My ajax post request was similar to above and it just kept returning to the 'error' section. Although I checked using firebug, the status was 200(ok) and there were no errors.
removing 'dataType:json' solved this issue for me. Thanks a lot!
Turns out I had to add async: false to the $.ajax function. It wasn't getting a response back from the php.
I know this is an old question but I have just run into a weird situation like this ( jquery ajax returns success when directly executed, but returns error when attached to button, even though server response is 200 OK )
And found that having the button inside the form tags caused JQuery to always return error. Simply changing the form tags to div solved the problem.
I believe JQuery assumes the communication should be form encoded, even though you say it is application/json.
Try moving your button outside your form and see what happens...
I had the same problem and discovery there. All the time the problem is the version of my jQuery, I had use jquery version (jquery-1.10.2.js) but this version is not Ajax stablish. So, I change version for (jquery-1.8.2.js) and this miracle heppened.
Good Luck Guy!
You should specify status Code 200 for successful response.
<?php
http_response_code(200);
?>
See here: http://php.net/manual/en/function.http-response-code.php
The first solution
Try to remove dataType in your js file like that:
$(document).ready(function() {
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
data: form.serialize(),
success: function (response) {
alert('something');
},
error: function() {
alert('fail');
}
});
});
});
The second solution
Send a real clean JSON to AJAX like that:
PHP
if(isset($_POST['username'])) {
$user = new Users;
$user->cleanInput($_POST['username'], $_POST['password']);
if($user->insertUser()) {
$error = [
"title"=> 'true',
"body"=> 'some info here ... '
];
echo json_encode($error);
} else {
$error = [
"title"=> 'false',
"body"=> 'some info here ... '
];
echo json_encode($error);
}
}
JavaScript
$(document).ready(function() {
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
dataType: 'json',
data: form.serialize(),
success: function (data) {
let x = JSON.parse(JSON.stringify(data));
console.log(x.title);
console.log(x.body);
},
error: function() {
//code here
}
});
});
});

Categories