how to pass a variable with the help of ajax jquery into a function directly, which is on another page - ajax

how to pass a variable with the help of ajax jquery into a function directly, which is on another page
function show_data2(str1) {
xml2http = new XMLHttpRequest();
xml2http.onreadystatechange = function () {
if (xml2http.readyState === 4 && xml2http.status === 200) {
document.getElementById("show_data_sal").innerHTML = xml2http.responseText;
}
};
xml2http.open("POST", "functions.php?r=" + str1, true);
xml2http.send(str1);
};
functions.php
class querydb
{
function useHere()
{
...I want to use that variable 'r' here.
}
}

If you are using jQuery, this will be the easiest way to send post data via ajax:
var jqxhr = $.ajax( {
method: "POST",
url: "functions.php",
data: { r: "some value", s: "another value" }
})
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
function.php
class querydb
{
function useHere()
{
// We're sending our post data as json so we'll need php to decode it for us to use.
$foo = json_decode($_POST[], true);
// you can now access your variables like an array
$bar = $foo['r'];
}
}
Just be sure to clean anything from post before you do anything with it to prevent any malicious parameters coming through

Related

Worpress bad request 400 pure Javascript

I get this following error when I use ajax in pure javascript:
"POST http://localhost:8888/website/wp-admin/admin-ajax.php" 400 (Bad Request) line in code: this.xhr.send(JSON.stringify(data));
my Contact.js file:
var Contact = function(data){
//setups and others methods
this.onFormSent = function(data){
data = {
action: 'my_action',
data: data
};
if(this.ajaxSendURL !== null){
this.xhr.open("post", this.ajaxSendURL);
this.xhr.setRequestHeader("Content-Type", "application/json");
this.xhr.onload = function() {
if(self.xhr.status === 200){
console.log(self.xhr.responseText);
var response = JSON.parse(self.xhr.responseText);
self.onSuccessForm(data);
}
};
this.xhr.send(JSON.stringify(data));
}
};
};
I use a form tag in html after filled my "form" and pressed the submit button it should call 'my_action' in php.
this my function.php:
function add_theme_scripts() {
wp_enqueue_script('Contact', get_template_directory_uri() . '/js/Contact.js', array(), 1.0, true);
wp_localize_script('Contact', 'ajaxurl', admin_url('admin-ajax.php'));
}
add_action('wp_enqueue_scripts', 'add_theme_scripts');
/* AJAX */
add_action('wp_ajax_my_action', 'my_action');
add_action('wp_ajax_nopriv_my_action', 'my_action');
function my_action(){
echo 'msg from server:' + $_POST['data']['name'];
die();
}
What am I doing wrong?
Updated: replaced by the following code and it works
this.onFormSent = function(data){
data = "action=my_function&name=" + dada.name;
this.xhr.setRequestHeader("Content-Type", "application/json");
...
}
Change this lines in ajax request;
data = {
action: 'my_action',
data: youdatadata
};
var data = $.param(data);
http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
http.send(data);

Youtube-data API "part" request parameter doesn't accept "player" as the value

https://developers.google.com/youtube/v3/docs/videos#resource
The link above says I can set the part attribute in the request to be "player". But when I do this, I get a bad response.
My code is below:
$("form").on("keyup", function (e) {
e.preventDefault();
// prepare the request
if ($('#search').val() === '') {
$('#results').html("");
} else {
var request = gapi.client.youtube.search.list({
part: "snippet",
type: "video",
q: encodeURIComponent($("#search").val()).replace(/%20/g, "+"),
maxResults: 10,
videoEmbeddable: true,
order: "viewCount",
publishedAfter: "2000-01-01T00:00:00Z"
});
// execute the request
request.execute(function (response) {
var results = response.result;
$("#results").html("");
$.each(results.items, function(index, item) {
$("#results").append('<span>' + item.player.embedHtml + '</span>');
});
});
resetVideoHeight();
$(window).on("resize", resetVideoHeight);
}
});
});
The link your referring is for videos endpoint, but your code using search endpoint. The search endpoint only accept snippet.
https://developers.google.com/youtube/v3/docs/search#resource

jQuery.ajax() inside a loop [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
If I call jQuery.ajax() inside a loop, would it cause the call in current iteration overwrite the last call or a new XHR object is assigned for the new request?
I have a loop that do this, while from console log I can see requests done 200 ok but just the result data of the last request in the loop is stored by the request success callback as supposed .
the code:
var Ajax = {
pages: {},
current_request: null,
prefetch: function () {
currentPath = location.pathname.substr(1);
if(this.pages[currentPath])
{
var current = this.pages[currentPath];
delete this.pages[currentPath];
current['name']=currentPath;
current['title']=$("title").text().replace(' - '.SITE_NAME, '');
current['meta_description']=$("meta[name=description]").attr('content');
current['meta_keywords']=$("meta[name=keywords]").attr('content');
}
var _Ajax = this;
//the loop in question *****
for(var key in this.pages)
{
$.ajax({
method: 'get',
url:'http://'+location.hostname+'/'+key,
success: function(data) {
_Ajax.pages[key] = data;
}
});
console.debug(this.pages);
}
if(current)
{
this.pages[currentPath] = current;
}
}
};//Ajax Obj
for(var i in pages)
{
Ajax.pages[pages[i]]={};
}
$(function() {
Ajax.prefetch();
});//doc ready
You'll need a closure for key:
for(var k in this.pages){
(function(key){
$.ajax({
method: 'get',
url:'http://'+location.hostname+'/'+key,
success: function(data) {
_Ajax.pages[key] = data;
}
});
console.debug(this.pages);
})(k);
}
that way you make sure that key is always the correct on in each ajax success callback.
but other than that it should work
i made a small closure demonstration using timeout instead of ajax but the principle is the same:
http://jsfiddle.net/KS6q5/
You need to use async:false in you ajax request. It will send the ajax request synchronously waiting for the previous request to finish and then sending the next request.
$.ajax({
type: 'POST',
url: 'http://stackoverflow.com',
data: data,
async: false,
success: function(data) {
//do something
},
error: function(jqXHR) {
//do something
}
});
I believe what's happening here has to do with closure. In this loop:
for(var key in this.pages)
{
$.ajax({
method: 'get',
url:'http://'+location.hostname+'/'+key,
success: function(data) {
_Ajax.pages[key] = data;
}
});
console.debug(this.pages);
}
The variable key is actually defined outside the for loop. So by the time you get to the callbacks, the value has probably changed. Try something like this instead:
http://jsfiddle.net/VHWvs/
var pages = ["a", "b", "c"];
for (var key in pages) {
console.log('before: ' + key);
(function (thisKey) {
setTimeout(function () {
console.log('after: ' + thisKey);
}, 1000);
})(key);
}
I was facing the same situation, I solved using the ajax call inside a new function then invoke the function into the loop.
It would looks like:
function a(){
for(var key in this.pages)
{
var paramsOut [] = ...
myAjaxCall(key,paramsOut);
.......
}
}
function myAjaxCall(paramsIn,paramsOut)
{
$.ajax({
method: 'get',
url:'http://'+location.hostname+'/'+paramsIn[0],
success: function(data) {
paramsOut[key] = data;
}
});
}
This is how I always do a ajax loop..
I use a recursive function that gets called after the xhr.readyState == 4
i = 0
process()
function process() {
if (i < 10) {
url = "http://some.." + i
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
alert(xhr.responseText)
i++
process()
}
}
xhr.send();
} else {
alert("done")
}
}

AJAX Form Validation to see if course already exist always return true

I want to validate my course name field if the course name inputted already exist using AJAX, but my ajax function always return the alert('Already exist') even if i inputted data that not yet in the database. Please help. Here is my code. Thanks.
View:
<script type="text/javascript">
var typingTimer;
var doneTypingInterval = 3000;
$('#course_name').keyup(function(){
typingTimer = setTimeout(check_course_name_exist, doneTypingInterval);
});
$('#course_name').keydown(function(){
clearTimeout(typingTimer);
});
function check_course_name_exist()
{
var course_name=$("#course_name").val();
var postData= {
'course_name':course_name
};
$.ajax({
type: "POST",
url: "<?php echo base_url();?>/courses/check_course_name_existence",
data: postData,
success: function(msg)
{
if(msg == 0)
{
alert('Already Exist!');
return false;
}
else
{
alert('Available');
return false;
}
return false;
}
});
$("html, body").animate({ scrollTop: 0 }, 600);
return false;
}
</script>
Controller:
function check_course_name_existence()
{
$course_name = $this->input->post('course_name');
$result = $this->course_booking_model->check_course_name_exist($course_name);
if ($result)
{
return true;
}
else
{
return false;
}
}
Model:
function check_course_name_exist($course_name)
{
$this->db->where("course_name",$course_name);
$query=$this->db->get("courses");
if($query->num_rows()>0)
{
return true;
}
else
{
return false;
}
}
You could use console.log() function from firebug. This way you will know exactly what the ajax returns. Example:
success: function(msg) {
console.log(msg);
}
This way you also know the type of the result variable.
jQuery, and Javascript generally, does not have access to the Boolean values that the PHP functions are returning. So either they return TRUE or FALSE does not make any difference for the JS part of your code.
You should try to echo something in your controller and then make your Javascript comparison based on that value.

Make a if loop according to what returns the ajax html(data)

I want to make a if loop according to what returns html(data), so how can I get in my ajax script a var returned by "form_treatment.php" ? I want to close the colorbox (a lightbox) containing myForm only if "form_treatment.php" returns a var PHP with a "true" value.
$('#myForm').submit(function() {
var myForm = $(this);
$.ajax({
type: 'POST',
url: 'form_treatment.php',
data: myForm.serialize(),
success: function (data) {
$('#message').html(data);
// Make a if loop according to what returns html(data)
}
});
return false;
});
form.php :
<form method="post" action="form_treatment.php" >
<input type="text" name="user_name" value="Your name..." />
<button type="submit" >OK</button>
</form>
form_treatment.php :
if ( empty($_POST['user_name']) ){
$a = false;
$b = "Name already used.";
} else {
$already_existing = verify_existence( $_POST['user_name'] );
// verification in the DB, return true or false
if( $already_existing ){
$a = false;
$b = "Name already used.";
} else {
$a = true;
$b = "Verification is OK";
}
}
Try adding dataType : 'json' inside your $.ajax() call, and then, in your php file, respond with nothing but a json object such as:
{ "success" : true, "msg" : 'Verification is OK' }
Then, inside your $.json() success function, you can access anything from the server's response like so:
if (data.success) {
alert(data.msg);
}
I know you said you want to loop, but that's just an example. Note that PHP has a great little function called json_encode() that can turn an array into a json object that your JavaScript will pick up just fine.
$('#myForm').submit(function() {
var myForm = $(this);
$.ajax({
type: 'POST',
url: 'form_treatment.php',
data: myForm.serialize(),
success: function (data) {
// if data is a variable like '$a="Verification is OK"':
eval(data);
if ($a == 'Verification is OK')
$("#colorBox").close() // or whatever the close method is for your plugin
else
$('#message').html($a);
}
});
return false;
});
The var "data" is the response being passed back from your PHP file. Therefore, you can do something like:
...success: function (data) {
if (data == 'Verification is OK') {
// Make a if loop according to what returns html(data)
}
}
You just have to make a simple comparison in your success function in the ajax request, like this:
success: function (data) {
$('#message').html(data);
if(data == 'Verification is OK')
{
// make the lightbox show
}
}

Resources