Does anyone know why this doesn't work? any help would be appreciated.
This is the HTML
Enter Code:<br/><input type="text" name="code" id="code"/><br/>
<input type="button" id="confirm" value="Confirm" onClick="confirm()"/>
This is the PHP (basically gets the value of the user input and if it's equal to the variable a echo sucess)
$code = $_POST["code"];
$a = 105678;
if($code==$a){
echo "sucess";
} else {
echo "nosucces";
}
The JavaScript (simple ajax code to alert yay on PHP sucess or nay on no sucess)
function confirm () {
$.post(
"confirm.php",
{code:$(this).val() },
function(data) {
if(data=='sucess') {
alert("yay");
} else {
alert("nay");
}
}
);
}
basically on all occasions the ouput is nay on further debugging i tried an elseif statement on the javascript asking if data is equal to nosucces but it didn't even alert anything, meaning it's not getting the data from the php
$(document).ready(function() {
$('#confirm').click(function() {
$.post("",{code:$('#code').val() } ,function(data)
{
if(data=='sucess')
{
alert("yay");
}
else
{alert("nay");}
});
});
});
Give brackets at end, so that it does understand that you are calling a function, also don't use confirm as function name, its a native JS function, use my_confirm instead.
onClick="my_confirm()"
Also $(this).val() won't work in your case use $('#code').val() instead.
$(document).ready(function() {
$('#confirm').click(function() {
$.ajax({
url: "confirm.php",
type: "POST",
data: "code="+$('input[name="code"]').val(),
dataType: "text",
async:false,
success: function(msg){
if(msg=='sucess'){
alert('yay');
}else{
alert('nay');
}
}
});
});
});
Related
I am familiar of how to get ajax to go to a php page an execute a series of things and then return json data. However is it possible to call a specific function which resides in a given page?
Basically what I want is to reduce the number of files in a project. So I can put a lot of common functions in one page and then just call whatever the function that I want at the moment.
For AJAX request
Include jQuery Library in your web page.
For e.g.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
Call a function on button click
<button type="button" onclick="create()">Click Me</button>
While click on button, call create function in JavaScript.
<script>
function create () {
$.ajax({
url:"test.php", //the page containing php script
type: "post", //request type,
dataType: 'json',
data: {registration: "success", name: "xyz", email: "abc#gmail.com"},
success:function(result){
console.log(result.abc);
}
});
}
</script>
On the server side test.php file, the action POST parameter should be read and the corresponding value and do the action in PHP and return in JSON format e.g.
$registration = $_POST['registration'];
$name= $_POST['name'];
$email= $_POST['email'];
if ($registration == "success"){
// some action goes here under php
echo json_encode(array("abc"=>'successfuly registered'));
}
You cannot call a PHP function directly from an AJAX request, but you can do this instead:
<? php
function test($data){
return $data+1;
}
if (isset($_POST['callFunc1'])) {
echo test($_POST['callFunc1']);
}
?>
<script>
$.ajax({
url: 'myFunctions.php',
type: 'post',
data: { "callFunc1": "1"},
success: function(response) { console.log(response); }
});
</script>
As a structure for this kind of purposes, I suggest this:
PHP
<?php
if(isset($_POST['action'])){
if ($_POST['action'] == "function1") { func1(); }
if ($_POST['action'] == "function2") { func2(); }
if ($_POST['action'] == "function3") { func3(); }
if ($_POST['action'] == "function4") { func4(); }
}
function func1(){
//Do something here
echo 'test';
}
?>
jQuery
var data = { action: 'function1' };
$.post(ajaxUrl, data, function(response) {
if(response != "") {
$('#SomeElement').html(response);
}else{
alert('Error, Please try again.');
}
});
As mentioned, you can't call a PHP function directly from an AJAX call.
If I understand correctly, yes you can.
Put all your functions in one php file and have the ajax pass as a parameter which one you want to call. Then with a switch or if structure, execute the one you want.
jquery:
$(document).ready(function(){
$('#tfa_1117700').change(function(){
var inputValue = $(this).val();
var v_token = "{{csrf_token()}}";
$.post(
"{{url('/each-child')}}",
{ dropdownValue: inputValue,_token:v_token },
function(data){
console.log(data);
$('#each-child-html').html(data);
}
);
});
});
php:
public function EachChild(Request $request)
{
$html ="";
for ($i=1; $i <= $request->dropdownValue; $i++)
{
$html = $i;
}
echo $html;
}
I am validating a form with ajax and jquery in WordPress post comments textarea for regex. But there is an issue when i want to alert a error message with return false. Its working fine with invalid data and showing alert and is not submitting. But when i put valid data then form is not submit. May be issue with return false.
I tried making variable and store true & false and apply condition out the ajax success block but did not work for me.
Its working fine when i do it with core php, ajax, jquery but not working in WordPress .
Here is my ajax, jquery code.
require 'nmp_process.php';
add_action('wp_ajax_nmp_process_ajax', 'nmp_process_func');
add_action('wp_ajax_nopriv_nmp_process_ajax', 'nmp_process_func');
add_action('wp_head', 'no_markup');
function no_markup() {
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('form').submit(function (e) {
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}
}
});
return false;
});
});
</script>
<?php
}
And i'm using wordpress wp_ajax hook.
And here is my php code.
<?php
function nmp_process_func (){
$comment = $_REQUEST['comment'];
preg_match_all("/(->|;|=|<|>|{|})/", $comment, $matches, PREG_SET_ORDER);
$count = 0;
foreach ($matches as $val) {
$count++;
}
echo $count;
wp_die();
}
?>
Thanks in advance.
Finally, I just figured it out by myself.
Just put async: false in ajax call. And now it is working fine. Plus create an empty variable and store Boolean values in it and then after ajax call return that variable.
Here is my previous code:
require 'nmp_process.php';
add_action('wp_ajax_nmp_process_ajax', 'nmp_process_func');
add_action('wp_ajax_nopriv_nmp_process_ajax', 'nmp_process_func');
add_action('wp_head', 'no_markup');
function no_markup() {
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('form').submit(function (e) {
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}
}
});
return false;
});
});
</script>
<?php
}
And the issue that i resolved is,
New code
var returnval = false;
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
async: false, // Add this
data: 'action=nmp_process_ajax&comment=' + comment,
Why i use it
Async:False will hold the execution of rest code. Once you get response of ajax, only then, rest of the code will execute.
And Then simply store Boolean in variable like this ,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
returnval = false;
} else {
returnval = true;
}
}
});
// Prevent Default Submission Form
return returnval; });
That's it.
Thanks for the answers by the way.
Try doing a ajax call with a click event and if the fields are valid you submit the form:
jQuery(document).ready(function () {
jQuery("input[type=submit]").click(function (e) {
var form = $(this).closest('form');
e.preventDefault();
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: {'action':'nmp_process_ajax','comment':comment},
success: function (res) {
var count = parseInt(res);
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
} else {
form.submit();
}
}
});
});
});
note : you call need to call that function in php and return only the count!
Instead of submitting the form bind the submit button to a click event.
jQuery("input[type=submit]").on("click",function(){
//ajax call here
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}else{
jQuery("form").submit();
}
}
});
return false;
})
Plus also its a good idea to put return type to you ajax request.
Let me know if this works.
this question has been asked before but the answers seem not to work on me. My Ajax returns the whole page when i perform a autocomplete search
ajax to search from database
$(function(){ $(".search_keyword").keyup(function() {
var search_keyword_value = $(this).val();
var dataString = 'search_keyword='+ search_keyword_value;
if(search_keyword_value!='')
{
$.ajax({
type: "POST",
url: "/ajax/search.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
} else{
document.getElementById('result').innerHTML ='';
}
return false; });
html page
<form method="get" action="/?page=results" class="navbar-form" autocomplete="off">
<input type="text" name="query" class="search_keyword"/>
<button type="submit" nam>Search</button>
</form>
<div id="result"></div>
would really appreciate the help Guys
check whether the page you are calling correct path or not...
due to 404 error only, it will returns whole page. may be the ajax url not found
The url used in ajax should be used to return(echo) the required data only, nothing else.
I've usually resolve this problem passing a 'action' POST to to php page wich contains what i would like to request from it and it gets selected with a switch.
The php code usually looks like this:
if(isset($_POST["action"]))
{
switch(action){
case "func_1":
func_1();
break;
case "func_2":
func_2();
break;
case "func_2":
func_3();
break;
case "func_2":
func_4();
break;
}
} else {
echo "error";
}
function func_1{
//do something
}
function func_2{
//do something
}
function func_3{
//do something
}
function func_4{
//do something
}
Inside the function I write the desired code, like getting autocompletion data, then echo it wia json, or something.
Also, the ajax 'data' tag capable to do html post/get paramteres via prebuilding a string:
$.ajax({
type: "POST",
url: "/ajax/search.php",
data:
{
search_keyword : search_keyword_value
}
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
I have the following AJAX script, but for some reason the var ok it's not returning true or false so the form can continue:
function ajax_call(email,title,url){
var email = document.getElementById("email").value;
var title = document.getElementById("title").value;
var url = document.getElementById("url").value;
var parametros = {"emaail":email, "tiitle":title, "uurl":url};
var ok = true;
$.ajax({
data: parametros,
url: 'validate.php',
type: 'post',
error: function () {
alert("An error has occurred! Try Again!");
},
success: function (response) {
if(response == 'bien') { ok = true; } else { $("#ajax_cal").html(response); ok = false; }
}
});
return ok;
}
HTML:
<form onsubmit="return ajax_call();">
...
</form>
PHP:
<?php
//////....
if(!empty($errors)) {
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
}
} else { echo 'bien'; }
?>
Everything works good, except for the return value.
Thanks in advance.
Prevent the submit completely, send the ajax request, then if it's good, submit the form.
HTML:
<form id="myform">
...
</form>
JavaScript:
$("#myform").submit(function(e){
// prevent submit
e.preventDefault();
var email = document.getElementById("email").value;
var title = document.getElementById("title").value;
var url = document.getElementById("url").value;
var parametros = {"emaail":email, "tiitle":title, "uurl":url};
$.ajax({
data: parametros,
url: 'validate.php',
type: 'post',
context: this,
error: function () {
alert("An error has occurred! Try Again!");
},
success: function (response) {
if($.trim(response) == 'bien') {
this.submit(); // submit, bypassing jquery bound event
}
else {
$("#ajax_call").html(response);
}
}
});
});
You are returning ok at the end of your function. This is returned before your ajax request is sent and completed.
You cannot rely on the return value of your function, you should do something inside your "success" part. It basically depends on what you want to do with your return value
I'm a complete newbie to jquery but in some of the scripts I've been working on I've had to prefix the 'response' you have.
For instance...
if(response.tiitle == 'bien') { ok = true; } else { $("#ajax_cal").html(response); ok = false; }
Also be aware you have double letters in your "parametros" but I'm sure that was intentional (i.e. tiitle and not title etc).
The Question is pretty direct. I have two variables in JS. I want to pass these to a php file first to update a database, and then return back to the original file, a true or false value based on the query. How do i do this?
Consider the PHP file for checking existing username as:
<?php
if(mysql_num_rows(mysql_query($query)) === 1)
die('true');
else
die('false');
?>
In your HTML File, you can call this way (using jQuery):
<script type="text/javascript">
function checkUsername()
{
$.ajax({
url: 'checkuser.php?username' = $('#username').val(),
success: function(data) {
if(data == 'true')
alert('Username Available!'); // User Exists!
else
alert('Username not Available!'); // User not Exist!
}
});
}
</script>
And in HTML:
<input type="text" name="username" id="username" />
Check
Hope this helps! :)
HTML
<'input type = "TEXT" Id="TEXTTOPARSE">
<'Span id="ResultVAlue>
On Load of the Page
$(document).ready(function(){
$('#TEXTTOPARSE').bind('onChange', function(){
var val = $(this).val();
updatePage(val);
});
});
function updatePage(value){
$.ajax({
method:"POST",
url:"YourPageLink"
data:{"textValue" : value},
success: function(data){
$('#ResultVAlue').html(data);
}
});
}