I am having trouble figuring out how to get the following done.
click on a paragraph element
send a .post request using jQuery
get the sent data from the server to display in the paragraph
I've searched quite a bit and tried using some of the solutions proposed but it failed.
Here's my folder structure:
+ html
- index.html
+ js
- eventhandling.js
+ php
- test.php
HTML
<div class="channel" id="channel1">
<p class="title">CHANNEL 01</p>
<p class="stb_sub_menu" id="model">STB Model</p>
<p class="network_sub_menu" id="network">Network</p>
<p class="smartcard_sub_menu" id="smartcard">Smartcard</p>
<p id="reboots">Reboots</p>
</div>
<p id="demodata">Demo Data</p>
PHP
<?php echo "PHP script -> You called master?"; ?>
JS
$(".channel").click(function(){
/*alert(I am clicked");*/
$.post('test.php', {name: 'John'}, function(data) {
$("#demodata").val("data");
});
});
The click event is successful because the alert pops up. Nothing shows on the Firebug console window.
Might be the service URL you passed into post is wrong (according to the folder structure).
The code must be like this.
$(".channel").click(function(){
var postData = {"name":"john"};
$.ajax({
type: "POST",
url: '../php/test.php',
data: postData ,
contentType: "application/json",
dataType: "json",
processdata: true,
success: function (response) {
},
error: function(error){
}
});
});
This will work for you.
$(".channel").click(function(){
/*alert(I am clicked");*/
$.post('test.php', {name: 'John'}, function(data) {
$("#demodata").text(data);
});
});
Related
Hi everyone i am trying to use ajax in wordpress and got stuck in something. My code is giving me an error in console as
jquery-3.3.1.js:9600 GET http://localhost/wordpress/wp-admin/admin-ajax.php 400 (Bad Request)
send # jquery-3.3.1.js:9600
ajax # jquery-3.3.1.js:9206
(anonymous) # main.js?ver=1:27
dispatch # jquery-3.3.1.js:5183
elemData.handle # jquery-3.3.1.js:4991
I looked into the source and it is showing me the error on this line
xhr.send( options.hasContent && options.data || null );
This is my jquery
$('#retrieve_users').click(function() {
$.ajax({
type: "GET",
url: scriptData.ajaxurl,
action : 'retrieveUsersData',
dataType: "html", //expect html to be returned
success: function(response)
{
$("#users_data").html(response);
//alert(response);
}
});
});
This is my php code in functions.php file
function retrieveUsersData(){
echo "ajax responding";
}
add_action('wp_ajax_retrieveUsersData','retrieveUsersData');
add_action('wp_ajax_nopriv_retrieveUsersData', 'retrieveUsersData');
and this is my html
<button id="retrieve_users">Watch Users</button>
<div id="users_data"></div>
Please help!! I didnt know how to import jquery src link in wordpress using wp_enque_scripts so i pasted the with jquery src directly in html. I hope its not creating problem
Please help.. i would really appreciate it. Thank you
Change your code to use POST and in the body of the request use the action key :
jQuery.ajax({
url: scriptData.ajaxurl,
type: "POST",
dataType: 'html',
data: {
action: 'retrieveUsersData'
},
...
});
Also you should use wp_die() in the function to prevent the 0 to be echoed.
function retrieveUsersData(){
echo "ajax responding";
wp_die();
}
So I am trying to post some some data from one PHP file to another PHP file using jquery/ajax. The following code shows a function which takes takes data from a specific div that is clicked on, and I attempt to make an ajax post request to the PHP file I want to send to.
$(function (){
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
const sha_obj = JSON.stringify({"sha": sha_id});
$.ajax({
url:'commitInfo.php',
type:'POST',
data: sha_obj,
dataType: 'application/json',
success:function(response){
console.log(response);
window.location.replace("commitInfo");
},
error: function (resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
Then on inside the other php file 'commitInfo.php' I attempt to grab/print the data using the following code:
$sha_data = $_POST['sha'];
echo $sha_data;
print_r($_POST);
However, nothing works. I do not get a printout, and the $_POST array is empty. Could it be because I am changing the page view to the commitInfo.php page on click and it is going to the page before the data is being posted? (some weird aync issue?). Or something else? I have tried multiple variations of everything yet nothing truly works. I have tried using 'method' instead of 'type', I have tried sending dataType 'text' instead of 'json'. I really don't know what the issue is.
Also I am running my apache server on my local mac with 'sudo apachectl start' and running it in the browser as 'http://localhost/kanopy/kanopy.php' && 'http://localhost/kanopy/commitInfo.php'.
Also, when I send it as dataType 'text' the success function runs, but I recieve NO data. When I send it as dataType 'json' it errors. Have no idea why.
If anyone can help, it would be greaat!
You don't need to JSON.stringify, you need to pass data as a JSON object:
$(function() {
$(".commit").on('click', function() {
const sha_id = $(this).data("sha");
const sha_obj = {
"sha": sha_id
};
$.ajax({
url: 'commitInfo.php',
type: 'POST',
data: sha_obj,
dataType: 'json',
success: function(response) {
console.log(response);
},
error: function(resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
And on commitInfo.php, you have to echo string on json format
=====================================
If you want to redirect to commitInfo.php you can just:
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
window.location.replace("commitInfo.php?sha=" + sha_id );
});
I know this seems kind of vague, but it was the best way I could put this into words. Below is the example of my code.
JavaScript
<script type="text/javascript">
var name = $('#firstName').val();
var email = $('#userEmail').val();
var json = { Email: email, FirstName: name };
var string = JSON.stringify(json);
$.ajax({
url: 'http://uBuildRewards.api/api/Users/GetInfo',
type: 'GET',
contentType: 'application/json',
dataType: "json",
crossDomain: true,
data: string
});
</script>
HTML
<div class="user-logged-in">
<div class="content">
<div class="user-name" id="firstName"> **NAME HERE** <span class="text-muted f9">admin</span></div>
<div class="user-email" id="userEmail"> **EMAIL HERE** </div>
<div class="user-actions">
<a class="m-r-5" href="">settings</a> logout
</div>
</div>
</div>
Before all this, in another view I have similar JavaScript code that is doing my login. Which is accessing a method from the UsersController that gets all information, and if email and pass is correct it logs me in. Then, this method, is when I am logged in I want it to say that Welcome, (name of user logged in as) and your current email address is (who ever I am logged in as).
So I am trying to find out how, from the javascript, to paste the info retrieved from the 'GetInfo' method, and display the Name and Email where I put "NAME HERE and EMAIL HERE"
I tried to be as descriptive as I possibly could. Sorry for any confusion. I greatly appreciate your help in advance :) Still fairly new to JQuery and JavaScript!
why are you sending login credentials over http and not https (SSL)?
That aside...
You have to use .done method.
$.ajax({
url: 'http://uBuildRewards.api/api/Users/GetInfo',
type: 'GET',
contentType: 'application/json',
dataType: "json",
crossDomain: true
}).done(function(data) {
console.log("Sample of data:", data);
$('#firstName').text(data.name);
$('#userEmail').text(data.email);
});
I'm trying to create a test script for a small little website I'm doing, and it requires a lot of troubleshooting with this particular form. In order to get a response, I need to fill out 5 step form wizard and then wait for the results. I've been trying to create a small little script I can use on a seperate page to test my php functions in a heartbeat. Here is what I have so far, and it doesn't seem to even post to the page.
<div id="response"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
var data = {
console: "playstation",
game: "FIFA14",
coinamount: "10000",
team: "Some Team Name",
league: "Some League Name",
player: "Some Player Name",
quality: "Silver",
chemistry: "Basic",
position: "CAM",
customername: "Joey Small",
customeremail: "jsmall#email.com",
customerphonenumber: "23454343534",
payment: "pp"
}
$.ajax({
type: "POST",
url: "order.php",
data: data,
cache: false,
contentType: false,
processData: false,
success: function(data){
$("#response").html(data);
}
});
});
</script>
I'm inspecting the network data in my browser, and it is not sending to order.php. I don't have much love for javascript, especially Jquery, so any help would be greatly appreciated.
first thing you should do is close the script tag on your Jquery include at the top
Ok, so the additional options added on to the end are what is making the script not submit.
$.ajax({
type: "POST",
url: "order.php",
data: data,
success: function(data){
//alert("---"+data);
$("#response").html(data);
}
});
That works correctly. Daedalus's comment got me to thinking about the additional tags, and how they are not needed.
I´m building a social network with Grails and got stucked
on giving users inner their editprofile
page the chance to paste an youtube-Url into a textfield and by clicking a button a JS regexxes the id out of the URL pasted, an ajax post is fired updating a div with a preview image of the youtube video
the html looks like :
<g:textField name="videoinput" class="videoinput reLef" value="" />
<span class="daten_videouploadbtn reLef" ></span>
<g:render template="/forms/storedVideos" />
the JS looks like :
$('.daten_videouploadbtn').click(function() {
var string = document.editProfileForm.videoinput.value;
var neu = string.replace(/http[s]?:\/\/(?:[^\.]+\.)*(?:youtube\.com\/(?:v\/|watch\?(?:.*?\&)?v=|embed\/)|youtu.be\/)([\w\-\_]+)/i, '$1');
var id = RegExp.$1;
jQuery.ajax({
type:'POST',
data:RegExp.$1,
url:'${createLink(action: 'addVideo')}',
success:function(data,textStatus){jQuery('#storedvideos').html(data);},
error:function(XMLHttpRequest,textStatus,errorThrown){}
});
});
the controller looks like :
def addVideo() {
def videoitems = !!%%-- HOW TO PARSE YOUTUBE-ID HERE -%%!!
render(template:"/forms/storedVideos", model: [newVideo:videoitems])
}
and stored videos looks :
<div id="storedvideos"><span><img src="http://img.youtube.com/vi/${newVideo}/default.jpg" width="225px" height="130px"/></span></div>
i just dont get it how to catch the data of the Ajax Post and update the div with the preview image with the id inside,
can someone give a hint ? it is killing me
You should post the data like this:
jQuery.ajax({
type: 'POST',
data: { value: RegExp.$1 },
...
After that you can access the posted data inside your grails controller with params.value.
I got this working on Grails 2.0.4:
Javascript/Ajax
var data =
{requestId: 12456,
node: "node1",
host: "mynode.com"};
$.ajax({
url: '/myurl',
data: JSON.stringify(data),
type: 'post',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function() ...
},
error: function() ...
}
});
In Grails....
def service(){
def jsonObj = request.JSON
}
I like this approach because request.JSON parses the data and returns a ready to use object.