Sending form data with extra parameters through Ajax? - javascript

I am trying to send a post request with the form data as well as some other parameters to my Codeigniter controller. This is the code I am using.
function onSignIn(googleUser) {
console.log('onto the function');
var profile = googleUser.getBasicProfile();
var google_name = profile.getName();
var google_image = profile.getImageUrl();
var google_email = profile.getEmail();
console.log('got the details');
console.log('submitting');
var title = ('#title').val();
var message = ('#message').val();
$.ajax({
type: "POST",
url: 'http://localhost/review/submit',
data: {
title,
message,
'google_name': google_name,
'google_email': google_email,
'google_image': google_image,
},
success: function () {
alert('fuck');
}
});
}
I keep getting $ is not defined and I have no idea why that is, cause when I remove $ it gives me #title.val() is not a function.

Make sure you are giving jquery reference with correct path to your code
Include bellow CDN link in your head section of code
https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js

Related

Dynamic html elements show only when going through debugger

I'm working on project that simulates Twitter and I'm using HTML + JS on client and WCF services on server side (ajax calls), and Neo4J as database.
For example:
in $(document).ready(function ()
there is DisplayTweets service call -> DisplayTweets(username)
function DisplayTweets(userName) {
$.ajax(
{
type: "GET", //GET or POST or PUT or DELETE verb
url: "Service.svc/DisplayTweets", // Location of the service
data: { userName: userName },
contentType: "application/json; charset=utf-8", // content type sent to server
dataType: "json",
processdata: true, //True or False
success: function (msg) //On Successfull service call
{
DisplayTweetsSucceeded(msg);
},
error: function () // When Service call fails
{
alert("DISPLAY TWEETS ERROR");
}
}
);
}
and then DisplayTweetsSucceeded(msg) where msg would be json array of users tweets
function DisplayTweetsSucceeded(result)
{
for (var i = 0; i < result.length; i++)
{
var tweet = JSON.parse(result[i]);
var id_tweet = tweet.id;
var content_tweet = tweet.content;
var r_count_tweet = tweet.r_count;
NewTweet(null, id_tweet, content_tweet, r_count_tweet);
}
}
Function NewTweet is used for dynamic generating of tweets.
Problem is when I first load html page, nothing shows up, neither when I load it multiple times again. It only shows when I go through Firebug, line by line.
I'm presuming that maybe getting data from database is slower, but I'm not sure and also have no idea how to solve this. Any help will be very much appreciated, thank you in advance!

jQuery $.ajax succeed but serv doesn't receive any data

I work on a pagination system that wouldn't reload the whole page but just refresh the contents.
I retrieve the requested page with the value contained in a ID and want to send it to the server for the process.
The success is reached but my php script does not recognize the $_POST['page'] value.
Here is the JS:
$(document).ready(function()
{
$('#containerWrapper').on('click', '.holder a', function (event) {
var page = $(this).attr('id');
var url = "cart.php";
event.preventDefault();
// Launch of the Ajax query to refresh the current page
$.ajax({
url: "cart.php",
type: "POST",
data: {page: page},
success: function()
{
alert('Success, delivered page: ' + page);
$('#containerWrapper').load(url + " #containerWrapper");
}
});
});
});
Here the PHP, which i think isn't the real problem:
if (isset($_POST['page']) && ($_POST['page'])>0 && ($_POST['page'])<= $nbPages)
{
$cPage = htmlspecialchars($_POST['page']);
}
I've ready many topics but haven't found any relative problem for the now.
You really have too much code, it is not necessary for your purposes to bury a load() statement in an AJAX call. You could simply do this -
$(document).ready(function(){
$('#containerWrapper').on('click', '.holder a', function (event) {
event.preventDefault();
var url = "cart.php";
var page = $(this).attr('id');
$('#containerWrapper').load(url + " #containerWrapper", {page: page});
});
});
load() does allow you to send data to the requested page via a second arguement.

How to get json data from javascript file

help, im using tumblr and connect my twitter account, Tumblr gave me this file example:http://titan-theme.tumblr.com/tweets.js
my question is can i get follower_count and screen_name data? if yes how to get it?
please help me
thanks
If you have only this file you should define *recent_tweets* function. Of cours you need to import tweets.js. For example:
<script>
var recent_tweets = function(tweets) {
for(var i=0; i<tweets.length; i++) {
var tweet = tweets[i];
var followerCounts = tweet.user.followers_count;
var screenName = tweet.user.screen_name;
}
}
</script>
<script src="tweets.js"></script>
However, there is no follower_count available.
This is a JSONP file, it needs to be requested via a script tag in order to execute the recent_tweets function that encloses it. Try using the jQuery ajax function.
$.ajax({
dataType: "jsonp",
success: function (result) {
callback(result);
}
});

Calling Javascript Functions In Order

I'm trying to use a button to perform an API Call to Flickr, like so:
$(document).ready(function (){
$('#goButton').click(function (){
makeAPICall();
});
});
This works as expected, but the communication between the client and the Flickr API takes a while to execute, so the page appears like it is hung. I would like to add a "Working Notice" that is displayed immediately on button click to let the user know that their action is processing.
To do this, I added an H1 tag:
<h1 id="notice"></h1>
and a function that changes the inner HTML to display a notice:
function workingNotice() {
document.getElementById("notice").innerHTML="I am getting your results";
}
But when I try to edit the code for the button to something like this:
$(document).ready(function (){
$('#goButton').click(function (){
workingNotice();
makeAPICall();
});
})
The Working Notice is never displayed until the API Call has completed, which defeats the purpose.
I then tried using:
$(document).ready(function (){
$('#goButton').click(function (){
$.when(
workingNotice()
).then(
makeAPICall()
);
});
})
This gives the exact same results, where the Working Notice is not called until the API Call completes. Is there any alternative that I can try to force the order of these functions to comply?
UPDATE/EDIT:
While I found the solution to the initial problem in another answer, I know there's a reasonable chance the delay in the API Call processing is due to some mistake in this function. Here is the code for makeAPICall:
//call Flickr api and look for tags matching user search term
function makeAPICall(){
//get value tag from team 1 search box
var searchTag1 = escape(document.getElementById("searchTag1").value);
//get value tag from team 2 search box
var searchTag2 = escape(document.getElementById("searchTag2").value);
//build api call url with searchTag1
var url1 = "http://api.flickr.com/services/rest/?"
+ "method=flickr.photos.search&api_key=XXX&tags="
+ searchTag1 + "&sort=interestingness-desc"
+ "&safe_search=1&has_geo=1&format=json&nojsoncallback=1";
//build api call url with searchTag1
var url2 = "http://api.flickr.com/services/rest/?"
+ "method=flickr.photos.search&api_key=XXX&tags="
+ searchTag2 + "&sort=interestingness-desc"
+ "&safe_search=1&has_geo=1&format=json&nojsoncallback=1";
//make call to flickr api
$.when(
$.ajax({
dataType: "json",
url: url1,
async: false,
success : function(callReturn1) {
callData1 = callReturn1;
numResults1 = parseInt(callData1.photos.total);
}
}),
$.ajax({
dataType: "json",
url: url2,
async: false,
success : function(callReturn2) {
callData2 = callReturn2;
numResults2 = parseInt(callData2.photos.total);
}
})
).then(
drawChart()
);
}
Note "callData1", "callData2", "numResults1" & "numResults2" are all global.
If your makeAPICall is not async - call it out of bounds:
workingNotice();
setTimeout(makeAPICall, 1);

Execute php url with JS

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