how to pass jquery variable one page to another? - php

index.php
<script>
$(document).ready(function() {
$("#submit").click(function() {
var field = $("#field").val();
$("#popular_colleges" ).load( "xyz.php");
$("#popular_colleges").on( "click", ".pagination a", function (e){
e.preventDefault();
$("imagen").show();
var page = $(this).attr("data-page");
$("#popular_colleges").load("xyz.php",{"page":page}, function(){
$("imagen").hide();
});
});
});
</script>
xyz.php
//another page code
Here I having two pages i.e. index.php and xyz.php now I want to post index.php page variable (var field) to xyz.php. How can I do this ? can anyone help me please ?
Thank You

To post var field = $("#field").val(); from index.php to xyz.php you have to use the jquery ajax(). To use this you have to include the jquery library in your page and its syntax is like:
$.ajax({
url : 'xyz.php',
method : 'post',
data : {
field: field
// key: value pair
},
success: function(response){
// here response in the response you get from xyz.php
}
});
xyz.php: you can get the posted value like:
$field = $_POST['field'];

You can use $.get(), or $.post(), or the more powerful and complex $.ajax().
For a simple value called page, get or post should be sufficient:
$.post('/path/to/other-page.php', {page: page}, function(data){
console.log(data); // what your other page returned
});

Related

Wordpress Form Not Submitting Data

I am working on wordpress site, i created custom form, in which i am getting voucher code and after validating this code , submitting this form to another url , defined in form action, here is jquery for this work,
<script type="text/javascript">
$( document ).ready(function() {
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
$( "#submit_btn_redeem" ).click(function(event) {
event.preventDefault();
var form = $("#form-voucher");
var voucher_code = $("#voucher_code").val();
var btn = $(this);
if(voucher_code!=""){
$("#voucher_code").removeClass("error-fld");
btn.prop('disabled', true);
btn.attr("disabled","disabled");
$(".loading").show();
var action_data = {
'action': 'check_voucher_code',
'voucher_code': voucher_code
};
$.ajax({
type: 'POST',
url: ajaxurl,
data: action_data,
dataType: 'json',
success: function (response) {
$(".loading").hide();
btn.prop('disabled',false);
btn.removeAttr("disabled");
if(response.status==1){
$(".response").html(response.message);
$(".response").show().delay(2000).hide(0);
alert($("#voucher_code").val());
//return false;
setTimeout(function(){
document.getElementById("form-voucher").submit();
}, 1000);
}else{
$("#voucher_code").addClass("error-fld");
$(".response").html(response.message);
$(".response").show().delay(3000).hide(0);
}
}
});
}else{
$("#voucher_code").addClass("error-fld");
}
});
});
</script>
Problem is when it submit on given url , it is first redirect to 301 with POST method, then again generate GET request with no parameter and sumitted to that url, I have dumped $_REQUEST on action url, not getting any data here, i have also check .htaccess and redirect plugin, there is no such url exists for redirection, the question is submitting form with post method redirect, while with GET method its work fine, any body can help
You need to defined the action function in your function.php file in your theme, which will look something like this
add_action( 'wp_ajax_nopriv_check_voucher_code', 'functiontohook' );
add_action( 'wp_ajax_check_voucher_code', 'functiontohook' );
After that you need to specify the action in you ajax request which you have done. In functiontohook you can get your all json data and do anything that you want to do. Let me know if anything is not clear. I hope this will help you out.

data passing on the same page using ajax

I am stuck while passing the input values to same page for that i used Ajax but it is not happening and here my ajax function not working and i think its all because of URL given in the below code.
Just tell me, what should I insert in url section so that I can pass the values on the same page.
Please suggest your thoughts on the same.
$(document).on('submit', '#saveForm', function()
{
var data = $(this).serialize();
$.ajax({
type : 'POST',
url : 'index.php',
data : data,
success : function(data)
{
$("#saveForm").fadeOut(500).hide(function()
{
$(".result").fadeIn(500).show(function()
{
$("#demo").html(data);
});
});
}
});
return false;
});

Show/hide div with jQuery and AJAX not working properly

I'm trying to show a specific div depending on the result of a SQL query.
My issue is that I can't get the divs to switch asynchronously.
Right now the page needs to be refreshed for the div to get updated.
<?php
//SQL query
if (foo) {
?>
<div id="add<?php echo $uid ?>">
<h2>Add to list!</h2>
</div>
<?php
} else {
?>
<div id="remove<?php echo $uid ?>">
<h2>Delete!</h2>
</div>
<?php
}
<?
<script type="text/javascript">
//add to list
$(function() {
$(".plus").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "ajax_add.php",
data: info,
success: function(data){
$('#add'+I).hide();
$('#remove'+I).show();
}
});
return false;
});
});
</script>
<script type="text/javascript">
//remove
$(function() {
$(".minus").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "ajax_remove.php",
data: info,
success: function(data){
$('#remove'+I).hide();
$('#add'+I).show();
}
});
return false;
});
});
</script>
ajax_add.php and ajax_remove.php only contain some SQL queries.
What is missing for the div #follow and #remove to switch without having to refresh the page?
"I'm trying to show a specific div depending on the result of a SQL query"
Your code doesn't seem to do anything with the results of the SQL query. Which div you hide or show in your Ajax success callbacks depends only on which link was clicked, not on the results of the query.
Anyway, your click handler is trying to retrieve the id attribute from an element that doesn't have one. You have:
$(".plus").click(function(){
var element = $(this);
var I = element.attr("id");
...where .plus is the anchor element which doesn't have an id. It is the anchor's containing div that has an id defined. You could use element.closest("div").attr("id") to get the id from the div, but I think you intended to define an id on the anchor, because you currently have an incomplete bit of PHP in your html:
<a href="#" class="plus" ?>">
^-- was this supposed to be the id?
Try this:
<a href="#" class="plus" data-id="<?php echo $uid ?>">
And then:
var I = element.attr("data-id");
Note also that you don't need two separate script elements and two document ready handlers, you can bind both click handlers from within the same document ready. And in your case since your two click functions do almost the same thing you can combine them into a single handler:
<script type="text/javascript">
$(function() {
$(".plus,.minus").click(function(){
var element = $(this);
var I = element.attr("data-id");
var isPlus = element.hasClass("plus");
$.ajax({
type: "POST",
url: isPlus ? "ajax_add.php" : "ajax_remove.php",
data: 'id=' + I,
success: function(data){
$('#add'+I).toggle(!isPlus);
$('#remove'+I).toggle(isPlus);
}
});
return false;
});
});
</script>
The way i like to do Ajax Reloading is by using 2 files.
The first: the main file where you have all your data posted.
The second: the ajax file where the tasks with the db are made.
Than it works like this:
in the Main file the user lets say clicks on a button.
and the button is activating a jQuery ajax function.
than the ajax file gets the request and post out (with "echo" or equivalent).
at this point the Main file gets a success and than a response that contains the results.
and than i use the response to change the entire HTML content of the certain div.
for example:
The jQuery ajax function:
$.ajax({
type: 'POST', // Type of request (can be POST or GET).
url: 'ajax.php', // The link to the Ajax file.
data: {
'action':'eliran_update_demo', // action name, used when one ajax file handles many functions of ajax.
'userId':uId, // Simple variable "uId" is a JS var.
'postId':pId // Simple variable "pId" is a JS var.
},
success:function(data) {
$("#div_name").html(data); // Update the contents of the div
},
error: function(errorThrown){
console.log(errorThrown); // If there was an error it can be seen through the console log.
}
});
The PHP ajax function:
if (isset($_POST['action']) ) {
$userId = $_POST['userId']; // Simple php variable
$postId = $_POST['postId']; // Simple php variable
$action = $_POST['action']; // Simple php variable
switch ($action) // switch: in case you have more than one function to handle with ajax.
{
case "eliran_update_demo":
if($userId == 2){
echo 'yes';
}
else{
echo 'no';
}
break;
}
}
in that php function you can do whatever you just might want to !
Just NEVER forget that you can do anything on this base.
Hope this helped you :)
if you have any questions just ask ! :)

My ajax/jquery script to send $_GET to php isn't working? (Wordpress)

This is the code that I'm using to send a variable (via GET) to another php file:
(basically, I click on a button, and then js gets the id and sends the id via ajax to the php file.
$(document).ready(function() {
$(".doClick").click(function() {
var category=$(this).attr('id');
$.ajax({
url:'aFile.php',
type:'GET',
data: $category,
success: function(data){
alert("It worked?"); // this is the response
}
});
alert($(this).attr("id"));
});
});
This is the code in my aFile.php:
The php file gets the info via $_GET[] and then assigns it to a variable and uses that variable in a function call.
<head>
<script type="text/javascript">
$(document).ready(function() {
function JS() {
//code
});
</script>
</head>
<body onload="JS()">
<?php
$category = $_GET['category'];
if (function_exists('inventory_insert')) {
echo inventory_insert('{category_name = '.$category.'}');
} else echo('warning');
?>
It's supposed to give me a response back on my main page, but nothing seems to be happening. I don't even get the alert I posted after the ajax script.
your variable is category but you're sending data: $category
You must send key/value pair to server
to receive $_GET['category'] your data sent in ajax needs to be either:
data: 'category='+category
Or
data: {category: category}
You have assigned id into category in jquery. so correct in data params.
data: {category : category},
Send it in this way to server or php file.
$(document).ready(function() {
$(".doClick").click(function() {
var category=$(this).attr('id');
$.ajax({
url:'aFile.php',
type:'GET',
data: {category : category},
success: function(data){
alert("It worked?"); // this is the response
}
});
alert($(this).attr("id"));
});
});

Execute php script with JS [duplicate]

Is it possibe to simply load a php script with a url with js?
$(function() {
$('form').submit(function(e) {
e.preventDefault();
var title = $('#title:input').val();
var urlsStr = $("#links").val();
var urls = urlsStr.match(/\bhttps?:\/\/[^\s]+/gi);
var formData = {
"title": title,
"urls": urls
}
var jsonForm = JSON.stringify(formData);
$.ajax({
type: 'GET',
cache: false,
data: { jsonForm : jsonForm },
url: 'publishlinks/publish'
})
//load php script
});
});
Edit:
function index() {
$this->load->model('NewsFeed_model');
$data['queryMovies'] = $this->NewsFeed_model->getPublications();
$this->load->view('news_feed_view', $data);
}
simple
jQuery and:
<script>
$.get('myPHP.php', function(data) {});
</script>
Later edit:
for form use serialize:
<script>
$.post("myPHP.php", $("#myFormID").serialize());
</script>
like this ?
$.get('myPHP.php', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
There are various ways to execute a server side page using jQuery. Every method has its own configuration and at the minimum you have to specify the url which you want to request.
$.ajax
$.ajax({
type: "Get",//Since you just have to request the page
url:"test.php",
data: {},//In case you want to provide the data along with the request
success: function(data){},//If you want to do something after the request is successfull
failure: function(){}, //If you want to do something if the request fails
});
$.get
$.get("test.php");//Simplest one if you just dont care whether the call went through or not
$.post
var data = {};
$.post("test.php", data, function(data){});
You can get the form data as a json object as below
var data = $("formSelector").searialize();//This you can pass along with your request

Categories