how to use ajax in jQuery in javascript - javascript

I want to post javascript variable to another php file and I search using Ajax may help.I want to get back the data on another php file by "post" method.But I can't use $.ajax({}) directly inside javascript:
function input() {
$.ajax({
url : 'update_service.php',
type : 'POST',
data : {
name: name,
},
success : function(response) {
alert(response);
}
});
The error message said "unexpected function ajax()". How to fix it?

JQuery Version
$.post( "update_service.php", function( data ) {
alert( "Data Loaded: " + data );
});

Related

Wp_admin ajax request returns with response "0"

I am new to code, and trying to learn things by doing them.
Currently, I am trying to do something very simple using wordpress. which I am trying to create some posts in wordpress, using some external data.
I can fetch the data using CURL. No problem with that and post it using Wp_insert_post, directly.
But, What I want to do is trigger the wp_insert_post function on click of a button in the admin panel ( I have created this as a plugin and a separate plugin dashboard, where the button Is embedded). I have been messing around with the code, and sending the data to wp-admin-ajax.php work fine, and gives the response code 200. But, the response receiving is "0" . if the data passed through are correct, I presume, the response should be "1" ?
I have the following code at the moment.
//Button
<form id="formtesting">
<input type="text" id="name" placeholder="Name">
<input type="submit" id="user-submit" value="user-submit">
//Ajax Call
$(document).ready(function() {
var userSubmitButton = document.getElementById('user-submit');
var adminAjaxRequest = function(formData, myaction) {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/wpdevelopment/wp-admin/admin-ajax.php',
data: {
action: myaction,
data: formData
},
success: function(response) {
if (true === response.success) {
alert('success');
} else {
alert(response);
}
}
});
};
userSubmitButton.addEventListener('click', function(event) {
event.preventDefault();
var formData = {
'name': document.getElementById('name').value
};
adminAjaxRequest(formData, 'data_submission');
});
});
And here is my test function // to test whether the function initiate properly, i try to send a Json error, So then I can include wp_insert_post details.
function data_submission(){
wp_send_json_error( 'I am an error' );}
add_action( 'wp_ajax_data_submission', 'data_submission' );
add_action( 'wp_ajax_nopriv_data_submission', 'data_submission' );
Could not locate where the faulty is. Some help would be appriciated
tks
Use add_action(' wp_ajax_myaction', 'yours_callback_fanc');
wp_ajax_
Remain part is yours action name that is defined into yours ajax call. In yours case it's myaction.
First this is not a standard way to use ajax in wordpress,
use wp_localize_script for embedding the global ajax_url variable,
wp_register_script('plugin-ajaxJs', plugins_url('/js/ajax-call.js', __FILE__));
wp_enqueue_script('plugin-ajaxJs');
wp_localize_script('plugin-ajaxJs', 'my_ajax_url', array('ajax_url' => admin_url('admin-ajax.php')));
Now as url in ajax you can add my_ajax_url.ajax_url,
this will send a request to admin-ajax.php.
Now coming to your question
you are returning an wp_json_error so the result is 0,
use this and return whatever data you wants in ajax success,
$responce['result'] = 1
wp_send_json( $response );

Send variable from Javascript to PHP using AJAX post method

I am trying to pass a variable from javascript to php, but it doesn't seem to be working and I can't figure out why.
I am using a function that is supposed to do three things:
Create a variable (based on what the user clicked on in a pie chart)
Send that variable to PHP using AJAX
Open the PHP page that the variable was sent to
Task one works as confirmed by the console log.
Task two doesn't work. Although I get an alert saying "Success", on test.php the variable is not echoed.
Task three works.
Javascript (located in index.php):
function selectHandler(e) {
// Task 1 - create variable
var itemNum = data.getValue(chart.getSelection()[0].row, 0);
if (itemNum) {
console.log('Item num: ' + itemNum);
console.log('Type: ' + typeof(itemNum));
// Task 2 - send var to PHP
$.ajax({
type: 'POST',
url: 'test.php',
dataType: 'html',
data: {
'itemNum' : itemNum,
},
success: function(data) {
alert('success!');
}
});
// Task 3 - open test.php in current tab
window.location = 'test.php';
}
}
PHP (located in test.php)
$item = $_POST['itemNum'];
echo "<h2>You selected item number: " . $item . ".</h2>";
Thanks to anyone who can help!
From what i can tell you don't know what ajax is used for, if you ever redirect form a ajax call you don't need ajax
See the following function (no ajax):
function selectHandler(e) {
// Task 1 - create variable
var itemNum = data.getValue(chart.getSelection()[0].row, 0);
if (itemNum) {
console.log('Item num: ' + itemNum);
console.log('Type: ' + typeof(itemNum));
window.location = 'test.php?itemNum='+itemNum;
}
}
change:
$item = $_GET['itemNum'];
echo "<h2>You selected item number: " . $item . ".</h2>";
or better you do a simple post request from a form like normal pages do :)
Try this:
success: function(data) {
$("body").append(data);
alert('success!');
}
Basically, data is the response that you echoed from the PHP file. And using jQuery, you can append() that html response to your body element.
you should change this code
'itemNum' : itemNum,
to this
itemNum : itemNum,
Seems contentType is missing, see if this helps:
$.ajax({
type: 'POST',
url: 'test.php',
dataType: "json",
data: {
'itemNum' : itemNum,
},
contentType: "application/json",
success: function (response) {
alert(response);
},
error: function (error) {
alert(error);
}
});
you can easily pass data to php via hidden variables in html for example our html page contain a hidden variable having a unique id like this ..
<input type="hidden" id="hidden1" value="" name="hidden1" />
In our javascript file contains ajax request like this
$.ajax({
type: 'POST',
url: 'test.php',
data: {
'itemNum' : itemNum,
}
success: function (data) {
// On success we assign data to hidden variable with id "hidden1" like this
$('#hidden1').val(data);
},
error: function (error) {
alert(error);
}
});
Then we can access that value eighter on form submit or using javascript
accessing via Javascript (Jquery) is
var data=$('#hidden1').val();
accessing via form submit (POST METHOD) is like this
<?php
$data=$_POST['hidden1'];
// remaining code goes here
?>

JQuery loading from the current html another html and check a submit of this one

I am triying to check if a submit is clicked in some other html in order to load an image by ajax in the current html, but I think that submit can not be located.
Ajax function to put image:
function sync_vitrasa(id){
$.ajax({
url: "/vitrasa_state/",
type:"GET",
data: {
id: id,
},success: function( data ) {
id="#zv"+id;
$(id).html(data);
}
});
}
Ajax function that call the last one and check the submit in another HTML:
$(document).ready(function() {
$.ajax({
url : '/vitrasa/',
success : function(data){
if($('#sub2').click()){
alert( "calling Ajax." );
sync_vitrasa(2);
}
}
});
});
PD: the url vitrasa_state call a controller function(in django views.py) that returns the image or not

Sending the body of a page to another server?

Is it possible to send the body of a page (i.e. all of the HTML code/DOM) from a page on one server to another and then receive a response? The method used doesn't really matter, but I do have access to jQuery functions if that helps.
You could do this by sending...
$("html").html();
...in an ajax call:
var data = $("html").html();
$.ajax({
url: "/echo/json/",
data: data,
type: "POST"
}).done(function(res) {
console.log(res);
});
Working jsFiddle: http://jsfiddle.net/brandonscript/p5zEW/
(See console for body output).
Something like this should work:
$.get( "somePage.html",
function( pageData ) {
$.post("targetPage.php", pageData, function( data ) {
alert("Done!");
},
"html"
);
});

Getting JSON response from the server but can't display as HTML with Jquery

I'm building a mobile app and i build a PHP API that renders data from a mysql db and encode it as JSON
i call this api with Jquery ajax to get to display the records from the json output as JSONP and render it in my document in the success function.
so far i get the JSON correctly when i do the request via $.ajax and i can see the data in the Response in my firebug but in the other side the ajax function fires the ERROR not the Success.
i have a demo code in here :jsfidle
this is my $.ajax Call:
$(document).on("pageinit","#myPage", function() {
$("#autocomplete").on("listviewbeforefilter", function ( e, data ) {
var $ul = $( this ),
$input = $( data.input ),
value = $input.val(),
html = "";
$ul.html( "" );
var dataString = 'keyword='+value;
if (value.length > 2 ) {
$.mobile.loading("show");
$.ajax({
type: "GET",
url: "http://example.com/search.php",
dataType: "jsonp",
jsonpCallback: 'jsonpCallback',
cache:true,
data: dataString,
success: function(data) {
$.mobile.loading("hide");
alert(data);
}
})
}
});
});
if you check the net panel you 'll find it successful and there is data coming.
Kindly Advise.
Thanks A lot
Your response is not including the callback jsonpCallback() in the response, the response I'm seeing is simply
({"name": ... })

Categories

Resources